title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http://www.refactoring.com/catalog/splitLoop.html">split loop</a> refactoring in mind), looks rather bloated:</p> <p>(alt 1)</p> <pre><code>r = xrange(1, 10) twos = 0 threes = 0 for v in r: if v % 2 == 0: twos+=1 if v % 3 == 0: threes+=1 print twos print threes </code></pre> <p>This looks rather nice, but has the drawback of expanding the expression to a list:</p> <p>(alt 2)</p> <pre><code>r = xrange(1, 10) print len([1 for v in r if v % 2 == 0]) print len([1 for v in r if v % 3 == 0]) </code></pre> <p>What I would really like is something like a function like this:</p> <p>(alt 3)</p> <pre><code>def count(iterable): n = 0 for i in iterable: n += 1 return n r = xrange(1, 10) print count(1 for v in r if v % 2 == 0) print count(1 for v in r if v % 3 == 0) </code></pre> <p>But this looks a lot like something that could be done without a function. The final variant is this:</p> <p>(alt 4)</p> <pre><code>r = xrange(1, 10) print sum(1 for v in r if v % 2 == 0) print sum(1 for v in r if v % 3 == 0) </code></pre> <p>and while the smallest (and in my book probably the most elegant) it doesn't feel like it expresses the intent very well.</p> <p>So, my question to you is:</p> <p>Which alternative do you like best to gather these types of stats? Feel free to supply your own alternative if you have something better.</p> <p>To clear up some confusion below:</p> <ul> <li>In reality my filter predicates are more complex than just this simple test.</li> <li>The objects I iterate over are larger and more complex than just numbers</li> <li>My filter functions are more different and hard to parameterize into one predicate</li> </ul>
13
2008-10-01T10:37:20Z
157,099
<p>Not as terse as you are looking for, but more efficient, it actually works with any iterable, not just iterables you can loop over multiple times, and you can expand the things to check for without complicating it further:</p> <pre><code>r = xrange(1, 10) counts = { 2: 0, 3: 0, } for v in r: for q in counts: if not v % q: counts[q] += 1 # Or, more obscure: #counts[q] += not v % q for q in counts: print "%s's: %s" % (q, counts[q]) </code></pre>
0
2008-10-01T10:56:46Z
[ "python", "list-comprehension" ]
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http://www.refactoring.com/catalog/splitLoop.html">split loop</a> refactoring in mind), looks rather bloated:</p> <p>(alt 1)</p> <pre><code>r = xrange(1, 10) twos = 0 threes = 0 for v in r: if v % 2 == 0: twos+=1 if v % 3 == 0: threes+=1 print twos print threes </code></pre> <p>This looks rather nice, but has the drawback of expanding the expression to a list:</p> <p>(alt 2)</p> <pre><code>r = xrange(1, 10) print len([1 for v in r if v % 2 == 0]) print len([1 for v in r if v % 3 == 0]) </code></pre> <p>What I would really like is something like a function like this:</p> <p>(alt 3)</p> <pre><code>def count(iterable): n = 0 for i in iterable: n += 1 return n r = xrange(1, 10) print count(1 for v in r if v % 2 == 0) print count(1 for v in r if v % 3 == 0) </code></pre> <p>But this looks a lot like something that could be done without a function. The final variant is this:</p> <p>(alt 4)</p> <pre><code>r = xrange(1, 10) print sum(1 for v in r if v % 2 == 0) print sum(1 for v in r if v % 3 == 0) </code></pre> <p>and while the smallest (and in my book probably the most elegant) it doesn't feel like it expresses the intent very well.</p> <p>So, my question to you is:</p> <p>Which alternative do you like best to gather these types of stats? Feel free to supply your own alternative if you have something better.</p> <p>To clear up some confusion below:</p> <ul> <li>In reality my filter predicates are more complex than just this simple test.</li> <li>The objects I iterate over are larger and more complex than just numbers</li> <li>My filter functions are more different and hard to parameterize into one predicate</li> </ul>
13
2008-10-01T10:37:20Z
157,121
<p>Alt 4! But maybe you should refactor the code to a function that takes an argument which should contain the divisible number (two and three). And then you could have a better functionname.</p> <pre><code>def methodName(divNumber, r): return sum(1 for v in r if v % divNumber == 0) print methodName(2, xrange(1, 10)) print methodName(3, xrange(1, 10)) </code></pre>
5
2008-10-01T11:04:46Z
[ "python", "list-comprehension" ]
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http://www.refactoring.com/catalog/splitLoop.html">split loop</a> refactoring in mind), looks rather bloated:</p> <p>(alt 1)</p> <pre><code>r = xrange(1, 10) twos = 0 threes = 0 for v in r: if v % 2 == 0: twos+=1 if v % 3 == 0: threes+=1 print twos print threes </code></pre> <p>This looks rather nice, but has the drawback of expanding the expression to a list:</p> <p>(alt 2)</p> <pre><code>r = xrange(1, 10) print len([1 for v in r if v % 2 == 0]) print len([1 for v in r if v % 3 == 0]) </code></pre> <p>What I would really like is something like a function like this:</p> <p>(alt 3)</p> <pre><code>def count(iterable): n = 0 for i in iterable: n += 1 return n r = xrange(1, 10) print count(1 for v in r if v % 2 == 0) print count(1 for v in r if v % 3 == 0) </code></pre> <p>But this looks a lot like something that could be done without a function. The final variant is this:</p> <p>(alt 4)</p> <pre><code>r = xrange(1, 10) print sum(1 for v in r if v % 2 == 0) print sum(1 for v in r if v % 3 == 0) </code></pre> <p>and while the smallest (and in my book probably the most elegant) it doesn't feel like it expresses the intent very well.</p> <p>So, my question to you is:</p> <p>Which alternative do you like best to gather these types of stats? Feel free to supply your own alternative if you have something better.</p> <p>To clear up some confusion below:</p> <ul> <li>In reality my filter predicates are more complex than just this simple test.</li> <li>The objects I iterate over are larger and more complex than just numbers</li> <li>My filter functions are more different and hard to parameterize into one predicate</li> </ul>
13
2008-10-01T10:37:20Z
157,141
<p>Having to iterate over the list multiple times isn't elegant IMHO.</p> <p>I'd probably create a function that allows doing:</p> <pre><code>twos, threes = countmatching(xrange(1,10), lambda a: a % 2 == 0, lambda a: a % 3 == 0) </code></pre> <p>A starting point would be something like this:</p> <pre><code>def countmatching(iterable, *predicates): v = [0] * len(predicates) for e in iterable: for i,p in enumerate(predicates): if p(e): v[i] += 1 return tuple(v) </code></pre> <p>Btw, "itertools recipes" has a recipe for doing much like your alt4.</p> <pre><code>def quantify(seq, pred=None): "Count how many times the predicate is true in the sequence" return sum(imap(pred, seq)) </code></pre>
14
2008-10-01T11:09:14Z
[ "python", "list-comprehension" ]
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http://www.refactoring.com/catalog/splitLoop.html">split loop</a> refactoring in mind), looks rather bloated:</p> <p>(alt 1)</p> <pre><code>r = xrange(1, 10) twos = 0 threes = 0 for v in r: if v % 2 == 0: twos+=1 if v % 3 == 0: threes+=1 print twos print threes </code></pre> <p>This looks rather nice, but has the drawback of expanding the expression to a list:</p> <p>(alt 2)</p> <pre><code>r = xrange(1, 10) print len([1 for v in r if v % 2 == 0]) print len([1 for v in r if v % 3 == 0]) </code></pre> <p>What I would really like is something like a function like this:</p> <p>(alt 3)</p> <pre><code>def count(iterable): n = 0 for i in iterable: n += 1 return n r = xrange(1, 10) print count(1 for v in r if v % 2 == 0) print count(1 for v in r if v % 3 == 0) </code></pre> <p>But this looks a lot like something that could be done without a function. The final variant is this:</p> <p>(alt 4)</p> <pre><code>r = xrange(1, 10) print sum(1 for v in r if v % 2 == 0) print sum(1 for v in r if v % 3 == 0) </code></pre> <p>and while the smallest (and in my book probably the most elegant) it doesn't feel like it expresses the intent very well.</p> <p>So, my question to you is:</p> <p>Which alternative do you like best to gather these types of stats? Feel free to supply your own alternative if you have something better.</p> <p>To clear up some confusion below:</p> <ul> <li>In reality my filter predicates are more complex than just this simple test.</li> <li>The objects I iterate over are larger and more complex than just numbers</li> <li>My filter functions are more different and hard to parameterize into one predicate</li> </ul>
13
2008-10-01T10:37:20Z
157,181
<pre><code>from itertools import groupby from collections import defaultdict def multiples(v): return 2 if v%2==0 else 3 if v%3==0 else None d = defaultdict(list) for k, values in groupby(range(10), multiples): if k is not None: d[k].extend(values) </code></pre>
0
2008-10-01T11:26:34Z
[ "python", "list-comprehension" ]
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http://www.refactoring.com/catalog/splitLoop.html">split loop</a> refactoring in mind), looks rather bloated:</p> <p>(alt 1)</p> <pre><code>r = xrange(1, 10) twos = 0 threes = 0 for v in r: if v % 2 == 0: twos+=1 if v % 3 == 0: threes+=1 print twos print threes </code></pre> <p>This looks rather nice, but has the drawback of expanding the expression to a list:</p> <p>(alt 2)</p> <pre><code>r = xrange(1, 10) print len([1 for v in r if v % 2 == 0]) print len([1 for v in r if v % 3 == 0]) </code></pre> <p>What I would really like is something like a function like this:</p> <p>(alt 3)</p> <pre><code>def count(iterable): n = 0 for i in iterable: n += 1 return n r = xrange(1, 10) print count(1 for v in r if v % 2 == 0) print count(1 for v in r if v % 3 == 0) </code></pre> <p>But this looks a lot like something that could be done without a function. The final variant is this:</p> <p>(alt 4)</p> <pre><code>r = xrange(1, 10) print sum(1 for v in r if v % 2 == 0) print sum(1 for v in r if v % 3 == 0) </code></pre> <p>and while the smallest (and in my book probably the most elegant) it doesn't feel like it expresses the intent very well.</p> <p>So, my question to you is:</p> <p>Which alternative do you like best to gather these types of stats? Feel free to supply your own alternative if you have something better.</p> <p>To clear up some confusion below:</p> <ul> <li>In reality my filter predicates are more complex than just this simple test.</li> <li>The objects I iterate over are larger and more complex than just numbers</li> <li>My filter functions are more different and hard to parameterize into one predicate</li> </ul>
13
2008-10-01T10:37:20Z
157,620
<p>The idea here is to use reduction to avoid repeated iterations. Also, this does not create any extra data structures, if memory is an issue for you. You start with a dictionary with your counters (<code>{'div2': 0, 'div3': 0}</code>) and increment them along the iteration.</p> <pre><code>def increment_stats(stats, n): if n % 2 == 0: stats['div2'] += 1 if n % 3 == 0: stats['div3'] += 1 return stats r = xrange(1, 10) stats = reduce(increment_stats, r, {'div2': 0, 'div3': 0}) print stats </code></pre> <p>If you want to count anything more complicated than divisors, it would be appropriate to use a more object-oriented approach (with the same advantages), encapsulating the logic for stats extraction.</p> <pre><code>class Stats: def __init__(self, div2=0, div3=0): self.div2 = div2 self.div3 = div3 def increment(self, n): if n % 2 == 0: self.div2 += 1 if n % 3 == 0: self.div3 += 1 return self def __repr__(self): return 'Stats(%d, %d)' % (self.div2, self.div3) r = xrange(1, 10) stats = reduce(lambda stats, n: stats.increment(n), r, Stats()) print stats </code></pre> <p>Please point out any mistakes.</p> <p>@<a href="#158250" rel="nofollow">Henrik</a>: I think the first approach is less maintainable since you have to control initialization of the dictionary in one place and update in another, as well as having to use strings to refer to each stat (instead of having attributes). And I do not think OO is overkill in this case, for you said the predicates and objects will be complex in your application. In fact if the predicates were really simple, I wouldn't even bother to use a dictionary, a single fixed size list would be just fine. Cheers :)</p>
0
2008-10-01T13:32:41Z
[ "python", "list-comprehension" ]
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http://www.refactoring.com/catalog/splitLoop.html">split loop</a> refactoring in mind), looks rather bloated:</p> <p>(alt 1)</p> <pre><code>r = xrange(1, 10) twos = 0 threes = 0 for v in r: if v % 2 == 0: twos+=1 if v % 3 == 0: threes+=1 print twos print threes </code></pre> <p>This looks rather nice, but has the drawback of expanding the expression to a list:</p> <p>(alt 2)</p> <pre><code>r = xrange(1, 10) print len([1 for v in r if v % 2 == 0]) print len([1 for v in r if v % 3 == 0]) </code></pre> <p>What I would really like is something like a function like this:</p> <p>(alt 3)</p> <pre><code>def count(iterable): n = 0 for i in iterable: n += 1 return n r = xrange(1, 10) print count(1 for v in r if v % 2 == 0) print count(1 for v in r if v % 3 == 0) </code></pre> <p>But this looks a lot like something that could be done without a function. The final variant is this:</p> <p>(alt 4)</p> <pre><code>r = xrange(1, 10) print sum(1 for v in r if v % 2 == 0) print sum(1 for v in r if v % 3 == 0) </code></pre> <p>and while the smallest (and in my book probably the most elegant) it doesn't feel like it expresses the intent very well.</p> <p>So, my question to you is:</p> <p>Which alternative do you like best to gather these types of stats? Feel free to supply your own alternative if you have something better.</p> <p>To clear up some confusion below:</p> <ul> <li>In reality my filter predicates are more complex than just this simple test.</li> <li>The objects I iterate over are larger and more complex than just numbers</li> <li>My filter functions are more different and hard to parameterize into one predicate</li> </ul>
13
2008-10-01T10:37:20Z
158,250
<p>Inspired by the OO-stab above, I had to try my hands on one as well (although this is way overkill for the problem I'm trying to solve :)</p> <pre><code>class Stat(object): def update(self, n): raise NotImplementedError def get(self): raise NotImplementedError class TwoStat(Stat): def __init__(self): self._twos = 0 def update(self, n): if n % 2 == 0: self._twos += 1 def get(self): return self._twos class ThreeStat(Stat): def __init__(self): self._threes = 0 def update(self, n): if n % 3 == 0: self._threes += 1 def get(self): return self._threes class StatCalculator(object): def __init__(self, stats): self._stats = stats def calculate(self, r): for v in r: for stat in self._stats: stat.update(v) return tuple(stat.get() for stat in self._stats) s = StatCalculator([TwoStat(), ThreeStat()]) r = xrange(1, 10) print s.calculate(r) </code></pre>
0
2008-10-01T15:35:20Z
[ "python", "list-comprehension" ]
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http://www.refactoring.com/catalog/splitLoop.html">split loop</a> refactoring in mind), looks rather bloated:</p> <p>(alt 1)</p> <pre><code>r = xrange(1, 10) twos = 0 threes = 0 for v in r: if v % 2 == 0: twos+=1 if v % 3 == 0: threes+=1 print twos print threes </code></pre> <p>This looks rather nice, but has the drawback of expanding the expression to a list:</p> <p>(alt 2)</p> <pre><code>r = xrange(1, 10) print len([1 for v in r if v % 2 == 0]) print len([1 for v in r if v % 3 == 0]) </code></pre> <p>What I would really like is something like a function like this:</p> <p>(alt 3)</p> <pre><code>def count(iterable): n = 0 for i in iterable: n += 1 return n r = xrange(1, 10) print count(1 for v in r if v % 2 == 0) print count(1 for v in r if v % 3 == 0) </code></pre> <p>But this looks a lot like something that could be done without a function. The final variant is this:</p> <p>(alt 4)</p> <pre><code>r = xrange(1, 10) print sum(1 for v in r if v % 2 == 0) print sum(1 for v in r if v % 3 == 0) </code></pre> <p>and while the smallest (and in my book probably the most elegant) it doesn't feel like it expresses the intent very well.</p> <p>So, my question to you is:</p> <p>Which alternative do you like best to gather these types of stats? Feel free to supply your own alternative if you have something better.</p> <p>To clear up some confusion below:</p> <ul> <li>In reality my filter predicates are more complex than just this simple test.</li> <li>The objects I iterate over are larger and more complex than just numbers</li> <li>My filter functions are more different and hard to parameterize into one predicate</li> </ul>
13
2008-10-01T10:37:20Z
158,587
<p>True booleans are coerced to unit integers, and false booleans to zero integers. So if you're happy to use scipy or numpy, make an array of integers for each element of your sequence, each array containing one element for each of your tests, and sum over the arrays. E.g.</p> <pre><code>&gt;&gt;&gt; sum(scipy.array([c % 2 == 0, c % 3 == 0]) for c in xrange(10)) array([5, 4]) </code></pre>
1
2008-10-01T16:47:13Z
[ "python", "list-comprehension" ]
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http://www.refactoring.com/catalog/splitLoop.html">split loop</a> refactoring in mind), looks rather bloated:</p> <p>(alt 1)</p> <pre><code>r = xrange(1, 10) twos = 0 threes = 0 for v in r: if v % 2 == 0: twos+=1 if v % 3 == 0: threes+=1 print twos print threes </code></pre> <p>This looks rather nice, but has the drawback of expanding the expression to a list:</p> <p>(alt 2)</p> <pre><code>r = xrange(1, 10) print len([1 for v in r if v % 2 == 0]) print len([1 for v in r if v % 3 == 0]) </code></pre> <p>What I would really like is something like a function like this:</p> <p>(alt 3)</p> <pre><code>def count(iterable): n = 0 for i in iterable: n += 1 return n r = xrange(1, 10) print count(1 for v in r if v % 2 == 0) print count(1 for v in r if v % 3 == 0) </code></pre> <p>But this looks a lot like something that could be done without a function. The final variant is this:</p> <p>(alt 4)</p> <pre><code>r = xrange(1, 10) print sum(1 for v in r if v % 2 == 0) print sum(1 for v in r if v % 3 == 0) </code></pre> <p>and while the smallest (and in my book probably the most elegant) it doesn't feel like it expresses the intent very well.</p> <p>So, my question to you is:</p> <p>Which alternative do you like best to gather these types of stats? Feel free to supply your own alternative if you have something better.</p> <p>To clear up some confusion below:</p> <ul> <li>In reality my filter predicates are more complex than just this simple test.</li> <li>The objects I iterate over are larger and more complex than just numbers</li> <li>My filter functions are more different and hard to parameterize into one predicate</li> </ul>
13
2008-10-01T10:37:20Z
158,632
<p>Alt 3, for the reason that it doesn't use memory proportional to the number of "hits". Given a pathological case like xrange(one_trillion), many of the other offered solutions would fail badly.</p>
0
2008-10-01T16:59:00Z
[ "python", "list-comprehension" ]
Most pythonic way of counting matching elements in something iterable
157,039
<p>I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three.</p> <p>My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the <a href="http://www.refactoring.com/catalog/splitLoop.html">split loop</a> refactoring in mind), looks rather bloated:</p> <p>(alt 1)</p> <pre><code>r = xrange(1, 10) twos = 0 threes = 0 for v in r: if v % 2 == 0: twos+=1 if v % 3 == 0: threes+=1 print twos print threes </code></pre> <p>This looks rather nice, but has the drawback of expanding the expression to a list:</p> <p>(alt 2)</p> <pre><code>r = xrange(1, 10) print len([1 for v in r if v % 2 == 0]) print len([1 for v in r if v % 3 == 0]) </code></pre> <p>What I would really like is something like a function like this:</p> <p>(alt 3)</p> <pre><code>def count(iterable): n = 0 for i in iterable: n += 1 return n r = xrange(1, 10) print count(1 for v in r if v % 2 == 0) print count(1 for v in r if v % 3 == 0) </code></pre> <p>But this looks a lot like something that could be done without a function. The final variant is this:</p> <p>(alt 4)</p> <pre><code>r = xrange(1, 10) print sum(1 for v in r if v % 2 == 0) print sum(1 for v in r if v % 3 == 0) </code></pre> <p>and while the smallest (and in my book probably the most elegant) it doesn't feel like it expresses the intent very well.</p> <p>So, my question to you is:</p> <p>Which alternative do you like best to gather these types of stats? Feel free to supply your own alternative if you have something better.</p> <p>To clear up some confusion below:</p> <ul> <li>In reality my filter predicates are more complex than just this simple test.</li> <li>The objects I iterate over are larger and more complex than just numbers</li> <li>My filter functions are more different and hard to parameterize into one predicate</li> </ul>
13
2008-10-01T10:37:20Z
163,273
<p>I would choose a small variant of your (alt 4):</p> <pre><code>def count(predicate, list): print sum(1 for x in list if predicate(x)) r = xrange(1, 10) count(lambda x: x % 2 == 0, r) count(lambda x: x % 3 == 0, r) # ... </code></pre> <p>If you want to change what count does, change its implementation in one place.</p> <p>Note: since your predicates are complex, you'll probably want to define them in functions instead of lambdas. And so you'll probably want to put all this in a class rather than the global namespace.</p>
1
2008-10-02T16:16:40Z
[ "python", "list-comprehension" ]
Date change notification in a Tkinter app (win32)
157,116
<p>Does anyone know if it is possible (and if yes, how) to bind an event (Python + Tkinter on MS Windows) to a system date change?</p> <p>I know I can have .after events checking once in a while; I'm asking if I can somehow have an event fired whenever the system date/time changes, either automatically (e.g. for daylight saving time) or manually.</p> <p>MS Windows sends such events to applications and Tkinter does receive them; I know, because if I have an .after timer waiting and I set the date/time after the timer's expiration, the timer event fires instantly.</p>
0
2008-10-01T11:02:43Z
160,031
<blockquote> <p>I know, because if I have an .after timer waiting and I set the date/time after the timer's expiration, the timer event fires instantly.</p> </blockquote> <p>That could just mean that Tkinter (or Tk) is polling the system clock as part of the event loop to figure out when to run timers.</p> <p>If you're using Windows, Mark Hammond's book notes that you can use the win32evtlogutil module to respond to changes in the Windows event log. Basically it works like this:</p> <pre><code>import win32evtlogutil def onEvent(record): # Do something with the event log record win32evtlogutil.FeedEventLogRecords(onEvent) </code></pre> <p>But you'll need to get docs on the structure of the event records (I don't feel like typing out the whole chapter, sorry :-) ). Also I don't know if date changes turn up in the event log anyway.</p> <p>Really, though, is it so bad to just poll the system clock? It seems easiest and I don't think it would slow you down much.</p> <p>(finally, a comment: I don't know about your country, but here in NZ, daylight savings doesn't involve a date change; only the time changes (from 2am-3am, or vice-versa))</p>
1
2008-10-01T22:21:02Z
[ "python", "windows", "events", "tkinter" ]
Template Lib (Engine) in Python running with Jython
157,313
<p>Im searching a Template Lib or Template Engine for generating HTML (XML) that runs under Jython (Jython 2.5 Alpha is ok).</p>
1
2008-10-01T12:20:23Z
157,362
<p>Have you tried <a href="http://www.cheetahtemplate.org/" rel="nofollow">Cheetah</a>, I don't have direct experience running it under Jython but there seem to be some people that do. </p>
2
2008-10-01T12:37:24Z
[ "python", "jython", "template-engine" ]
Template Lib (Engine) in Python running with Jython
157,313
<p>Im searching a Template Lib or Template Engine for generating HTML (XML) that runs under Jython (Jython 2.5 Alpha is ok).</p>
1
2008-10-01T12:20:23Z
160,496
<p>Jinja is pretty cool and seems to work on Jython.</p>
2
2008-10-02T01:35:51Z
[ "python", "jython", "template-engine" ]
Template Lib (Engine) in Python running with Jython
157,313
<p>Im searching a Template Lib or Template Engine for generating HTML (XML) that runs under Jython (Jython 2.5 Alpha is ok).</p>
1
2008-10-01T12:20:23Z
304,203
<p>Use StringTemplate, see <a href="http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf" rel="nofollow">http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf</a> for details of why. There is nothing better, and it supports both Java and Python (and .NET, etc.).</p>
1
2008-11-20T02:50:53Z
[ "python", "jython", "template-engine" ]
Accurate timestamping in Python
157,359
<p>I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that).</p> <p>I've been using datetime.now() as a first stab, but this isn't perfect:</p> <pre><code>&gt;&gt;&gt; for i in range(0,1000): ... datetime.datetime.now() ... datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) etc. </code></pre> <p>The changes between clocks for the first second of samples looks like this:</p> <pre><code>uSecs difference 562000 578000 16000 609000 31000 625000 16000 640000 15000 656000 16000 687000 31000 703000 16000 718000 15000 750000 32000 765000 15000 781000 16000 796000 15000 828000 32000 843000 15000 859000 16000 890000 31000 906000 16000 921000 15000 937000 16000 968000 31000 984000 16000 </code></pre> <p>So it looks like the timer data is only updated every ~15-32ms on my machine. The problem comes when we come to analyse the data because sorting by something other than the timestamp and then sorting by timestamp again can leave the data in the wrong order (chronologically). It would be nice to have the time stamps accurate to the point that any call to the time stamp generator gives a unique timestamp.</p> <p>I had been considering some methods involving using a time.clock() call added to a starting datetime, but would appreciate a solution that would work accurately across threads on the same machine. Any suggestions would be very gratefully received.</p>
12
2008-10-01T12:36:17Z
157,439
<p>time.clock() only measures wallclock time on Windows. On other systems, time.clock() actually measures CPU-time. On those systems time.time() is more suitable for wallclock time, and it has as high a resolution as Python can manage -- which is as high as the OS can manage; usually using gettimeofday(3) (microsecond resolution) or ftime(3) (millisecond resolution.) Other OS restrictions actually make the real resolution a lot higher than that. datetime.datetime.now() uses time.time(), so time.time() directly won't be better.</p> <p>For the record, if I use datetime.datetime.now() in a loop, I see about a 1/10000 second resolution. From looking at your data, you have much, much coarser resolution than that. I'm not sure if there's anything Python as such can do, although you may be able to convince the OS to do better through other means.</p> <p>I seem to recall that on Windows, time.clock() is actually (slightly) more accurate than time.time(), but it measures wallclock since the first call to time.clock(), so you have to remember to 'initialize' it first.</p>
11
2008-10-01T12:54:25Z
[ "python", "timestamp", "timer" ]
Accurate timestamping in Python
157,359
<p>I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that).</p> <p>I've been using datetime.now() as a first stab, but this isn't perfect:</p> <pre><code>&gt;&gt;&gt; for i in range(0,1000): ... datetime.datetime.now() ... datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) etc. </code></pre> <p>The changes between clocks for the first second of samples looks like this:</p> <pre><code>uSecs difference 562000 578000 16000 609000 31000 625000 16000 640000 15000 656000 16000 687000 31000 703000 16000 718000 15000 750000 32000 765000 15000 781000 16000 796000 15000 828000 32000 843000 15000 859000 16000 890000 31000 906000 16000 921000 15000 937000 16000 968000 31000 984000 16000 </code></pre> <p>So it looks like the timer data is only updated every ~15-32ms on my machine. The problem comes when we come to analyse the data because sorting by something other than the timestamp and then sorting by timestamp again can leave the data in the wrong order (chronologically). It would be nice to have the time stamps accurate to the point that any call to the time stamp generator gives a unique timestamp.</p> <p>I had been considering some methods involving using a time.clock() call added to a starting datetime, but would appreciate a solution that would work accurately across threads on the same machine. Any suggestions would be very gratefully received.</p>
12
2008-10-01T12:36:17Z
157,656
<p>Here is a thread about Python timing accuracy:<br><br> <a href="http://stackoverflow.com/questions/85451/python-timeclock-vs-timetime-accuracy">http://stackoverflow.com/questions/85451/python-timeclock-vs-timetime-accuracy</a></p>
2
2008-10-01T13:44:13Z
[ "python", "timestamp", "timer" ]
Accurate timestamping in Python
157,359
<p>I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that).</p> <p>I've been using datetime.now() as a first stab, but this isn't perfect:</p> <pre><code>&gt;&gt;&gt; for i in range(0,1000): ... datetime.datetime.now() ... datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) etc. </code></pre> <p>The changes between clocks for the first second of samples looks like this:</p> <pre><code>uSecs difference 562000 578000 16000 609000 31000 625000 16000 640000 15000 656000 16000 687000 31000 703000 16000 718000 15000 750000 32000 765000 15000 781000 16000 796000 15000 828000 32000 843000 15000 859000 16000 890000 31000 906000 16000 921000 15000 937000 16000 968000 31000 984000 16000 </code></pre> <p>So it looks like the timer data is only updated every ~15-32ms on my machine. The problem comes when we come to analyse the data because sorting by something other than the timestamp and then sorting by timestamp again can leave the data in the wrong order (chronologically). It would be nice to have the time stamps accurate to the point that any call to the time stamp generator gives a unique timestamp.</p> <p>I had been considering some methods involving using a time.clock() call added to a starting datetime, but would appreciate a solution that would work accurately across threads on the same machine. Any suggestions would be very gratefully received.</p>
12
2008-10-01T12:36:17Z
157,711
<p>You're unlikely to get sufficiently fine-grained control that you can completely eliminate the possibility of duplicate timestamps - you'd need resolution smaller than the time it takes to generate a datetime object. There are a couple of other approaches you might take to deal with it:</p> <ol> <li><p>Deal with it. Leave your timestamps non-unique as they are, but rely on python's sort being stable to deal with reordering problems. Sorting on timestamp <em>first</em>, then something else will retain the timestamp ordering - you just have to be careful to always start from the timestamp ordered list every time, rather than doing multiple sorts on the same list.</p></li> <li><p>Append your own value to enforce uniqueness. Eg. include an incrementing integer value as part of the key, or append such a value only if timestamps are different. Eg.</p></li> </ol> <p>The following will guarantee unique timestamp values:</p> <pre><code> class TimeStamper(object): def __init__(self): self.lock = threading.Lock() self.prev = None self.count = 0 def getTimestamp(self): with self.lock: ts = str(datetime.now()) if ts == self.prev: ts +='.%04d' % self.count self.count += 1 else: self.prev = ts self.count = 1 return ts </code></pre> <p>For multiple processes (rather than threads), it gets a bit trickier though.</p>
7
2008-10-01T13:55:57Z
[ "python", "timestamp", "timer" ]
Accurate timestamping in Python
157,359
<p>I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that).</p> <p>I've been using datetime.now() as a first stab, but this isn't perfect:</p> <pre><code>&gt;&gt;&gt; for i in range(0,1000): ... datetime.datetime.now() ... datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) etc. </code></pre> <p>The changes between clocks for the first second of samples looks like this:</p> <pre><code>uSecs difference 562000 578000 16000 609000 31000 625000 16000 640000 15000 656000 16000 687000 31000 703000 16000 718000 15000 750000 32000 765000 15000 781000 16000 796000 15000 828000 32000 843000 15000 859000 16000 890000 31000 906000 16000 921000 15000 937000 16000 968000 31000 984000 16000 </code></pre> <p>So it looks like the timer data is only updated every ~15-32ms on my machine. The problem comes when we come to analyse the data because sorting by something other than the timestamp and then sorting by timestamp again can leave the data in the wrong order (chronologically). It would be nice to have the time stamps accurate to the point that any call to the time stamp generator gives a unique timestamp.</p> <p>I had been considering some methods involving using a time.clock() call added to a starting datetime, but would appreciate a solution that would work accurately across threads on the same machine. Any suggestions would be very gratefully received.</p>
12
2008-10-01T12:36:17Z
157,871
<p>"timestamp should be accurate relative to each other "</p> <p>Why time? Why not a sequence number? If it's any client of client-server application, network latency makes timestamps kind of random.</p> <p>Are you matching some external source of information? Say a log on another application? Again, if there's a network, those times won't be too close.</p> <p>If you must match things between separate apps, consider passing GUID's around so that both apps log the GUID value. Then you could be absolutely sure they match, irrespective of timing differences.</p> <p>If you want the <em>relative</em> order to be exactly right, maybe it's enough for your logger to assign a sequence number to each message in the order they were received.</p>
2
2008-10-01T14:24:59Z
[ "python", "timestamp", "timer" ]
Accurate timestamping in Python
157,359
<p>I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that).</p> <p>I've been using datetime.now() as a first stab, but this isn't perfect:</p> <pre><code>&gt;&gt;&gt; for i in range(0,1000): ... datetime.datetime.now() ... datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) etc. </code></pre> <p>The changes between clocks for the first second of samples looks like this:</p> <pre><code>uSecs difference 562000 578000 16000 609000 31000 625000 16000 640000 15000 656000 16000 687000 31000 703000 16000 718000 15000 750000 32000 765000 15000 781000 16000 796000 15000 828000 32000 843000 15000 859000 16000 890000 31000 906000 16000 921000 15000 937000 16000 968000 31000 984000 16000 </code></pre> <p>So it looks like the timer data is only updated every ~15-32ms on my machine. The problem comes when we come to analyse the data because sorting by something other than the timestamp and then sorting by timestamp again can leave the data in the wrong order (chronologically). It would be nice to have the time stamps accurate to the point that any call to the time stamp generator gives a unique timestamp.</p> <p>I had been considering some methods involving using a time.clock() call added to a starting datetime, but would appreciate a solution that would work accurately across threads on the same machine. Any suggestions would be very gratefully received.</p>
12
2008-10-01T12:36:17Z
160,208
<p>Thank you all for your contributions - they've all be very useful. Brian's answer seems closest to what I eventually went with (i.e. deal with it but use a sort of unique identifier - see below) so I've accepted his answer. I managed to consolidate all the various data receivers into a single thread which is where the timestamping is now done using my new <strong>AccurrateTimeStamp</strong> class. What I've done works as long as the time stamp is the first thing to use the clock.</p> <p>As S.Lott stipulates, without a realtime OS, they're never going to be absolutely perfect. I really only wanted something that would let me see relative to each incoming chunk of data, when things were being received so what I've got below will work well.</p> <p>Thanks again everyone!</p> <pre><code>import time class AccurateTimeStamp(): """ A simple class to provide a very accurate means of time stamping some data """ # Do the class-wide initial time stamp to synchronise calls to # time.clock() to a single time stamp initialTimeStamp = time.time()+ time.clock() def __init__(self): """ Constructor for the AccurateTimeStamp class. This makes a stamp based on the current time which should be more accurate than anything you can get out of time.time(). NOTE: This time stamp will only work if nothing has called clock() in this instance of the Python interpreter. """ # Get the time since the first of call to time.clock() offset = time.clock() # Get the current (accurate) time currentTime = AccurateTimeStamp.initialTimeStamp+offset # Split the time into whole seconds and the portion after the fraction self.accurateSeconds = int(currentTime) self.accuratePastSecond = currentTime - self.accurateSeconds def GetAccurateTimeStampString(timestamp): """ Function to produce a timestamp of the form "13:48:01.87123" representing the time stamp 'timestamp' """ # Get a struct_time representing the number of whole seconds since the # epoch that we can use to format the time stamp wholeSecondsInTimeStamp = time.localtime(timestamp.accurateSeconds) # Convert the whole seconds and whatever fraction of a second comes after # into a couple of strings wholeSecondsString = time.strftime("%H:%M:%S", wholeSecondsInTimeStamp) fractionAfterSecondString = str(int(timestamp.accuratePastSecond*1000000)) # Return our shiny new accurate time stamp return wholeSecondsString+"."+fractionAfterSecondString if __name__ == '__main__': for i in range(0,500): timestamp = AccurateTimeStamp() print GetAccurateTimeStampString(timestamp) </code></pre>
5
2008-10-01T23:23:33Z
[ "python", "timestamp", "timer" ]
Accurate timestamping in Python
157,359
<p>I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that).</p> <p>I've been using datetime.now() as a first stab, but this isn't perfect:</p> <pre><code>&gt;&gt;&gt; for i in range(0,1000): ... datetime.datetime.now() ... datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) etc. </code></pre> <p>The changes between clocks for the first second of samples looks like this:</p> <pre><code>uSecs difference 562000 578000 16000 609000 31000 625000 16000 640000 15000 656000 16000 687000 31000 703000 16000 718000 15000 750000 32000 765000 15000 781000 16000 796000 15000 828000 32000 843000 15000 859000 16000 890000 31000 906000 16000 921000 15000 937000 16000 968000 31000 984000 16000 </code></pre> <p>So it looks like the timer data is only updated every ~15-32ms on my machine. The problem comes when we come to analyse the data because sorting by something other than the timestamp and then sorting by timestamp again can leave the data in the wrong order (chronologically). It would be nice to have the time stamps accurate to the point that any call to the time stamp generator gives a unique timestamp.</p> <p>I had been considering some methods involving using a time.clock() call added to a starting datetime, but would appreciate a solution that would work accurately across threads on the same machine. Any suggestions would be very gratefully received.</p>
12
2008-10-01T12:36:17Z
284,375
<p>I wanted to thank J. Cage for this last post. </p> <p>For my work, "reasonable" timing of events across processes and platforms is essential. There are obviously lots of places where things can go askew (clock drift, context switching, etc.), however this accurate timing solution will, I think, help to ensure that the time stamps recorded are sufficiently accurate to see the other sources of error. </p> <p>That said, there are a couple of details I wonder about that are explained in <a href="http://www.ibm.com/developerworks/library/i-seconds/" rel="nofollow" title="When Microseconds Matter">When MicroSeconds Matter</a>. For example, I think time.clock() will eventually wrap. I think for this to work for a long running process, you might have to handle that.</p>
0
2008-11-12T15:51:52Z
[ "python", "timestamp", "timer" ]
Accurate timestamping in Python
157,359
<p>I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that).</p> <p>I've been using datetime.now() as a first stab, but this isn't perfect:</p> <pre><code>&gt;&gt;&gt; for i in range(0,1000): ... datetime.datetime.now() ... datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) etc. </code></pre> <p>The changes between clocks for the first second of samples looks like this:</p> <pre><code>uSecs difference 562000 578000 16000 609000 31000 625000 16000 640000 15000 656000 16000 687000 31000 703000 16000 718000 15000 750000 32000 765000 15000 781000 16000 796000 15000 828000 32000 843000 15000 859000 16000 890000 31000 906000 16000 921000 15000 937000 16000 968000 31000 984000 16000 </code></pre> <p>So it looks like the timer data is only updated every ~15-32ms on my machine. The problem comes when we come to analyse the data because sorting by something other than the timestamp and then sorting by timestamp again can leave the data in the wrong order (chronologically). It would be nice to have the time stamps accurate to the point that any call to the time stamp generator gives a unique timestamp.</p> <p>I had been considering some methods involving using a time.clock() call added to a starting datetime, but would appreciate a solution that would work accurately across threads on the same machine. Any suggestions would be very gratefully received.</p>
12
2008-10-01T12:36:17Z
22,194,015
<p>A few years past since the question has been asked and answered, and this has been dealt with, at least for CPython on Windows. Using the script below on both Win7 64bit and Windows Server 2008 R2, I got the same results:</p> <ul> <li><code>datetime.now()</code> gives a resolution of 1ms and a jitter smaller than 1ms</li> <li><code>time.clock()</code> gives a resolution of better than 1us and a jitter much smaller than 1ms</li> </ul> <p>The script:</p> <pre><code>import time import datetime t1_0 = time.clock() t2_0 = datetime.datetime.now() with open('output.csv', 'w') as f: for i in xrange(100000): t1 = time.clock() t2 = datetime.datetime.now() td1 = t1-t1_0 td2 = (t2-t2_0).total_seconds() f.write('%.6f,%.6f\n' % (td1, td2)) </code></pre> <p>The results visualized: <img src="http://i.stack.imgur.com/PHaYA.jpg" alt="enter image description here"></p>
0
2014-03-05T09:46:44Z
[ "python", "timestamp", "timer" ]
Accurate timestamping in Python
157,359
<p>I've been building an error logging app recently and was after a way of accurately timestamping the incoming data. When I say accurately I mean each timestamp should be accurate relative to each other (no need to sync to an atomic clock or anything like that).</p> <p>I've been using datetime.now() as a first stab, but this isn't perfect:</p> <pre><code>&gt;&gt;&gt; for i in range(0,1000): ... datetime.datetime.now() ... datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 562000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 578000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) datetime.datetime(2008, 10, 1, 13, 17, 27, 609000) etc. </code></pre> <p>The changes between clocks for the first second of samples looks like this:</p> <pre><code>uSecs difference 562000 578000 16000 609000 31000 625000 16000 640000 15000 656000 16000 687000 31000 703000 16000 718000 15000 750000 32000 765000 15000 781000 16000 796000 15000 828000 32000 843000 15000 859000 16000 890000 31000 906000 16000 921000 15000 937000 16000 968000 31000 984000 16000 </code></pre> <p>So it looks like the timer data is only updated every ~15-32ms on my machine. The problem comes when we come to analyse the data because sorting by something other than the timestamp and then sorting by timestamp again can leave the data in the wrong order (chronologically). It would be nice to have the time stamps accurate to the point that any call to the time stamp generator gives a unique timestamp.</p> <p>I had been considering some methods involving using a time.clock() call added to a starting datetime, but would appreciate a solution that would work accurately across threads on the same machine. Any suggestions would be very gratefully received.</p>
12
2008-10-01T12:36:17Z
38,840,918
<p>If you want microsecond-<em>resolution</em> (NOT accuracy) timestamps in Python, in <em>Windows,</em> you can use Windows's QPC timer, as demonstrated in my answer here: <a href="http://stackoverflow.com/questions/38319606/how-to-get-millisecond-and-microsecond-resolution-timestamps-in-python">How to get millisecond and microsecond-resolution timestamps in Python</a>. I'm not sure how to do this in Linux yet, so if anyone knows, please comment or answer in the link above.</p>
0
2016-08-09T01:59:53Z
[ "python", "timestamp", "timer" ]
Python 2.5 dictionary 2 key sort
157,424
<p>I have a dictionary of 200,000 items (the keys are strings and the values are integers).</p> <p>What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)?</p> <pre><code> a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort( key=lambda a:a[1], reverse=True ) print b &gt;&gt;&gt;[('keyB', 2), ('keyA', 1), ('keyC', 1)] </code></pre>
14
2008-10-01T12:50:19Z
157,445
<p>You can't sort dictionaries. You have to sort the list of items.</p> <p>Previous versions were wrong. When you have a numeric value, it's easy to sort in reverse order. These will do that. But this isn't general. This only works because the value is numeric.</p> <pre><code>a = { 'key':1, 'another':2, 'key2':1 } b= a.items() b.sort( key=lambda a:(-a[1],a[0]) ) print b </code></pre> <p>Here's an alternative, using an explicit function instead of a lambda and the cmp instead of the key option.</p> <pre><code>def valueKeyCmp( a, b ): return cmp( (-a[1], a[0]), (-b[1], b[0] ) ) b.sort( cmp= valueKeyCmp ) print b </code></pre> <p>The more general solution is actually two separate sorts</p> <pre><code>b.sort( key=lambda a:a[1], reverse=True ) b.sort( key=lambda a:a[0] ) print b </code></pre>
17
2008-10-01T12:56:01Z
[ "python" ]
Python 2.5 dictionary 2 key sort
157,424
<p>I have a dictionary of 200,000 items (the keys are strings and the values are integers).</p> <p>What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)?</p> <pre><code> a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort( key=lambda a:a[1], reverse=True ) print b &gt;&gt;&gt;[('keyB', 2), ('keyA', 1), ('keyC', 1)] </code></pre>
14
2008-10-01T12:50:19Z
157,462
<p>The most pythonic way to do it would be to know a little more about the actual data -- specifically, the maximum value you can have -- and then do it like this:</p> <pre><code>def sortkey((k, v)): return (maxval - v, k) items = thedict.items() items.sort(key=sortkey) </code></pre> <p>but unless you already know the maximum value, searching for the maximum value means looping through the dict an extra time (with <code>max(thedict.itervalues())</code>), which may be expensive. Alternatively, a keyfunc version of S.Lott's solution:</p> <pre><code>def sortkey((k, v)): return (-v, k) items = thedict.items() items.sort(key=sortkey) </code></pre> <p>An alternative that doesn't care about the types would be a comparison function:</p> <pre><code>def sortcmp((ak, av), (bk, bv)): # compare values 'in reverse' r = cmp(bv, av) if not r: # and then keys normally r = cmp(ak, bk) return r items = thedict.items() items.sort(cmp=sortcmp) </code></pre> <p>and this solution actually works for any type of key and value that you want to mix ascending and descending sorting with in the same key. If you value brevity you can write sortcmp as:</p> <pre><code>def sortcmp((ak, av), (bk, bv)): return cmp((bk, av), (ak, bv)) </code></pre>
1
2008-10-01T13:00:26Z
[ "python" ]
Python 2.5 dictionary 2 key sort
157,424
<p>I have a dictionary of 200,000 items (the keys are strings and the values are integers).</p> <p>What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)?</p> <pre><code> a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort( key=lambda a:a[1], reverse=True ) print b &gt;&gt;&gt;[('keyB', 2), ('keyA', 1), ('keyC', 1)] </code></pre>
14
2008-10-01T12:50:19Z
157,494
<p>You can use something like this:</p> <pre><code>dic = {'aaa':1, 'aab':3, 'aaf':3, 'aac':2, 'aad':2, 'aae':4} def sort_compare(a, b): c = cmp(dic[b], dic[a]) if c != 0: return c return cmp(a, b) for k in sorted(dic.keys(), cmp=sort_compare): print k, dic[k] </code></pre> <p>Don't know how pythonic it is however :)</p>
0
2008-10-01T13:08:50Z
[ "python" ]
Python 2.5 dictionary 2 key sort
157,424
<p>I have a dictionary of 200,000 items (the keys are strings and the values are integers).</p> <p>What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)?</p> <pre><code> a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort( key=lambda a:a[1], reverse=True ) print b &gt;&gt;&gt;[('keyB', 2), ('keyA', 1), ('keyC', 1)] </code></pre>
14
2008-10-01T12:50:19Z
157,792
<pre><code>data = { 'keyC':1, 'keyB':2, 'keyA':1 } for key, value in sorted(data.items(), key=lambda x: (-1*x[1], x[0])): print key, value </code></pre>
6
2008-10-01T14:11:59Z
[ "python" ]
Python 2.5 dictionary 2 key sort
157,424
<p>I have a dictionary of 200,000 items (the keys are strings and the values are integers).</p> <p>What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)?</p> <pre><code> a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort( key=lambda a:a[1], reverse=True ) print b &gt;&gt;&gt;[('keyB', 2), ('keyA', 1), ('keyC', 1)] </code></pre>
14
2008-10-01T12:50:19Z
158,022
<p>Building on Thomas Wouters and Ricardo Reyes solutions:</p> <pre><code>def combine(*cmps): """Sequence comparisons.""" def comparator(a, b): for cmp in cmps: result = cmp(a, b): if result: return result return 0 return comparator def reverse(cmp): """Invert a comparison.""" def comparator(a, b): return cmp(b, a) return comparator def compare_nth(cmp, n): """Compare the n'th item from two sequences.""" def comparator(a, b): return cmp(a[n], b[n]) return comparator rev_val_key_cmp = combine( # compare values, decreasing reverse(compare_nth(1, cmp)), # compare keys, increasing compare_nth(0, cmp) ) data = { 'keyC':1, 'keyB':2, 'keyA':1 } for key, value in sorted(data.items(), cmp=rev_val_key_cmp): print key, value </code></pre>
0
2008-10-01T14:53:17Z
[ "python" ]
Python 2.5 dictionary 2 key sort
157,424
<p>I have a dictionary of 200,000 items (the keys are strings and the values are integers).</p> <p>What is the best/most pythonic way to print the items sorted by descending value then ascending key (i.e. a 2 key sort)?</p> <pre><code> a={ 'keyC':1, 'keyB':2, 'keyA':1 } b = a.items() b.sort( key=lambda a:a[0]) b.sort( key=lambda a:a[1], reverse=True ) print b &gt;&gt;&gt;[('keyB', 2), ('keyA', 1), ('keyC', 1)] </code></pre>
14
2008-10-01T12:50:19Z
280,027
<pre><code>&gt;&gt;&gt; keys = sorted(a, key=lambda k: (-a[k], k)) </code></pre> <p>or</p> <pre><code>&gt;&gt;&gt; keys = sorted(a) &gt;&gt;&gt; keys.sort(key=a.get, reverse=True) </code></pre> <p>then</p> <pre><code>print [(key, a[key]) for key in keys] [('keyB', 2), ('keyA', 1), ('keyC', 1)] </code></pre>
0
2008-11-11T04:43:43Z
[ "python" ]
What is the best way to sample/profile a PyObjC application?
157,662
<p>Sampling with Activity Monitor/Instruments/Shark will show stack traces full of C functions for the Python interpreter. I would be helpful to see the corresponding Python symbol names. Is there some DTrace magic that can do that? Python's cProfile module can be useful for profiling individual subtrees of Python calls, but not so much for getting a picture of what's going on with the whole application in response to user events.</p>
6
2008-10-01T13:45:12Z
165,590
<p>The answer is "dtrace", but it won't work on sufficiently old macs.</p> <p><a href="http://tech.marshallfamily.com.au/archives/python-dtrace-on-os-x-leopard-part-1/" rel="nofollow">http://tech.marshallfamily.com.au/archives/python-dtrace-on-os-x-leopard-part-1/</a></p> <p><a href="http://tech.marshallfamily.com.au/archives/python-dtrace-on-os-x-leopard-part-2/" rel="nofollow">http://tech.marshallfamily.com.au/archives/python-dtrace-on-os-x-leopard-part-2/</a></p>
3
2008-10-03T03:33:35Z
[ "python", "cocoa", "osx", "pyobjc" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ? </p>
75
2008-10-01T14:37:17Z
157,974
<p>There are several ROT13 utilities written in Python on the 'Net -- just google for them. ROT13 encode the string offline, copy it into the source, decode at point of transmission.<br><br>But this is <em>really</em> weak protection...</p>
0
2008-10-01T14:43:20Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ? </p>
75
2008-10-01T14:37:17Z
157,975
<p><a href="http://docs.python.org/lib/module-base64.html">Base64 encoding</a> is in the standard library and will do to stop shoulder surfers:</p> <pre><code>&gt;&gt;&gt; import base64 &gt;&gt;&gt; print base64.b64encode("password") cGFzc3dvcmQ= &gt;&gt;&gt; print base64.b64decode("cGFzc3dvcmQ=") password </code></pre>
69
2008-10-01T14:43:51Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ? </p>
75
2008-10-01T14:37:17Z
158,180
<p>Your operating system probably provides facilities for encrypting data securely. For instance, on Windows there is DPAPI (data protection API). Why not ask the user for their credentials the first time you run then squirrel them away encrypted for subsequent runs?</p>
2
2008-10-01T15:22:32Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ? </p>
75
2008-10-01T14:37:17Z
158,221
<p>How about importing the username and password from a file external to the script? That way even if someone got hold of the script, they wouldn't automatically get the password.</p>
10
2008-10-01T15:28:38Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ? </p>
75
2008-10-01T14:37:17Z
158,248
<p>Douglas F Shearer's is the generally approved solution in Unix when you need to specify a password for a remote login.<br /> You add a <strong>--password-from-file</strong> option to specify the path and read plaintext from a file.<br /> The file can then be in the user's own area protected by the operating system. It also allows different users to automatically pick up their own own file.</p> <p>For passwords that the user of the script isn't allowed to know - you can run the script with elavated permission and have the password file owned by that root/admin user.</p>
33
2008-10-01T15:34:13Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ? </p>
75
2008-10-01T14:37:17Z
158,387
<p>The best solution, assuming the username and password can't be given at runtime by the user, is probably a separate source file containing only variable initialization for the username and password that is imported into your main code. This file would only need editing when the credentials change. Otherwise, if you're only worried about shoulder surfers with average memories, base 64 encoding is probably the easiest solution. ROT13 is just too easy to decode manually, isn't case sensitive and retains too much meaning in it's encrypted state. Encode your password and user id outside the python script. Have he script decode at runtime for use.</p> <p>Giving scripts credentials for automated tasks is always a risky proposal. Your script should have its own credentials and the account it uses should have no access other than exactly what is necessary. At least the password should be long and rather random.</p>
15
2008-10-01T16:09:40Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ? </p>
75
2008-10-01T14:37:17Z
158,450
<p>This is a pretty common problem. Typically the best you can do is to either </p> <p>A) create some kind of ceasar cipher function to encode/decode (just not rot13) or B) the preferred method is to use an encryption key, within reach of your program, encode/decode the password. In which you can use file protection to protect access the key. Along those lines if your app runs as a service/daemon (like a webserver) you can put your key into a password protected keystore with the password input as part of the service startup. It'll take an admin to restart your app, but you will have really good pretection for your configuration passwords.</p>
4
2008-10-01T16:19:00Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ? </p>
75
2008-10-01T14:37:17Z
160,042
<p>base64 is the way to go for your simple needs. There is no need to import anything:</p> <pre><code>&gt;&gt;&gt; 'your string'.encode('base64') 'eW91ciBzdHJpbmc=\n' &gt;&gt;&gt; _.decode('base64') 'your string' </code></pre>
10
2008-10-01T22:26:09Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ? </p>
75
2008-10-01T14:37:17Z
160,053
<p>Place the configuration information in a encrypted config file. Query this info in your code using an key. Place this key in a separate file per environment, and don't store it with your code.</p>
1
2008-10-01T22:29:38Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ? </p>
75
2008-10-01T14:37:17Z
6,451,826
<p>If you are working on a Unix system, take advantage of the netrc module in the standard Python library. It reads passwords from a separate text file (.netrc), which has the format decribed <a href="http://www.mavetju.org/unix/netrc.php">here</a>.</p> <p>Here is a small usage example:</p> <pre><code>import netrc # Define which host in the .netrc file to use HOST = 'mailcluster.loopia.se' # Read from the .netrc file in your home directory secrets = netrc.netrc() username, account, password = secrets.authenticators( HOST ) print username, password </code></pre>
17
2011-06-23T09:17:55Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ? </p>
75
2008-10-01T14:37:17Z
16,844,309
<p>More homegrown appraoch rather than converting authentication / passwords / username to encrytpted details. <strong>FTPLIB</strong> is just the example. "<strong>pass.csv</strong>" is the csv file name</p> <p>Save password in CSV like below : </p> <p>user_name</p> <p>user_password</p> <p>(With no column heading)</p> <p>Reading the CSV and saving it to a list. </p> <p>Using List elelments as authetntication details.</p> <p>Full code.</p> <pre><code>import os import ftplib import csv cred_detail = [] os.chdir("Folder where the csv file is stored") for row in csv.reader(open("pass.csv","rb")): cred_detail.append(row) ftp = ftplib.FTP('server_name',cred_detail[0][0],cred_detail[1][0]) </code></pre>
1
2013-05-30T19:24:20Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ? </p>
75
2008-10-01T14:37:17Z
22,821,470
<p>Here is a simple method:</p> <ol> <li>Create a python module - let's call it peekaboo.py. </li> <li>In peekaboo.py, include both the password and any code needing that password</li> <li>Create a compiled version - peekaboo.pyc - by importing this module (via python commandline, etc...).</li> <li>Now, delete peekaboo.py. </li> <li>You can now happily import peekaboo relying only on peekaboo.pyc. Since peekaboo.pyc is byte compiled it is not readable to the casual user.</li> </ol> <p>This should be a bit more secure than base64 decoding - although it is vulnerable to a py_to_pyc decompiler.</p>
10
2014-04-02T19:45:46Z
[ "python", "security" ]
Hiding a password in a (python) script
157,938
<p>I have got a python script which is creating an ODBC connection. The ODBC connection is generated with a connection string. In this connection string I have to include the username and password for this connection. </p> <p>Is there an easy way to obscure this password in the file (just that nobody can read the password when I'm editing the file) ? </p>
75
2008-10-01T14:37:17Z
38,073,122
<p>Do you know pit?</p> <p><a href="https://pypi.python.org/pypi/pit" rel="nofollow">https://pypi.python.org/pypi/pit</a> (py2 only (version 0.3))</p> <p><a href="https://github.com/yoshiori/pit" rel="nofollow">https://github.com/yoshiori/pit</a> (it will work on py3 (current version 0.4))</p> <p>test.py</p> <pre><code>from pit import Pit config = Pit.get('section-name', {'require': { 'username': 'DEFAULT STRING', 'password': 'DEFAULT STRING', }}) print(config) </code></pre> <p>Run:</p> <pre><code>$ python test.py {'password': 'my-password', 'username': 'my-name'} </code></pre> <p>~/.pit/default.yml:</p> <pre><code>section-name: password: my-password username: my-name </code></pre>
0
2016-06-28T10:03:26Z
[ "python", "security" ]
Python module dependency
158,268
<p>Ok I have two modules, each containing a class, the problem is their classes reference each other.</p> <p>Lets say for example I had a room module and a person module containing CRoom and CPerson.</p> <p>The CRoom class contains infomation about the room, and a CPerson list of every one in the room.</p> <p>The CPerson class however sometimes needs to use the CRoom class for the room its in, for example to find the door, or too see who else is in the room.</p> <p>The problem is with the two modules importing each other I just get an import error on which ever is being imported second :(</p> <p>In c++ I could solve this by only including the headers, and since in both cases the classes just have pointers to the other class, a forward declaration would suffice for the header eg:</p> <pre><code>class CPerson;//forward declare class CRoom { std::set&lt;CPerson*&gt; People; ... </code></pre> <p>Is there anyway to do this in python, other than placing both classes in the same module or something like that?</p> <p>edit: added python example showing problem using above classes</p> <p>error:</p> <blockquote> <p>Traceback (most recent call last):<br> File "C:\Projects\python\test\main.py", line 1, in <br> from room import CRoom<br> File "C:\Projects\python\test\room.py", line 1, in <br> from person import CPerson<br> File "C:\Projects\python\test\person.py", line 1, in <br> from room import CRoom<br> ImportError: cannot import name CRoom<br> room.py</p> </blockquote> <pre><code>from person import CPerson class CRoom: def __init__(Self): Self.People = {} Self.NextId = 0 def AddPerson(Self, FirstName, SecondName, Gender): Id = Self.NextId Self.NextId += 1# Person = CPerson(FirstName,SecondName,Gender,Id) Self.People[Id] = Person return Person def FindDoorAndLeave(Self, PersonId): del Self.People[PeopleId] </code></pre> <p>person.py</p> <pre><code>from room import CRoom class CPerson: def __init__(Self, Room, FirstName, SecondName, Gender, Id): Self.Room = Room Self.FirstName = FirstName Self.SecondName = SecondName Self.Gender = Gender Self.Id = Id def Leave(Self): Self.Room.FindDoorAndLeave(Self.Id) </code></pre>
15
2008-10-01T15:38:58Z
158,326
<p>Do you actually need to reference the classes at class definition time? ie.</p> <pre><code> class CRoom(object): person = CPerson("a person") </code></pre> <p>Or (more likely), do you just need to use CPerson in the methods of your class (and vice versa). eg:</p> <pre><code>class CRoom(object): def getPerson(self): return CPerson("someone") </code></pre> <p>If the second, there's no problem - as by the time the method gets <strong>called</strong> rather than defined, the module will be imported. Your sole problem is how to refer to it. Likely you're doing something like:</p> <pre><code>from CRoom import CPerson # or even import * </code></pre> <p>With circularly referencing modules, you can't do this, as at the point one module imports another, the original modules body won't have finished executing, so the namespace will be incomplete. Instead, use qualified references. ie:</p> <pre><code>#croom.py import cperson class CRoom(object): def getPerson(self): return cperson.CPerson("someone") </code></pre> <p>Here, python doesn't need to lookup the attribute on the namespace until the method actually gets called, by which time both modules should have completed their initialisation.</p>
7
2008-10-01T15:52:34Z
[ "python", "module", "circular-dependency" ]
Python module dependency
158,268
<p>Ok I have two modules, each containing a class, the problem is their classes reference each other.</p> <p>Lets say for example I had a room module and a person module containing CRoom and CPerson.</p> <p>The CRoom class contains infomation about the room, and a CPerson list of every one in the room.</p> <p>The CPerson class however sometimes needs to use the CRoom class for the room its in, for example to find the door, or too see who else is in the room.</p> <p>The problem is with the two modules importing each other I just get an import error on which ever is being imported second :(</p> <p>In c++ I could solve this by only including the headers, and since in both cases the classes just have pointers to the other class, a forward declaration would suffice for the header eg:</p> <pre><code>class CPerson;//forward declare class CRoom { std::set&lt;CPerson*&gt; People; ... </code></pre> <p>Is there anyway to do this in python, other than placing both classes in the same module or something like that?</p> <p>edit: added python example showing problem using above classes</p> <p>error:</p> <blockquote> <p>Traceback (most recent call last):<br> File "C:\Projects\python\test\main.py", line 1, in <br> from room import CRoom<br> File "C:\Projects\python\test\room.py", line 1, in <br> from person import CPerson<br> File "C:\Projects\python\test\person.py", line 1, in <br> from room import CRoom<br> ImportError: cannot import name CRoom<br> room.py</p> </blockquote> <pre><code>from person import CPerson class CRoom: def __init__(Self): Self.People = {} Self.NextId = 0 def AddPerson(Self, FirstName, SecondName, Gender): Id = Self.NextId Self.NextId += 1# Person = CPerson(FirstName,SecondName,Gender,Id) Self.People[Id] = Person return Person def FindDoorAndLeave(Self, PersonId): del Self.People[PeopleId] </code></pre> <p>person.py</p> <pre><code>from room import CRoom class CPerson: def __init__(Self, Room, FirstName, SecondName, Gender, Id): Self.Room = Room Self.FirstName = FirstName Self.SecondName = SecondName Self.Gender = Gender Self.Id = Id def Leave(Self): Self.Room.FindDoorAndLeave(Self.Id) </code></pre>
15
2008-10-01T15:38:58Z
158,331
<p>You could just alias the second one.</p> <p>import CRoom</p> <p>CPerson = CRoom.CPerson</p>
1
2008-10-01T15:53:19Z
[ "python", "module", "circular-dependency" ]
Python module dependency
158,268
<p>Ok I have two modules, each containing a class, the problem is their classes reference each other.</p> <p>Lets say for example I had a room module and a person module containing CRoom and CPerson.</p> <p>The CRoom class contains infomation about the room, and a CPerson list of every one in the room.</p> <p>The CPerson class however sometimes needs to use the CRoom class for the room its in, for example to find the door, or too see who else is in the room.</p> <p>The problem is with the two modules importing each other I just get an import error on which ever is being imported second :(</p> <p>In c++ I could solve this by only including the headers, and since in both cases the classes just have pointers to the other class, a forward declaration would suffice for the header eg:</p> <pre><code>class CPerson;//forward declare class CRoom { std::set&lt;CPerson*&gt; People; ... </code></pre> <p>Is there anyway to do this in python, other than placing both classes in the same module or something like that?</p> <p>edit: added python example showing problem using above classes</p> <p>error:</p> <blockquote> <p>Traceback (most recent call last):<br> File "C:\Projects\python\test\main.py", line 1, in <br> from room import CRoom<br> File "C:\Projects\python\test\room.py", line 1, in <br> from person import CPerson<br> File "C:\Projects\python\test\person.py", line 1, in <br> from room import CRoom<br> ImportError: cannot import name CRoom<br> room.py</p> </blockquote> <pre><code>from person import CPerson class CRoom: def __init__(Self): Self.People = {} Self.NextId = 0 def AddPerson(Self, FirstName, SecondName, Gender): Id = Self.NextId Self.NextId += 1# Person = CPerson(FirstName,SecondName,Gender,Id) Self.People[Id] = Person return Person def FindDoorAndLeave(Self, PersonId): del Self.People[PeopleId] </code></pre> <p>person.py</p> <pre><code>from room import CRoom class CPerson: def __init__(Self, Room, FirstName, SecondName, Gender, Id): Self.Room = Room Self.FirstName = FirstName Self.SecondName = SecondName Self.Gender = Gender Self.Id = Id def Leave(Self): Self.Room.FindDoorAndLeave(Self.Id) </code></pre>
15
2008-10-01T15:38:58Z
158,403
<p><strong>No need to import CRoom</strong></p> <p>You don't use <code>CRoom</code> in <code>person.py</code>, so don't import it. Due to dynamic binding, Python doesn't need to "see all class definitions at compile time".</p> <p>If you actually <em>do</em> use <code>CRoom</code> in <code>person.py</code>, then change <code>from room import CRoom</code> to <code>import room</code> and use module-qualified form <code>room.CRoom</code>. See <a href="http://effbot.org/zone/import-confusion.htm#circular-imports">Effbot's Circular Imports</a> for details.</p> <p><em>Sidenote:</em> you probably have an error in <code>Self.NextId += 1</code> line. It increments <code>NextId</code> of instance, not <code>NextId</code> of class. To increment class's counter use <code>CRoom.NextId += 1</code> or <code>Self.__class__.NextId += 1</code>.</p>
16
2008-10-01T16:11:41Z
[ "python", "module", "circular-dependency" ]
Python module dependency
158,268
<p>Ok I have two modules, each containing a class, the problem is their classes reference each other.</p> <p>Lets say for example I had a room module and a person module containing CRoom and CPerson.</p> <p>The CRoom class contains infomation about the room, and a CPerson list of every one in the room.</p> <p>The CPerson class however sometimes needs to use the CRoom class for the room its in, for example to find the door, or too see who else is in the room.</p> <p>The problem is with the two modules importing each other I just get an import error on which ever is being imported second :(</p> <p>In c++ I could solve this by only including the headers, and since in both cases the classes just have pointers to the other class, a forward declaration would suffice for the header eg:</p> <pre><code>class CPerson;//forward declare class CRoom { std::set&lt;CPerson*&gt; People; ... </code></pre> <p>Is there anyway to do this in python, other than placing both classes in the same module or something like that?</p> <p>edit: added python example showing problem using above classes</p> <p>error:</p> <blockquote> <p>Traceback (most recent call last):<br> File "C:\Projects\python\test\main.py", line 1, in <br> from room import CRoom<br> File "C:\Projects\python\test\room.py", line 1, in <br> from person import CPerson<br> File "C:\Projects\python\test\person.py", line 1, in <br> from room import CRoom<br> ImportError: cannot import name CRoom<br> room.py</p> </blockquote> <pre><code>from person import CPerson class CRoom: def __init__(Self): Self.People = {} Self.NextId = 0 def AddPerson(Self, FirstName, SecondName, Gender): Id = Self.NextId Self.NextId += 1# Person = CPerson(FirstName,SecondName,Gender,Id) Self.People[Id] = Person return Person def FindDoorAndLeave(Self, PersonId): del Self.People[PeopleId] </code></pre> <p>person.py</p> <pre><code>from room import CRoom class CPerson: def __init__(Self, Room, FirstName, SecondName, Gender, Id): Self.Room = Room Self.FirstName = FirstName Self.SecondName = SecondName Self.Gender = Gender Self.Id = Id def Leave(Self): Self.Room.FindDoorAndLeave(Self.Id) </code></pre>
15
2008-10-01T15:38:58Z
158,505
<p>First, naming your arguments with uppercase letters is confusing. Since Python does not have formal, static type checking, we use the <code>UpperCase</code> to mean a class and <code>lowerCase</code> to mean an argument.</p> <p>Second, we don't bother with CRoom and CPerson. Upper case is sufficient to indicate it's a class. The letter C isn't used. <code>Room</code>. <code>Person</code>.</p> <p>Third, we don't usually put things in <strong>One Class Per File</strong> format. A file is a Python module, and we more often import an entire module with all the classes and functions. </p> <p>[I'm aware those are habits -- you don't need to break them today, but they do make it hard to read.]</p> <p>Python doesn't use statically defined types like C++. When you define a method function, you don't formally define the data type of the arguments to that function. You merely list some variable names. Hopefully, the client class will provide arguments of the correct type.</p> <p>At run time, when you make a method request, then Python has to be sure the object has the method. NOTE. Python doesn't check to see if the object is the right type -- that doesn't matter. It only checks to see if it has the right method.</p> <p>The loop between <code>room.Room</code> and <code>person.Person</code> is a problem. You don't need to include one when defining the other.</p> <p>It's safest to import the entire module.</p> <p>Here's <code>room.py</code></p> <pre><code>import person class Room( object ): def __init__( self ): self.nextId= 0 self.people= {} def addPerson(self, firstName, secondName, gender): id= self.NextId self.nextId += 1 thePerson = person.Person(firstName,secondName,gender,id) self.people[id] = thePerson return thePerson </code></pre> <p>Works fine as long as Person is eventually defined in the namespace where this is executing. Person does not have to be known when you define the class. </p> <p>Person does not have to be known until runtime when then Person(...) expression is evaluated.</p> <p>Here's <code>person.py</code></p> <pre><code>import room class Person( object ): def something( self, x, y ): aRoom= room.Room( ) aRoom.addPerson( self.firstName, self.lastName, self.gender ) </code></pre> <p>Your <code>main.py</code> looks like this</p> <pre><code>import room import person r = room.Room( ... ) r.addPerson( "some", "name", "M" ) print r </code></pre>
2
2008-10-01T16:30:26Z
[ "python", "module", "circular-dependency" ]
Python module dependency
158,268
<p>Ok I have two modules, each containing a class, the problem is their classes reference each other.</p> <p>Lets say for example I had a room module and a person module containing CRoom and CPerson.</p> <p>The CRoom class contains infomation about the room, and a CPerson list of every one in the room.</p> <p>The CPerson class however sometimes needs to use the CRoom class for the room its in, for example to find the door, or too see who else is in the room.</p> <p>The problem is with the two modules importing each other I just get an import error on which ever is being imported second :(</p> <p>In c++ I could solve this by only including the headers, and since in both cases the classes just have pointers to the other class, a forward declaration would suffice for the header eg:</p> <pre><code>class CPerson;//forward declare class CRoom { std::set&lt;CPerson*&gt; People; ... </code></pre> <p>Is there anyway to do this in python, other than placing both classes in the same module or something like that?</p> <p>edit: added python example showing problem using above classes</p> <p>error:</p> <blockquote> <p>Traceback (most recent call last):<br> File "C:\Projects\python\test\main.py", line 1, in <br> from room import CRoom<br> File "C:\Projects\python\test\room.py", line 1, in <br> from person import CPerson<br> File "C:\Projects\python\test\person.py", line 1, in <br> from room import CRoom<br> ImportError: cannot import name CRoom<br> room.py</p> </blockquote> <pre><code>from person import CPerson class CRoom: def __init__(Self): Self.People = {} Self.NextId = 0 def AddPerson(Self, FirstName, SecondName, Gender): Id = Self.NextId Self.NextId += 1# Person = CPerson(FirstName,SecondName,Gender,Id) Self.People[Id] = Person return Person def FindDoorAndLeave(Self, PersonId): del Self.People[PeopleId] </code></pre> <p>person.py</p> <pre><code>from room import CRoom class CPerson: def __init__(Self, Room, FirstName, SecondName, Gender, Id): Self.Room = Room Self.FirstName = FirstName Self.SecondName = SecondName Self.Gender = Gender Self.Id = Id def Leave(Self): Self.Room.FindDoorAndLeave(Self.Id) </code></pre>
15
2008-10-01T15:38:58Z
158,620
<p>@<a href="#158505" rel="nofollow">S.Lott</a> if i don't import anything into the room module I get an undefined error instead (I imported it into the main module like you showed)</p> <blockquote> <p>Traceback (most recent call last):<br /> File "C:\Projects\python\test\main.py", line 6, in <br /> Ben = Room.AddPerson('Ben', 'Blacker', 'Male')<br /> File "C:\Projects\python\test\room.py", line 12, in AddPerson<br /> Person = CPerson(FirstName,SecondName,Gender,Id)<br /> NameError: global name 'CPerson' is not defined </p> </blockquote> <p>Also, the reason there diffrent modules is where I encountered the problem to start with the container class (ieg the room) is already several hundred lines, so I wanted the items in it (eg the people) in a seperate file.</p> <p>EDIT: main.py</p> <pre><code>from room import CRoom from person import CPerson Room = CRoom() Ben = Room.AddPerson('Ben', 'Blacker', 'Male') Tom = Room.AddPerson('Tom', 'Smith', 'Male') Ben.Leave() </code></pre>
0
2008-10-01T16:55:17Z
[ "python", "module", "circular-dependency" ]
Best way to store and use a large text-file in python
158,546
<p>I'm creating a networked server for a boggle-clone I wrote in python, which accepts users, solves the boards, and scores the player input. The dictionary file I'm using is 1.8MB (the ENABLE2K dictionary), and I need it to be available to several game solver classes. Right now, I have it so that each class iterates through the file line-by-line and generates a hash table(associative array), but the more solver classes I instantiate, the more memory it takes up.</p> <p>What I would like to do is import the dictionary file once and pass it to each solver instance as they need it. But what is the best way to do this? Should I import the dictionary in the global space, then access it in the solver class as globals()['dictionary']? Or should I import the dictionary then pass it as an argument to the class constructor? Is one of these better than the other? Is there a third option?</p>
4
2008-10-01T16:37:08Z
158,622
<p>Even though it is essentially a singleton at this point, the usual arguments against globals apply. For a pythonic singleton-substitute, look up the "borg" object. </p> <p>That's really the only difference. Once the dictionary object is created, you are only binding new references as you pass it along unless if you explicitly perform a deep copy. It makes sense that it is centrally constructed once and only once so long as each solver instance does not require a private copy for modification. </p>
1
2008-10-01T16:55:23Z
[ "python" ]
Best way to store and use a large text-file in python
158,546
<p>I'm creating a networked server for a boggle-clone I wrote in python, which accepts users, solves the boards, and scores the player input. The dictionary file I'm using is 1.8MB (the ENABLE2K dictionary), and I need it to be available to several game solver classes. Right now, I have it so that each class iterates through the file line-by-line and generates a hash table(associative array), but the more solver classes I instantiate, the more memory it takes up.</p> <p>What I would like to do is import the dictionary file once and pass it to each solver instance as they need it. But what is the best way to do this? Should I import the dictionary in the global space, then access it in the solver class as globals()['dictionary']? Or should I import the dictionary then pass it as an argument to the class constructor? Is one of these better than the other? Is there a third option?</p>
4
2008-10-01T16:37:08Z
158,753
<p>If you create a dictionary.py module, containing code which reads the file and builds a dictionary, this code will only be executed the first time it is imported. Further imports will return a reference to the existing module instance. As such, your classes can:</p> <pre><code>import dictionary dictionary.words[whatever] </code></pre> <p>where dictionary.py has:</p> <pre><code>words = {} # read file and add to 'words' </code></pre>
10
2008-10-01T17:30:41Z
[ "python" ]
Best way to store and use a large text-file in python
158,546
<p>I'm creating a networked server for a boggle-clone I wrote in python, which accepts users, solves the boards, and scores the player input. The dictionary file I'm using is 1.8MB (the ENABLE2K dictionary), and I need it to be available to several game solver classes. Right now, I have it so that each class iterates through the file line-by-line and generates a hash table(associative array), but the more solver classes I instantiate, the more memory it takes up.</p> <p>What I would like to do is import the dictionary file once and pass it to each solver instance as they need it. But what is the best way to do this? Should I import the dictionary in the global space, then access it in the solver class as globals()['dictionary']? Or should I import the dictionary then pass it as an argument to the class constructor? Is one of these better than the other? Is there a third option?</p>
4
2008-10-01T16:37:08Z
159,341
<p>Depending on what your dict contains, you may be interested in the 'shelve' or 'anydbm' modules. They give you dict-like interfaces (just strings as keys and items for 'anydbm', and strings as keys and any python object as item for 'shelve') but the data is actually in a DBM file (gdbm, ndbm, dbhash, bsddb, depending on what's available on the platform.) You probably still want to share the actual database between classes as you are asking for, but it would avoid the parsing-the-textfile step as well as the keeping-it-all-in-memory bit.</p>
0
2008-10-01T19:38:26Z
[ "python" ]
Best way to store and use a large text-file in python
158,546
<p>I'm creating a networked server for a boggle-clone I wrote in python, which accepts users, solves the boards, and scores the player input. The dictionary file I'm using is 1.8MB (the ENABLE2K dictionary), and I need it to be available to several game solver classes. Right now, I have it so that each class iterates through the file line-by-line and generates a hash table(associative array), but the more solver classes I instantiate, the more memory it takes up.</p> <p>What I would like to do is import the dictionary file once and pass it to each solver instance as they need it. But what is the best way to do this? Should I import the dictionary in the global space, then access it in the solver class as globals()['dictionary']? Or should I import the dictionary then pass it as an argument to the class constructor? Is one of these better than the other? Is there a third option?</p>
4
2008-10-01T16:37:08Z
159,441
<p>Adam, remember that in Python when you say:</p> <pre><code>a = read_dict_from_file() b = a </code></pre> <p>... you are not actually <em>copying</em> <code>a</code>, and thus using more memory, you are merely making <code>b</code> another reference to the same object.</p> <p>So basically <strong>any</strong> of the solutions you propose will be far better in terms of memory usage. Basically, read in the dictionary <strong>once</strong> and then hang on to a reference to that. Whether you do it with a global variable, or pass it to each instance, or something else, you'll be referencing the same object and not duplicating it.</p> <p>Which one is most Pythonic? That's a whole 'nother can of worms, but here's what I would do personally:</p> <pre><code>def main(args): run_initialization_stuff() dictionary = read_dictionary_from_file() solvers = [ Solver(class=x, dictionary=dictionary) for x in len(number_of_solvers) ] </code></pre> <p>HTH.</p>
1
2008-10-01T20:00:11Z
[ "python" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another program doesn't seem very elegant not to mention error prone. </p> <p>Does anyone know a cross platform method (windows and linux) method to get the MAC address? If not, does anyone know any more elegant methods then those I listed above?</p>
68
2008-10-01T18:51:36Z
159,150
<p>netifaces is a good module to use for getting the mac address (and other addresses). It's crossplatform and makes a bit more sense than using socket or uuid.</p> <pre><code>&gt;&gt;&gt; import netifaces &gt;&gt;&gt; netifaces.interfaces() ['lo', 'eth0', 'tun2'] &gt;&gt;&gt; netifaces.ifaddresses('eth0')[netifaces.AF_LINK] [{'addr': '08:00:27:50:f2:51', 'broadcast': 'ff:ff:ff:ff:ff:ff'}] </code></pre> <hr> <ul> <li><p><a href="https://pypi.python.org/pypi/netifaces">pypi location</a></p></li> <li><p><a href="http://alastairs-place.net/projects/netifaces/">Good Intro to netifaces</a></p></li> </ul>
13
2008-10-01T18:55:14Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another program doesn't seem very elegant not to mention error prone. </p> <p>Does anyone know a cross platform method (windows and linux) method to get the MAC address? If not, does anyone know any more elegant methods then those I listed above?</p>
68
2008-10-01T18:51:36Z
159,169
<p>I dont know of a unified way, but heres something that you might find useful:</p> <p><a href="http://www.codeguru.com/Cpp/I-N/network/networkinformation/article.php/c5451" rel="nofollow">http://www.codeguru.com/Cpp/I-N/network/networkinformation/article.php/c5451</a></p> <p>What I would do in this case would be to wrap these up into a function, and based on the OS it would run the proper command, parse as required and return only the MAC address formatted as you want. Its ofcourse all the same, except that you only have to do it once, and it looks cleaner from the main code.</p>
1
2008-10-01T19:02:33Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another program doesn't seem very elegant not to mention error prone. </p> <p>Does anyone know a cross platform method (windows and linux) method to get the MAC address? If not, does anyone know any more elegant methods then those I listed above?</p>
68
2008-10-01T18:51:36Z
159,195
<p>Python 2.5 includes an uuid implementation which (in at least one version) needs the mac address. You can import the mac finding function into your own code easily:</p> <pre><code>from uuid import getnode as get_mac mac = get_mac() </code></pre> <p>The return value is the mac address as 48 bit integer.</p>
92
2008-10-01T19:06:30Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another program doesn't seem very elegant not to mention error prone. </p> <p>Does anyone know a cross platform method (windows and linux) method to get the MAC address? If not, does anyone know any more elegant methods then those I listed above?</p>
68
2008-10-01T18:51:36Z
159,236
<p>For Linux you can retrieve the MAC address using a SIOCGIFHWADDR ioctl.</p> <pre><code>struct ifreq ifr; uint8_t macaddr[6]; if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) &lt; 0) return -1; strcpy(ifr.ifr_name, "eth0"); if (ioctl(s, SIOCGIFHWADDR, (void *)&amp;ifr) == 0) { if (ifr.ifr_hwaddr.sa_family == ARPHRD_ETHER) { memcpy(macaddr, ifr.ifr_hwaddr.sa_data, 6); return 0; ... etc ... </code></pre> <p>You've tagged the question "python". I don't know of an existing Python module to get this information. You could use <A HREF="http://pypi.python.org/pypi/ctypes/1.0.2" rel="nofollow">ctypes</A> to call the ioctl directly.</p>
-5
2008-10-01T19:12:56Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another program doesn't seem very elegant not to mention error prone. </p> <p>Does anyone know a cross platform method (windows and linux) method to get the MAC address? If not, does anyone know any more elegant methods then those I listed above?</p>
68
2008-10-01T18:51:36Z
159,992
<p>Note that you can build your own cross-platform library in python using conditional imports. e.g.</p> <pre><code>import platform if platform.system() == 'Linux': import LinuxMac mac_address = LinuxMac.get_mac_address() elif platform.system() == 'Windows': # etc </code></pre> <p>This will allow you to use os.system calls or platform-specific libraries.</p>
2
2008-10-01T22:09:58Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another program doesn't seem very elegant not to mention error prone. </p> <p>Does anyone know a cross platform method (windows and linux) method to get the MAC address? If not, does anyone know any more elegant methods then those I listed above?</p>
68
2008-10-01T18:51:36Z
160,821
<p>One other thing that you should note is that <code>uuid.getnode()</code> can fake the MAC addr by returning a random 48-bit number which may not be what you are expecting. Also, there's no explicit indication that the MAC address has been faked, but you could detect it by calling <code>getnode()</code> twice and seeing if the result varies. If the same value is returned by both calls, you have the MAC address, otherwise you are getting a faked address.</p> <pre><code>&gt;&gt;&gt; print uuid.getnode.__doc__ Get the hardware address as a 48-bit positive integer. The first time this runs, it may launch a separate program, which could be quite slow. If all attempts to obtain the hardware address fail, we choose a random 48-bit number with its eighth bit set to 1 as recommended in RFC 4122. </code></pre>
17
2008-10-02T03:49:54Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another program doesn't seem very elegant not to mention error prone. </p> <p>Does anyone know a cross platform method (windows and linux) method to get the MAC address? If not, does anyone know any more elegant methods then those I listed above?</p>
68
2008-10-01T18:51:36Z
4,789,267
<p>The pure python solution for this problem under Linux to get the MAC for a specific local interface, originally posted as a comment by vishnubob and improved by on Ben Mackey in <a href="http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/">this activestate recipe</a></p> <pre><code>#!/usr/bin/python import fcntl, socket, struct def getHwAddr(ifname): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15])) return ':'.join(['%02x' % ord(char) for char in info[18:24]]) print getHwAddr('eth0') </code></pre>
57
2011-01-25T01:57:17Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another program doesn't seem very elegant not to mention error prone. </p> <p>Does anyone know a cross platform method (windows and linux) method to get the MAC address? If not, does anyone know any more elegant methods then those I listed above?</p>
68
2008-10-01T18:51:36Z
17,884,450
<p>For Linux let me introduce a shell script that will show the mac address and allows to change it (MAC sniffing).</p> <pre><code> ifconfig eth0 | grep HWaddr |cut -dH -f2|cut -d\ -f2 00:26:6c:df:c3:95 </code></pre> <p>Cut arguements may dffer (I am not an expert) try:</p> <pre><code>ifconfig etho | grep HWaddr eth0 Link encap:Ethernet HWaddr 00:26:6c:df:c3:95 </code></pre> <p>To change MAC we may do:</p> <pre><code>ifconfig eth0 down ifconfig eth0 hw ether 00:80:48:BA:d1:30 ifconfig eth0 up </code></pre> <p>will change mac address to 00:80:48:BA:d1:30 (temporarily, will restore to actual one upon reboot).</p>
2
2013-07-26T14:46:26Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another program doesn't seem very elegant not to mention error prone. </p> <p>Does anyone know a cross platform method (windows and linux) method to get the MAC address? If not, does anyone know any more elegant methods then those I listed above?</p>
68
2008-10-01T18:51:36Z
18,031,954
<p>Using my answer from here: <a href="http://stackoverflow.com/a/18031868/2362361">http://stackoverflow.com/a/18031868/2362361</a></p> <p>It would be important to know to which iface you want the MAC for since many can exist (bluetooth, several nics, etc.).</p> <p>This does the job when you know the IP of the iface you need the MAC for, using <code>netifaces</code> (available in PyPI):</p> <pre><code>import netifaces as nif def mac_for_ip(ip): 'Returns a list of MACs for interfaces that have given IP, returns None if not found' for i in nif.interfaces(): addrs = nif.ifaddresses(i) try: if_mac = addrs[nif.AF_LINK][0]['addr'] if_ip = addrs[nif.AF_INET][0]['addr'] except IndexError, KeyError: #ignore ifaces that dont have MAC or IP if_mac = if_ip = None if if_ip == ip: return if_mac return None </code></pre> <p>Testing:</p> <pre><code>&gt;&gt;&gt; mac_for_ip('169.254.90.191') '2c:41:38:0a:94:8b' </code></pre>
7
2013-08-03T10:40:10Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another program doesn't seem very elegant not to mention error prone. </p> <p>Does anyone know a cross platform method (windows and linux) method to get the MAC address? If not, does anyone know any more elegant methods then those I listed above?</p>
68
2008-10-01T18:51:36Z
27,617,579
<p>for Linux solution</p> <pre><code>INTERFACE_NAME = "eth0" ####################################### def get_mac_id(ifname=INTERFACE_NAME): import commands words = commands.getoutput("ifconfig " + ifname).split() if "HWaddr" in words: return words[ words.index("HWaddr") + 1 ] else: return 'No MAC Address Found!' </code></pre> <p>Usage:</p> <pre><code>print get_mac_id(ifname="eth0") </code></pre>
-1
2014-12-23T09:32:56Z
[ "python", "windows", "linux", "networking" ]
Getting MAC Address
159,137
<p>I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another program doesn't seem very elegant not to mention error prone. </p> <p>Does anyone know a cross platform method (windows and linux) method to get the MAC address? If not, does anyone know any more elegant methods then those I listed above?</p>
68
2008-10-01T18:51:36Z
32,080,877
<p>Sometimes we have more than one net interface.</p> <p>A simple method to find out the mac address of a specific interface, is:</p> <pre><code>def getmac(interface): try: mac = open('/sys/class/net/'+interface+'/address').readline() except: mac = "00:00:00:00:00:00" return mac[0:17] </code></pre> <p>to call the method is simple</p> <pre><code>myMAC = getmac("wlan0") </code></pre>
5
2015-08-18T19:16:50Z
[ "python", "windows", "linux", "networking" ]
Nginx + fastcgi truncation problem
159,541
<p>I'm running a Django site using the fastcgi interface to nginx. However, some pages are being served truncated (i.e. the page source just stops, sometimes in the middle of a tag). How do I fix this (let me know what extra information is needed, and I'll post it)</p> <p>Details:</p> <p>I'm using flup, and spawning the fastcgi server with the following command:</p> <pre><code>python ./manage.py runfcgi umask=000 maxchildren=5 maxspare=1 minspare=0 method=prefork socket=/path/to/runfiles/django.sock pidfile=/path/to/runfiles/django.pid </code></pre> <p>The nginx config is as follows:</p> <pre><code># search and replace this: {project_location} pid /path/to/runfiles/nginx.pid; worker_processes 2; error_log /path/to/runfiles/error_log; events { worker_connections 1024; use epoll; } http { # default nginx location include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] ' '"$request" $status $bytes_sent ' '"$http_referer" "$http_user_agent" ' '"$gzip_ratio"'; client_header_timeout 3m; client_body_timeout 3m; send_timeout 3m; connection_pool_size 256; client_header_buffer_size 1k; large_client_header_buffers 4 2k; request_pool_size 4k; output_buffers 4 32k; postpone_output 1460; sendfile on; tcp_nopush on; keepalive_timeout 75 20; tcp_nodelay on; client_max_body_size 10m; client_body_buffer_size 256k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; client_body_temp_path /path/to/runfiles/client_body_temp; proxy_temp_path /path/to/runfiles/proxy_temp; fastcgi_temp_path /path/to/runfiles/fastcgi_temp; gzip on; gzip_min_length 1100; gzip_buffers 4 32k; gzip_types text/plain text/html application/x-javascript text/xml text/css; ignore_invalid_headers on; server { listen 80; server_name alpha2.sonyalabs.com; index index.html; root /path/to/django-root/static; # static resources location ~* ^/static/.*$ { root /path/to/django-root; expires 30d; break; } location / { # host and port to fastcgi server fastcgi_pass unix:/path/to/runfiles/django.sock; fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param QUERY_STRING $query_string; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_pass_header Authorization; fastcgi_intercept_errors off; } location /403.html { root /usr/local/nginx; access_log off; } location /401.html { root /usr/local/nginx; access_log off; } location /404.html { root /usr/local/nginx; access_log off; } location = /_.gif { empty_gif; access_log off; } access_log /path/to/runfiles/localhost.access_log main; error_log /path/to/runfiles/localhost.error_log; } } </code></pre>
10
2008-10-01T20:26:12Z
159,819
<p>What fastcgi interface are you using and how. Is it flup? If yes, paste the way you spawn the server and how it's hooked into nginx. Without that information it's just guessing what could go wrong.</p> <p>Possible problems:</p> <ul> <li>nginx is buggy. At least lighttpd has horrible fastcgi bugs, I wouldn't wonder if nginx has some too :)</li> <li>Django is dying with a traceback in an internal system that is not properly catched and closes the fastcgi server which you can't see from the client. In that situation wrap the fastcgi server application call and try/except it to print the exception.</li> </ul> <p>But server log and config would be great.</p>
3
2008-10-01T21:21:52Z
[ "python", "django", "nginx", "fastcgi" ]
Nginx + fastcgi truncation problem
159,541
<p>I'm running a Django site using the fastcgi interface to nginx. However, some pages are being served truncated (i.e. the page source just stops, sometimes in the middle of a tag). How do I fix this (let me know what extra information is needed, and I'll post it)</p> <p>Details:</p> <p>I'm using flup, and spawning the fastcgi server with the following command:</p> <pre><code>python ./manage.py runfcgi umask=000 maxchildren=5 maxspare=1 minspare=0 method=prefork socket=/path/to/runfiles/django.sock pidfile=/path/to/runfiles/django.pid </code></pre> <p>The nginx config is as follows:</p> <pre><code># search and replace this: {project_location} pid /path/to/runfiles/nginx.pid; worker_processes 2; error_log /path/to/runfiles/error_log; events { worker_connections 1024; use epoll; } http { # default nginx location include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] ' '"$request" $status $bytes_sent ' '"$http_referer" "$http_user_agent" ' '"$gzip_ratio"'; client_header_timeout 3m; client_body_timeout 3m; send_timeout 3m; connection_pool_size 256; client_header_buffer_size 1k; large_client_header_buffers 4 2k; request_pool_size 4k; output_buffers 4 32k; postpone_output 1460; sendfile on; tcp_nopush on; keepalive_timeout 75 20; tcp_nodelay on; client_max_body_size 10m; client_body_buffer_size 256k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; client_body_temp_path /path/to/runfiles/client_body_temp; proxy_temp_path /path/to/runfiles/proxy_temp; fastcgi_temp_path /path/to/runfiles/fastcgi_temp; gzip on; gzip_min_length 1100; gzip_buffers 4 32k; gzip_types text/plain text/html application/x-javascript text/xml text/css; ignore_invalid_headers on; server { listen 80; server_name alpha2.sonyalabs.com; index index.html; root /path/to/django-root/static; # static resources location ~* ^/static/.*$ { root /path/to/django-root; expires 30d; break; } location / { # host and port to fastcgi server fastcgi_pass unix:/path/to/runfiles/django.sock; fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param QUERY_STRING $query_string; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_pass_header Authorization; fastcgi_intercept_errors off; } location /403.html { root /usr/local/nginx; access_log off; } location /401.html { root /usr/local/nginx; access_log off; } location /404.html { root /usr/local/nginx; access_log off; } location = /_.gif { empty_gif; access_log off; } access_log /path/to/runfiles/localhost.access_log main; error_log /path/to/runfiles/localhost.error_log; } } </code></pre>
10
2008-10-01T20:26:12Z
675,015
<p>try to raise "gzip_buffers" may help.</p> <p>see here: <a href="http://blog.leetsoft.com/2007/7/25/nginx-gzip-ssl" rel="nofollow">http://blog.leetsoft.com/2007/7/25/nginx-gzip-ssl</a></p>
2
2009-03-23T20:00:22Z
[ "python", "django", "nginx", "fastcgi" ]
Nginx + fastcgi truncation problem
159,541
<p>I'm running a Django site using the fastcgi interface to nginx. However, some pages are being served truncated (i.e. the page source just stops, sometimes in the middle of a tag). How do I fix this (let me know what extra information is needed, and I'll post it)</p> <p>Details:</p> <p>I'm using flup, and spawning the fastcgi server with the following command:</p> <pre><code>python ./manage.py runfcgi umask=000 maxchildren=5 maxspare=1 minspare=0 method=prefork socket=/path/to/runfiles/django.sock pidfile=/path/to/runfiles/django.pid </code></pre> <p>The nginx config is as follows:</p> <pre><code># search and replace this: {project_location} pid /path/to/runfiles/nginx.pid; worker_processes 2; error_log /path/to/runfiles/error_log; events { worker_connections 1024; use epoll; } http { # default nginx location include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] ' '"$request" $status $bytes_sent ' '"$http_referer" "$http_user_agent" ' '"$gzip_ratio"'; client_header_timeout 3m; client_body_timeout 3m; send_timeout 3m; connection_pool_size 256; client_header_buffer_size 1k; large_client_header_buffers 4 2k; request_pool_size 4k; output_buffers 4 32k; postpone_output 1460; sendfile on; tcp_nopush on; keepalive_timeout 75 20; tcp_nodelay on; client_max_body_size 10m; client_body_buffer_size 256k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; client_body_temp_path /path/to/runfiles/client_body_temp; proxy_temp_path /path/to/runfiles/proxy_temp; fastcgi_temp_path /path/to/runfiles/fastcgi_temp; gzip on; gzip_min_length 1100; gzip_buffers 4 32k; gzip_types text/plain text/html application/x-javascript text/xml text/css; ignore_invalid_headers on; server { listen 80; server_name alpha2.sonyalabs.com; index index.html; root /path/to/django-root/static; # static resources location ~* ^/static/.*$ { root /path/to/django-root; expires 30d; break; } location / { # host and port to fastcgi server fastcgi_pass unix:/path/to/runfiles/django.sock; fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param QUERY_STRING $query_string; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_pass_header Authorization; fastcgi_intercept_errors off; } location /403.html { root /usr/local/nginx; access_log off; } location /401.html { root /usr/local/nginx; access_log off; } location /404.html { root /usr/local/nginx; access_log off; } location = /_.gif { empty_gif; access_log off; } access_log /path/to/runfiles/localhost.access_log main; error_log /path/to/runfiles/localhost.error_log; } } </code></pre>
10
2008-10-01T20:26:12Z
1,172,861
<p>I'm running very similar configurations to this both on my webhost (Webfaction) and on a local Ubuntu dev server and I don't see any problems. I'm guessing it's a time-out or full buffer that's causing this.</p> <p>Can you post the output of the nginx error log? Also what version of nginx are you using?</p> <p>As a side note it may be worth looking at <a href="http://code.google.com/p/django-logging/wiki/Overview" rel="nofollow">django-logging</a> to find out what your fastcgi process is doing.</p>
0
2009-07-23T16:11:04Z
[ "python", "django", "nginx", "fastcgi" ]
Nginx + fastcgi truncation problem
159,541
<p>I'm running a Django site using the fastcgi interface to nginx. However, some pages are being served truncated (i.e. the page source just stops, sometimes in the middle of a tag). How do I fix this (let me know what extra information is needed, and I'll post it)</p> <p>Details:</p> <p>I'm using flup, and spawning the fastcgi server with the following command:</p> <pre><code>python ./manage.py runfcgi umask=000 maxchildren=5 maxspare=1 minspare=0 method=prefork socket=/path/to/runfiles/django.sock pidfile=/path/to/runfiles/django.pid </code></pre> <p>The nginx config is as follows:</p> <pre><code># search and replace this: {project_location} pid /path/to/runfiles/nginx.pid; worker_processes 2; error_log /path/to/runfiles/error_log; events { worker_connections 1024; use epoll; } http { # default nginx location include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] ' '"$request" $status $bytes_sent ' '"$http_referer" "$http_user_agent" ' '"$gzip_ratio"'; client_header_timeout 3m; client_body_timeout 3m; send_timeout 3m; connection_pool_size 256; client_header_buffer_size 1k; large_client_header_buffers 4 2k; request_pool_size 4k; output_buffers 4 32k; postpone_output 1460; sendfile on; tcp_nopush on; keepalive_timeout 75 20; tcp_nodelay on; client_max_body_size 10m; client_body_buffer_size 256k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; client_body_temp_path /path/to/runfiles/client_body_temp; proxy_temp_path /path/to/runfiles/proxy_temp; fastcgi_temp_path /path/to/runfiles/fastcgi_temp; gzip on; gzip_min_length 1100; gzip_buffers 4 32k; gzip_types text/plain text/html application/x-javascript text/xml text/css; ignore_invalid_headers on; server { listen 80; server_name alpha2.sonyalabs.com; index index.html; root /path/to/django-root/static; # static resources location ~* ^/static/.*$ { root /path/to/django-root; expires 30d; break; } location / { # host and port to fastcgi server fastcgi_pass unix:/path/to/runfiles/django.sock; fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param QUERY_STRING $query_string; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_pass_header Authorization; fastcgi_intercept_errors off; } location /403.html { root /usr/local/nginx; access_log off; } location /401.html { root /usr/local/nginx; access_log off; } location /404.html { root /usr/local/nginx; access_log off; } location = /_.gif { empty_gif; access_log off; } access_log /path/to/runfiles/localhost.access_log main; error_log /path/to/runfiles/localhost.error_log; } } </code></pre>
10
2008-10-01T20:26:12Z
4,515,898
<p>Check your error logs for "Permission denied" errors writing to <code>.../nginx/tmp/...</code> files. Nginx will work fine unless it needs temporary space, and that typically happens at 32K boundaries. If you find these errors, make sure the tmp directory is writable by the user nginx runs as.</p>
5
2010-12-23T04:37:11Z
[ "python", "django", "nginx", "fastcgi" ]
Nginx + fastcgi truncation problem
159,541
<p>I'm running a Django site using the fastcgi interface to nginx. However, some pages are being served truncated (i.e. the page source just stops, sometimes in the middle of a tag). How do I fix this (let me know what extra information is needed, and I'll post it)</p> <p>Details:</p> <p>I'm using flup, and spawning the fastcgi server with the following command:</p> <pre><code>python ./manage.py runfcgi umask=000 maxchildren=5 maxspare=1 minspare=0 method=prefork socket=/path/to/runfiles/django.sock pidfile=/path/to/runfiles/django.pid </code></pre> <p>The nginx config is as follows:</p> <pre><code># search and replace this: {project_location} pid /path/to/runfiles/nginx.pid; worker_processes 2; error_log /path/to/runfiles/error_log; events { worker_connections 1024; use epoll; } http { # default nginx location include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] ' '"$request" $status $bytes_sent ' '"$http_referer" "$http_user_agent" ' '"$gzip_ratio"'; client_header_timeout 3m; client_body_timeout 3m; send_timeout 3m; connection_pool_size 256; client_header_buffer_size 1k; large_client_header_buffers 4 2k; request_pool_size 4k; output_buffers 4 32k; postpone_output 1460; sendfile on; tcp_nopush on; keepalive_timeout 75 20; tcp_nodelay on; client_max_body_size 10m; client_body_buffer_size 256k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; client_body_temp_path /path/to/runfiles/client_body_temp; proxy_temp_path /path/to/runfiles/proxy_temp; fastcgi_temp_path /path/to/runfiles/fastcgi_temp; gzip on; gzip_min_length 1100; gzip_buffers 4 32k; gzip_types text/plain text/html application/x-javascript text/xml text/css; ignore_invalid_headers on; server { listen 80; server_name alpha2.sonyalabs.com; index index.html; root /path/to/django-root/static; # static resources location ~* ^/static/.*$ { root /path/to/django-root; expires 30d; break; } location / { # host and port to fastcgi server fastcgi_pass unix:/path/to/runfiles/django.sock; fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param QUERY_STRING $query_string; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_pass_header Authorization; fastcgi_intercept_errors off; } location /403.html { root /usr/local/nginx; access_log off; } location /401.html { root /usr/local/nginx; access_log off; } location /404.html { root /usr/local/nginx; access_log off; } location = /_.gif { empty_gif; access_log off; } access_log /path/to/runfiles/localhost.access_log main; error_log /path/to/runfiles/localhost.error_log; } } </code></pre>
10
2008-10-01T20:26:12Z
5,218,788
<p>I had the same exact problem running Nagios on nginx. I stumbled upon your question while googling for an answer, and reading "permission denied" related answers it struck me (and perhaps it will help you) : </p> <ul> <li><p>Nginx error.log was reporting :</p> <p>2011/03/07 11:36:02 [crit] 30977#0: *225952 open() "/var/lib/nginx/fastcgi/2/65/0000002652" failed (13: Permission denied)</p></li> <li><p>so I just ran # chown -R www-data:www-data /var/lib/nginx/fastcgi</p></li> <li><p>Fixed ! (and thank you for your indirect help)</p></li> </ul>
7
2011-03-07T10:54:59Z
[ "python", "django", "nginx", "fastcgi" ]
Nginx + fastcgi truncation problem
159,541
<p>I'm running a Django site using the fastcgi interface to nginx. However, some pages are being served truncated (i.e. the page source just stops, sometimes in the middle of a tag). How do I fix this (let me know what extra information is needed, and I'll post it)</p> <p>Details:</p> <p>I'm using flup, and spawning the fastcgi server with the following command:</p> <pre><code>python ./manage.py runfcgi umask=000 maxchildren=5 maxspare=1 minspare=0 method=prefork socket=/path/to/runfiles/django.sock pidfile=/path/to/runfiles/django.pid </code></pre> <p>The nginx config is as follows:</p> <pre><code># search and replace this: {project_location} pid /path/to/runfiles/nginx.pid; worker_processes 2; error_log /path/to/runfiles/error_log; events { worker_connections 1024; use epoll; } http { # default nginx location include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] ' '"$request" $status $bytes_sent ' '"$http_referer" "$http_user_agent" ' '"$gzip_ratio"'; client_header_timeout 3m; client_body_timeout 3m; send_timeout 3m; connection_pool_size 256; client_header_buffer_size 1k; large_client_header_buffers 4 2k; request_pool_size 4k; output_buffers 4 32k; postpone_output 1460; sendfile on; tcp_nopush on; keepalive_timeout 75 20; tcp_nodelay on; client_max_body_size 10m; client_body_buffer_size 256k; proxy_connect_timeout 90; proxy_send_timeout 90; proxy_read_timeout 90; client_body_temp_path /path/to/runfiles/client_body_temp; proxy_temp_path /path/to/runfiles/proxy_temp; fastcgi_temp_path /path/to/runfiles/fastcgi_temp; gzip on; gzip_min_length 1100; gzip_buffers 4 32k; gzip_types text/plain text/html application/x-javascript text/xml text/css; ignore_invalid_headers on; server { listen 80; server_name alpha2.sonyalabs.com; index index.html; root /path/to/django-root/static; # static resources location ~* ^/static/.*$ { root /path/to/django-root; expires 30d; break; } location / { # host and port to fastcgi server fastcgi_pass unix:/path/to/runfiles/django.sock; fastcgi_param PATH_INFO $fastcgi_script_name; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param QUERY_STRING $query_string; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_pass_header Authorization; fastcgi_intercept_errors off; } location /403.html { root /usr/local/nginx; access_log off; } location /401.html { root /usr/local/nginx; access_log off; } location /404.html { root /usr/local/nginx; access_log off; } location = /_.gif { empty_gif; access_log off; } access_log /path/to/runfiles/localhost.access_log main; error_log /path/to/runfiles/localhost.error_log; } } </code></pre>
10
2008-10-01T20:26:12Z
6,033,063
<p>FastCGI is not to blame for this. </p> <p>I ran into exactly the same issue using nginx/gunicorn. Reducing the response size to less than 32k (in the specific case using the <code>spaceless</code> tag in the template) solved it.</p> <p>As dwc says, it's probably a hard limit due to the way nginx uses address space.</p>
2
2011-05-17T15:17:05Z
[ "python", "django", "nginx", "fastcgi" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <pre><code># python example this_is_my_variable = 'a' def this_is_my_function(): </code></pre> <p>Is there a more preferable, definitive coding style for Python?</p>
326
2008-10-01T21:01:16Z
159,745
<p>See Python <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a>.</p> <blockquote> <p>Function names should be lowercase, with words separated by underscores as necessary to improve readability.</p> <p>mixedCase is allowed only in contexts where that's already the prevailing style</p> </blockquote> <p>Variables...</p> <blockquote> <p>Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.</p> </blockquote> <p>Personally, I deviate from this because I also prefer <code>mixedCase</code> over <code>lower_case</code> for my own projects.</p>
381
2008-10-01T21:05:24Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <pre><code># python example this_is_my_variable = 'a' def this_is_my_function(): </code></pre> <p>Is there a more preferable, definitive coding style for Python?</p>
326
2008-10-01T21:01:16Z
159,756
<p>The coding style is usually part of an organization's internal policy/convention standards, but I think in general, the all_lower_case_underscore_separator style (also called snake_case) is most common in python. </p>
0
2008-10-01T21:08:19Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <pre><code># python example this_is_my_variable = 'a' def this_is_my_function(): </code></pre> <p>Is there a more preferable, definitive coding style for Python?</p>
326
2008-10-01T21:01:16Z
159,778
<p>There is <a href="http://www.python.org/dev/peps/pep-0008/">PEP 8</a>, as other answers show, but PEP 8 is only the styleguide for the standard library, and it's only taken as gospel therein. One of the most frequent deviations of PEP 8 for other pieces of code is the variable naming, specifically for methods. There is no single predominate style, although considering the volume of code that uses mixedCase, if one were to make a strict census one would probably end up with a version of PEP 8 with mixedCase. There is little other deviation from PEP 8 that is quite as common.</p>
26
2008-10-01T21:12:41Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <pre><code># python example this_is_my_variable = 'a' def this_is_my_function(): </code></pre> <p>Is there a more preferable, definitive coding style for Python?</p>
326
2008-10-01T21:01:16Z
159,798
<p>Most python people prefer underscores, but even I am using python since more than 5 years right now, I still do not like them. They just look ugly to me, but maybe that's all the Java in my head. </p> <p>I simply like CamelCase better since it fits better with the way classes are named, It feels more logical to have <code>SomeClass.doSomething()</code> than <code>SomeClass.do_something()</code>. If you look around in the global module index in python, you will find both, which is due to the fact that it's a collection of libraries from various sources that grew overtime and not something that was developed by one company like Sun with strict coding rules. I would say the bottom line is: Use whatever you like better, it's just a question of personal taste.</p>
11
2008-10-01T21:16:21Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <pre><code># python example this_is_my_variable = 'a' def this_is_my_function(): </code></pre> <p>Is there a more preferable, definitive coding style for Python?</p>
326
2008-10-01T21:01:16Z
160,769
<p>Personally I try to use CamelCase for classes, mixedCase methods and functions. Variables are usually underscore separated (when I can remember). This way I can tell at a glance what exactly I'm calling, rather than everything looking the same.</p>
9
2008-10-02T03:24:30Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <pre><code># python example this_is_my_variable = 'a' def this_is_my_function(): </code></pre> <p>Is there a more preferable, definitive coding style for Python?</p>
326
2008-10-01T21:01:16Z
160,830
<p>David Goodger (in "Code Like a Pythonista" <a href="http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html">here</a>) describes the PEP 8 recommendations as follows:</p> <ul> <li><p><code>joined_lower</code> for functions, methods, attributes, variables</p></li> <li><p><code>joined_lower</code> or <code>ALL_CAPS</code> for constants</p></li> <li><p><code>StudlyCaps</code> for classes</p></li> <li><p><code>camelCase</code> only to conform to pre-existing conventions</p></li> </ul>
150
2008-10-02T03:53:12Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <pre><code># python example this_is_my_variable = 'a' def this_is_my_function(): </code></pre> <p>Is there a more preferable, definitive coding style for Python?</p>
326
2008-10-01T21:01:16Z
160,833
<p>Typically, one follow the conventions used in the language's standard library.</p>
2
2008-10-02T03:55:18Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <pre><code># python example this_is_my_variable = 'a' def this_is_my_function(): </code></pre> <p>Is there a more preferable, definitive coding style for Python?</p>
326
2008-10-01T21:01:16Z
264,226
<p>As mentioned, PEP 8 says to use <code>lower_case_with_underscores</code> for variables, methods and functions.</p> <p>I prefer using <code>lower_case_with_underscores</code> for variables and <code>mixedCase</code> for methods and functions makes the code more explicit and readable. Thus following the <a href="http://www.python.org/dev/peps/pep-0020/">Zen of Python's</a> "explicit is better than implicit" and "Readability counts"</p>
23
2008-11-05T02:51:29Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <pre><code># python example this_is_my_variable = 'a' def this_is_my_function(): </code></pre> <p>Is there a more preferable, definitive coding style for Python?</p>
326
2008-10-01T21:01:16Z
2,708,015
<p>As the <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">Style Guide for Python Code</a> admits,</p> <blockquote> <p>The naming conventions of Python's library are a bit of a mess, so we'll never get this completely consistent</p> </blockquote> <p>Note that this refers just to Python's <em>standard library</em>. If they can't get <em>that</em> consistent, then there hardly is much hope of having a generally-adhered-to convention for <em>all</em> Python code, is there?</p> <p>From that, and the discussion here, I would deduce that it's <strong>not</strong> a horrible sin if one keeps using e.g. Java's or C#'s (clear and well-established) naming conventions for variables and functions when crossing over to Python. Keeping in mind, of course, that it is best to abide with whatever the prevailing style for a codebase / project / team happens to be. As the Python Style Guide points out, <em>internal consistency</em> matters most.</p> <p><sup>Feel free to dismiss me as a heretic. :-) Like the OP, I'm not a "Pythonista", not yet anyway.</sup></p>
26
2010-04-25T11:23:57Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <pre><code># python example this_is_my_variable = 'a' def this_is_my_function(): </code></pre> <p>Is there a more preferable, definitive coding style for Python?</p>
326
2008-10-01T21:01:16Z
8,423,697
<p><a href="https://google.github.io/styleguide/pyguide.html">Google Python Style Guide</a> has the following convention:</p> <blockquote> <p>module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_CONSTANT_NAME, global_var_name, instance_var_name, function_parameter_name, local_var_name</p> </blockquote>
252
2011-12-07T22:44:24Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <pre><code># python example this_is_my_variable = 'a' def this_is_my_function(): </code></pre> <p>Is there a more preferable, definitive coding style for Python?</p>
326
2008-10-01T21:01:16Z
32,563,758
<p>I've varied the PEP system a little. </p> <pre><code>ThisIsAClass this_is_a_function </code></pre> <p>However, for variables I employ a system that goes a bit against Python's dynamic typing, but I find the improved readability at a glance so very useful, plus most variables don't ever change type in any case. I start each variable with a small letter denoting what it is, followed by StudlyCaps. An additional advantage is that variables and functions don't look the same. For example: </p> <pre><code>iIntegerVariable rRealNumber oObject fFile lList dDictionary sString xDynamicVariable aNumpyArray etc.. </code></pre>
0
2015-09-14T11:32:36Z
[ "python", "variables", "function", "naming-conventions" ]
What is the naming convention in Python for variable and function names?
159,720
<p>Coming from a C# background the naming convention for variables and method names are usually either CamelCase or Pascal Case:</p> <pre><code>// C# example string thisIsMyVariable = "a" public void ThisIsMyMethod() </code></pre> <p>In Python, I have seen the above but I have also seen underscores being used:</p> <pre><code># python example this_is_my_variable = 'a' def this_is_my_function(): </code></pre> <p>Is there a more preferable, definitive coding style for Python?</p>
326
2008-10-01T21:01:16Z
37,120,709
<p>There is a paper about this: <a href="http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf" rel="nofollow">http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf</a></p> <p>If you are lazy to read it it says that snake_case is more readable than camelCase. That's why modern languages use (or should use) snake wherever they can.</p>
1
2016-05-09T16:20:04Z
[ "python", "variables", "function", "naming-conventions" ]
Python Web Services
159,802
<p>Elementree has become the accepted standard for interacting with xml. What is the prevalent web service/SOAP library in use today?</p>
3
2008-10-01T21:18:26Z
159,809
<p>I'm not sure about an accepted standard, but I've found <a href="http://soapy.sourceforge.net/" rel="nofollow">SOAPpy</a> to be fairly straight-forward and useful library for handling SOAP-based web services.</p> <blockquote> <p>SOAPy is a SOAP/XML Schema Library for Python. Given either a WSDL or SDL document, SOAPy discovers the published API for a web service and exposes it to Python applications as transparently as possible.</p> </blockquote> <p>IBM provide a <a href="http://www.ibm.com/developerworks/library/ws-pyth5/" rel="nofollow">good walk-through and example</a> on their site for getting started with SOAPpy.</p> <p>SOAPpy's no longer under active development, but is instead being folded into Zolera SOAP Infrastructure (ZSI) at the <a href="http://pywebsvcs.sourceforge.net/" rel="nofollow">Python Web Services Project</a>. This project however has alos <a href="http://sourceforge.net/projects/pywebsvcs" rel="nofollow">not seen much activity</a> since November last year.</p>
1
2008-10-01T21:20:36Z
[ "python", "web-services" ]
Python Web Services
159,802
<p>Elementree has become the accepted standard for interacting with xml. What is the prevalent web service/SOAP library in use today?</p>
3
2008-10-01T21:18:26Z
160,059
<p>soaplib is very easy to use and seems to be active.</p> <p><a href="http://wiki.github.com/jkp/soaplib/" rel="nofollow">http://wiki.github.com/jkp/soaplib/</a></p>
0
2008-10-01T22:32:39Z
[ "python", "web-services" ]
Python Web Services
159,802
<p>Elementree has become the accepted standard for interacting with xml. What is the prevalent web service/SOAP library in use today?</p>
3
2008-10-01T21:18:26Z
7,720,351
<p>Old question, but for anyone else who is asking this question I've had good success with suds: <a href="https://fedorahosted.org/suds/" rel="nofollow">https://fedorahosted.org/suds/</a></p>
0
2011-10-11T00:58:26Z
[ "python", "web-services" ]
What is the difference between Ruby and Python versions of"self"?
159,990
<p>I've done some Python but have just now starting to use Ruby<br /> I could use a good explanation of the difference between "self" in these two languages. </p> <p><strong>Obvious on first glance:</strong><br /> Self is not a keyword in Python, but there is a "self-like" value no matter what you call it.<br /> Python methods receive self as an explicit argument, whereas Ruby does not.<br /> Ruby sometimes has methods explicitly defined as part of self using dot notation.</p> <p><strong>Initial Googling reveals</strong><br /> <a href="http://rubylearning.com/satishtalim/ruby_self.html">http://rubylearning.com/satishtalim/ruby_self.html</a><br /> <a href="http://www.ibiblio.org/g2swap/byteofpython/read/self.html">http://www.ibiblio.org/g2swap/byteofpython/read/self.html</a> </p>
6
2008-10-01T22:09:16Z
160,017
<p>Well, I don't know much about Ruby. But the obvious point about Python's "self" is that it's not a "keyword" ...it's just the name of an argument that's sent to your method.</p> <p>You can use any name you like for this argument. "Self" is just a convention.</p> <p>For example :</p> <pre><code>class X : def __init__(a,val) : a.x = val def p(b) : print b.x x = X(6) x.p() </code></pre> <p>Prints the number 6 on the terminal. In the constructor the self object is actually called a. But in the p() method, it's called b.</p> <p>Update : In October 2008, Guido pointed out that having an explicit self was also necessary to allow Python decorators to be general enough to work on pure functions, methods or classmethods : <a href="http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html" rel="nofollow">http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html</a></p>
5
2008-10-01T22:16:33Z
[ "python", "ruby", "language-features" ]
What is the difference between Ruby and Python versions of"self"?
159,990
<p>I've done some Python but have just now starting to use Ruby<br /> I could use a good explanation of the difference between "self" in these two languages. </p> <p><strong>Obvious on first glance:</strong><br /> Self is not a keyword in Python, but there is a "self-like" value no matter what you call it.<br /> Python methods receive self as an explicit argument, whereas Ruby does not.<br /> Ruby sometimes has methods explicitly defined as part of self using dot notation.</p> <p><strong>Initial Googling reveals</strong><br /> <a href="http://rubylearning.com/satishtalim/ruby_self.html">http://rubylearning.com/satishtalim/ruby_self.html</a><br /> <a href="http://www.ibiblio.org/g2swap/byteofpython/read/self.html">http://www.ibiblio.org/g2swap/byteofpython/read/self.html</a> </p>
6
2008-10-01T22:09:16Z
160,064
<p>self is used only as a convention, you can use spam, bacon or sausage instead of self and get the same result. It's just the first argument passed to bound methods. But stick to using self as it will confuse others and some editors.</p>
5
2008-10-01T22:34:42Z
[ "python", "ruby", "language-features" ]
What is the difference between Ruby and Python versions of"self"?
159,990
<p>I've done some Python but have just now starting to use Ruby<br /> I could use a good explanation of the difference between "self" in these two languages. </p> <p><strong>Obvious on first glance:</strong><br /> Self is not a keyword in Python, but there is a "self-like" value no matter what you call it.<br /> Python methods receive self as an explicit argument, whereas Ruby does not.<br /> Ruby sometimes has methods explicitly defined as part of self using dot notation.</p> <p><strong>Initial Googling reveals</strong><br /> <a href="http://rubylearning.com/satishtalim/ruby_self.html">http://rubylearning.com/satishtalim/ruby_self.html</a><br /> <a href="http://www.ibiblio.org/g2swap/byteofpython/read/self.html">http://www.ibiblio.org/g2swap/byteofpython/read/self.html</a> </p>
6
2008-10-01T22:09:16Z
160,227
<p>Python is designed to support more than just object-oriented programming. Preserving the same interface between methods and functions lets the two styles interoperate more cleanly.</p> <p>Ruby was built from the ground up to be object-oriented. Even the literals are objects (evaluate 1.class and you get Fixnum). The language was built such that self is a reserved keyword that returns the current instance wherever you are.</p> <p>If you're inside an instance method of one of your class, self is a reference to said instance. </p> <p>If you're in the definition of the class itself (not in a method), self is the class itself:</p> <pre><code>class C puts "I am a #{self}" def instance_method puts 'instance_method' end def self.class_method puts 'class_method' end end </code></pre> <p>At class definition time, 'I am a C' will be printed.</p> <p>The straight 'def' defines an instance method, whereas the 'def self.xxx' defines a class method.</p> <pre><code>c=C.new c.instance_method #=&gt; instance_method C.class_method #=&gt; class_method </code></pre>
7
2008-10-01T23:32:01Z
[ "python", "ruby", "language-features" ]
What is the difference between Ruby and Python versions of"self"?
159,990
<p>I've done some Python but have just now starting to use Ruby<br /> I could use a good explanation of the difference between "self" in these two languages. </p> <p><strong>Obvious on first glance:</strong><br /> Self is not a keyword in Python, but there is a "self-like" value no matter what you call it.<br /> Python methods receive self as an explicit argument, whereas Ruby does not.<br /> Ruby sometimes has methods explicitly defined as part of self using dot notation.</p> <p><strong>Initial Googling reveals</strong><br /> <a href="http://rubylearning.com/satishtalim/ruby_self.html">http://rubylearning.com/satishtalim/ruby_self.html</a><br /> <a href="http://www.ibiblio.org/g2swap/byteofpython/read/self.html">http://www.ibiblio.org/g2swap/byteofpython/read/self.html</a> </p>
6
2008-10-01T22:09:16Z
165,574
<p>Despite webmat's claim, Guido <a href="http://markmail.org/message/n6fs5pec5233mbfg">wrote</a> that explicit self is "not an implementation hack -- it is a semantic device".</p> <blockquote> <p>The reason for explicit self in method definition signatures is semantic consistency. If you write</p> <p>class C: def foo(self, x, y): ...</p> <p>This really <em>is</em> the same as writing</p> <p>class C: pass</p> <p>def foo(self, x, y): ... C.foo = foo</p> </blockquote> <p>This was an intentional design decision, not a result of introducing OO behaviour at a latter date.</p> <p>Everything in Python -is- an object, including literals.</p> <p>See also <a href="http://effbot.org/pyfaq/why-must-self-be-used-explicitly-in-method-definitions-and-calls.htm">Why must 'self' be used explicitly in method definitions and calls?</a></p>
5
2008-10-03T03:24:23Z
[ "python", "ruby", "language-features" ]
Model limit_choices_to={'user': user}
160,009
<p>I went to all the documentation, also I went to the IRC channel (BTW a great community) and they told me that is not possible to create a model and limit choices in a field where the 'current user' is in a ForeignKey. I will try to explain this with an example:</p> <pre><code>class Project(models.Model): name = models.CharField(max_length=100) employees = models.ManyToManyField(Profile, limit_choices_to={'active': '1'}) class TimeWorked(models.Model): project = models.ForeignKey(Project, limit_choices_to={'user': user}) hours = models.PositiveIntegerField() </code></pre> <p>Of course that code doesn't work because there is no 'user' object, but that was my idea and I was trying to send the object 'user' to the model to just limit the choices where the current user has projects, I don't want to see projects where I'm not in.</p> <p>Thank you very much if you can help me or give me any advice, I don't want to you write all the app, just a tip how to deal with that. I have 2 days with this in my head and I can't figure it out :(</p> <p><strong>UPDATE</strong>: The solution is here: <a href="http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/" rel="nofollow">http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/</a> sending <code>request.user</code> to a model.</p>
10
2008-10-01T22:14:36Z
160,035
<p>Hmmm, I don't fully understand your question. But if you can't do it when you declare the model maybe you can achieve the same thing with overriding methods of the class of objects where you "send" the user object, maybe start with the constructor.</p>
-1
2008-10-01T22:24:08Z
[ "python", "django", "model", "user" ]
Model limit_choices_to={'user': user}
160,009
<p>I went to all the documentation, also I went to the IRC channel (BTW a great community) and they told me that is not possible to create a model and limit choices in a field where the 'current user' is in a ForeignKey. I will try to explain this with an example:</p> <pre><code>class Project(models.Model): name = models.CharField(max_length=100) employees = models.ManyToManyField(Profile, limit_choices_to={'active': '1'}) class TimeWorked(models.Model): project = models.ForeignKey(Project, limit_choices_to={'user': user}) hours = models.PositiveIntegerField() </code></pre> <p>Of course that code doesn't work because there is no 'user' object, but that was my idea and I was trying to send the object 'user' to the model to just limit the choices where the current user has projects, I don't want to see projects where I'm not in.</p> <p>Thank you very much if you can help me or give me any advice, I don't want to you write all the app, just a tip how to deal with that. I have 2 days with this in my head and I can't figure it out :(</p> <p><strong>UPDATE</strong>: The solution is here: <a href="http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/" rel="nofollow">http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/</a> sending <code>request.user</code> to a model.</p>
10
2008-10-01T22:14:36Z
160,421
<p>Model itself doesn't know anything about current user but you can give this user in a view to the form which operates models objects (and in form reset <code>choices</code> for necessary field). </p> <p>If you need this on admin site - you can try <code>raw_id_admin</code> along with <code>django-granular-permissions</code> (<a href="http://code.google.com/p/django-granular-permissions/" rel="nofollow">http://code.google.com/p/django-granular-permissions/</a> but I couldn't rapidly get it working on my django but it seems to be fresh enough for 1.0 so...). </p> <p>At last, if you heavily need a selectbox in admin - then you'll need to hack <code>django.contrib.admin</code> itself.</p>
4
2008-10-02T00:47:35Z
[ "python", "django", "model", "user" ]
Model limit_choices_to={'user': user}
160,009
<p>I went to all the documentation, also I went to the IRC channel (BTW a great community) and they told me that is not possible to create a model and limit choices in a field where the 'current user' is in a ForeignKey. I will try to explain this with an example:</p> <pre><code>class Project(models.Model): name = models.CharField(max_length=100) employees = models.ManyToManyField(Profile, limit_choices_to={'active': '1'}) class TimeWorked(models.Model): project = models.ForeignKey(Project, limit_choices_to={'user': user}) hours = models.PositiveIntegerField() </code></pre> <p>Of course that code doesn't work because there is no 'user' object, but that was my idea and I was trying to send the object 'user' to the model to just limit the choices where the current user has projects, I don't want to see projects where I'm not in.</p> <p>Thank you very much if you can help me or give me any advice, I don't want to you write all the app, just a tip how to deal with that. I have 2 days with this in my head and I can't figure it out :(</p> <p><strong>UPDATE</strong>: The solution is here: <a href="http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/" rel="nofollow">http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/</a> sending <code>request.user</code> to a model.</p>
10
2008-10-01T22:14:36Z
160,435
<p>I'm not sure that I fully understand exactly what you want to do, but I think that there's a good chance that you'll get at least part the way there using a <a href="https://docs.djangoproject.com/en/dev/topics/db/managers/#custom-managers-and-model-inheritance" rel="nofollow">custom Manager</a>. In particular, don't try to define your models with restrictions to the current user, but create a manager that only returns objects that match the current user.</p>
0
2008-10-02T00:58:35Z
[ "python", "django", "model", "user" ]
Model limit_choices_to={'user': user}
160,009
<p>I went to all the documentation, also I went to the IRC channel (BTW a great community) and they told me that is not possible to create a model and limit choices in a field where the 'current user' is in a ForeignKey. I will try to explain this with an example:</p> <pre><code>class Project(models.Model): name = models.CharField(max_length=100) employees = models.ManyToManyField(Profile, limit_choices_to={'active': '1'}) class TimeWorked(models.Model): project = models.ForeignKey(Project, limit_choices_to={'user': user}) hours = models.PositiveIntegerField() </code></pre> <p>Of course that code doesn't work because there is no 'user' object, but that was my idea and I was trying to send the object 'user' to the model to just limit the choices where the current user has projects, I don't want to see projects where I'm not in.</p> <p>Thank you very much if you can help me or give me any advice, I don't want to you write all the app, just a tip how to deal with that. I have 2 days with this in my head and I can't figure it out :(</p> <p><strong>UPDATE</strong>: The solution is here: <a href="http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/" rel="nofollow">http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/</a> sending <code>request.user</code> to a model.</p>
10
2008-10-01T22:14:36Z
161,615
<p>Use threadlocals if you want to get <strong>current</strong> user that edits this model. Threadlocals middleware puts current user into process-wide variable. Take this middleware</p> <pre><code>from threading import local _thread_locals = local() def get_current_user(): return getattr(getattr(_thread_locals, 'user', None),'id',None) class ThreadLocals(object): """Middleware that gets various objects from the request object and saves them in thread local storage.""" def process_request(self, request): _thread_locals.user = getattr(request, 'user', None) </code></pre> <p>Check the documentation on how to use middleware classes. Then anywhere in code you can call</p> <pre><code>user = threadlocals.get_current_user </code></pre>
1
2008-10-02T10:09:01Z
[ "python", "django", "model", "user" ]
Model limit_choices_to={'user': user}
160,009
<p>I went to all the documentation, also I went to the IRC channel (BTW a great community) and they told me that is not possible to create a model and limit choices in a field where the 'current user' is in a ForeignKey. I will try to explain this with an example:</p> <pre><code>class Project(models.Model): name = models.CharField(max_length=100) employees = models.ManyToManyField(Profile, limit_choices_to={'active': '1'}) class TimeWorked(models.Model): project = models.ForeignKey(Project, limit_choices_to={'user': user}) hours = models.PositiveIntegerField() </code></pre> <p>Of course that code doesn't work because there is no 'user' object, but that was my idea and I was trying to send the object 'user' to the model to just limit the choices where the current user has projects, I don't want to see projects where I'm not in.</p> <p>Thank you very much if you can help me or give me any advice, I don't want to you write all the app, just a tip how to deal with that. I have 2 days with this in my head and I can't figure it out :(</p> <p><strong>UPDATE</strong>: The solution is here: <a href="http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/" rel="nofollow">http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/</a> sending <code>request.user</code> to a model.</p>
10
2008-10-01T22:14:36Z
163,536
<p>Here is the <a href="http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser" rel="nofollow">CookBook Threadlocals And User</a></p>
1
2008-10-02T17:24:22Z
[ "python", "django", "model", "user" ]
Model limit_choices_to={'user': user}
160,009
<p>I went to all the documentation, also I went to the IRC channel (BTW a great community) and they told me that is not possible to create a model and limit choices in a field where the 'current user' is in a ForeignKey. I will try to explain this with an example:</p> <pre><code>class Project(models.Model): name = models.CharField(max_length=100) employees = models.ManyToManyField(Profile, limit_choices_to={'active': '1'}) class TimeWorked(models.Model): project = models.ForeignKey(Project, limit_choices_to={'user': user}) hours = models.PositiveIntegerField() </code></pre> <p>Of course that code doesn't work because there is no 'user' object, but that was my idea and I was trying to send the object 'user' to the model to just limit the choices where the current user has projects, I don't want to see projects where I'm not in.</p> <p>Thank you very much if you can help me or give me any advice, I don't want to you write all the app, just a tip how to deal with that. I have 2 days with this in my head and I can't figure it out :(</p> <p><strong>UPDATE</strong>: The solution is here: <a href="http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/" rel="nofollow">http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/</a> sending <code>request.user</code> to a model.</p>
10
2008-10-01T22:14:36Z
4,656,296
<p>This limiting of choices to current user is a kind of validation that needs to happen dynamically in the request cycle, not in the static Model definition.</p> <p>In other words: at the point where you are creating an <em>instance</em> of this model you will be in a View and at that point you will have access to the current user and can limit the choices.</p> <p>Then you just need a custom ModelForm to pass in the request.user to, see the example here: <a href="http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/" rel="nofollow">http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/</a></p> <pre><code>from datetime import datetime, timedelta from django import forms from mysite.models import Project, TimeWorked class TimeWorkedForm(forms.ModelForm): def __init__(self, user, *args, **kwargs): super(ProjectForm, self).__init__(*args, **kwargs) self.fields['project'].queryset = Project.objects.filter(user=user) class Meta: model = TimeWorked </code></pre> <p>then in your view:</p> <pre><code>def time_worked(request): form = TimeWorkedForm(request.user, request.POST or None) if form.is_valid(): obj = form.save() # redirect somewhere return render_to_response('time_worked.html', {'form': form}) </code></pre>
0
2011-01-11T09:52:59Z
[ "python", "django", "model", "user" ]
Which is the best way to get a list of running processes in unix with python?
160,245
<p>I'm trying:</p> <pre><code>import commands print commands.getoutput("ps -u 0") </code></pre> <p>But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND</p> <p>nothing more</p>
2
2008-10-01T23:37:06Z
160,271
<p>It works if you use os instead of commands:</p> <pre><code>import os print os.system("ps -u 0") </code></pre>
0
2008-10-01T23:45:01Z
[ "python" ]
Which is the best way to get a list of running processes in unix with python?
160,245
<p>I'm trying:</p> <pre><code>import commands print commands.getoutput("ps -u 0") </code></pre> <p>But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND</p> <p>nothing more</p>
2
2008-10-01T23:37:06Z
160,284
<p>The cross-platform replacement for <code>commands</code> is <code>subprocess</code>. See the <a href="http://docs.python.org/lib/module-subprocess.html" rel="nofollow">subprocess module documentation</a>. The 'Replacing older modules' section includes <a href="http://docs.python.org/lib/node534.html" rel="nofollow">how to get output from a command</a>.</p> <p>Of course, you still have to pass the right arguments to 'ps' for the platform you're on. Python can't help you with that, and though I've seen occasional mention of third-party libraries that try to do this, they usually only work on a few systems (like strictly SysV style, strictly BSD style, or just systems with /proc.)</p>
3
2008-10-01T23:52:13Z
[ "python" ]
Which is the best way to get a list of running processes in unix with python?
160,245
<p>I'm trying:</p> <pre><code>import commands print commands.getoutput("ps -u 0") </code></pre> <p>But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND</p> <p>nothing more</p>
2
2008-10-01T23:37:06Z
160,316
<p>I've tried in on OS X (10.5.5) and seems to work just fine:</p> <pre><code>print commands.getoutput("ps -u 0") UID PID TTY TIME CMD 0 1 ?? 0:01.62 /sbin/launchd 0 10 ?? 0:00.57 /usr/libexec/kextd </code></pre> <p>etc.</p> <p>Python 2.5.1</p>
1
2008-10-02T00:06:46Z
[ "python" ]
Which is the best way to get a list of running processes in unix with python?
160,245
<p>I'm trying:</p> <pre><code>import commands print commands.getoutput("ps -u 0") </code></pre> <p>But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND</p> <p>nothing more</p>
2
2008-10-01T23:37:06Z
160,375
<p>This works on Mac OS X 10.5.5. Note the capital <strong>-U</strong> option. Perhaps that's been your problem.</p> <pre><code>import subprocess ps = subprocess.Popen("ps -U 0", shell=True, stdout=subprocess.PIPE) print ps.stdout.read() ps.stdout.close() ps.wait() </code></pre> <p>Here's the Python version</p> <pre><code>Python 2.5.2 (r252:60911, Feb 22 2008, 07:57:53) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin </code></pre>
8
2008-10-02T00:29:39Z
[ "python" ]
Which is the best way to get a list of running processes in unix with python?
160,245
<p>I'm trying:</p> <pre><code>import commands print commands.getoutput("ps -u 0") </code></pre> <p>But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND</p> <p>nothing more</p>
2
2008-10-01T23:37:06Z
3,710,903
<p>any of the above python calls - but try 'pgrep
0
2010-09-14T16:31:31Z
[ "python" ]
Which is the best way to get a list of running processes in unix with python?
160,245
<p>I'm trying:</p> <pre><code>import commands print commands.getoutput("ps -u 0") </code></pre> <p>But it doesn't work on os x. os instead of commands gives the same output: USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND</p> <p>nothing more</p>
2
2008-10-01T23:37:06Z
6,265,416
<p>If the OS support the /proc fs you can do:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; pids = [int(x) for x in os.listdir('/proc') if x.isdigit()] &gt;&gt;&gt; pids [1, 2, 3, 6, 7, 9, 11, 12, 13, 15, ... 9406, 9414, 9428, 9444] &gt;&gt;&gt; </code></pre> <p>A cross-platform solution (linux, freebsd, osx, windows) is by using <a href="http://code.google.com/p/psutil/">psutil</a>:</p> <pre><code>&gt;&gt;&gt; import psutil &gt;&gt;&gt; psutil.get_pid_list() [1, 2, 3, 6, 7, 9, 11, 12, 13, 15, ... 9406, 9414, 9428, 9444] &gt;&gt;&gt; </code></pre>
5
2011-06-07T12:51:23Z
[ "python" ]
Django/Python - Grouping objects by common set from a many-to-many relationships
160,298
<p>This is a part algorithm-logic question (how to do it), part implementation question (how to do it best!). I'm working with Django, so I thought I'd share with that.</p> <p>In Python, it's worth mentioning that the problem is somewhat related to <a href="http://stackoverflow.com/questions/773/how-do-i-use-pythons-itertoolsgroupby">how-do-i-use-pythons-itertoolsgroupby</a>.</p> <p>Suppose you're given two Django Model-derived classes:</p> <pre><code>from django.db import models class Car(models.Model): mods = models.ManyToManyField(Representative) </code></pre> <p>and</p> <pre><code>from django.db import models class Mods(models.Model): ... </code></pre> <p>How does one get a list of Cars, grouped by Cars with a common set of Mods?</p> <p>I.e. I want to get a class likeso:</p> <pre><code>Cars_by_common_mods = [ { mods: { 'a' }, cars: { 'W1', 'W2' } }, { mods: { 'a', 'b' }, cars: { 'X1', 'X2', 'X3' }, }, { mods: { 'b' }, cars: { 'Y1', 'Y2' } }, { mods: { 'a', 'b', 'c' }, cars: { 'Z1' } }, ] </code></pre> <p>I've been thinking of something like:</p> <pre><code>def cars_by_common_mods(): cars = Cars.objects.all() mod_list = [] for car in cars: mod_list.append( { 'car': car, 'mods': list(car.mods.all()) } ret = [] for key, mods_group in groupby(list(mods), lambda x: set(x.mods)): ret.append(mods_group) return ret </code></pre> <p>However, that doesn't work because (perhaps among other reasons) the groupby doesn't seem to group by the mods sets. I guess the mod_list has to be sorted to work with groupby. All to say, I'm confident there's something simple and elegant out there that will be both enlightening and illuminating.</p> <p><em>Cheers &amp; thanks!</em></p>
5
2008-10-01T23:59:52Z
160,552
<p>check <a href="http://docs.djangoproject.com/en/dev//ref/templates/builtins/#regroup" rel="nofollow">regroup</a>. it's only for templates, but i guess this kind of classification belongs to the presentation layer anyway.</p>
2
2008-10-02T01:58:49Z
[ "python", "django", "algorithm", "puzzle" ]
Django/Python - Grouping objects by common set from a many-to-many relationships
160,298
<p>This is a part algorithm-logic question (how to do it), part implementation question (how to do it best!). I'm working with Django, so I thought I'd share with that.</p> <p>In Python, it's worth mentioning that the problem is somewhat related to <a href="http://stackoverflow.com/questions/773/how-do-i-use-pythons-itertoolsgroupby">how-do-i-use-pythons-itertoolsgroupby</a>.</p> <p>Suppose you're given two Django Model-derived classes:</p> <pre><code>from django.db import models class Car(models.Model): mods = models.ManyToManyField(Representative) </code></pre> <p>and</p> <pre><code>from django.db import models class Mods(models.Model): ... </code></pre> <p>How does one get a list of Cars, grouped by Cars with a common set of Mods?</p> <p>I.e. I want to get a class likeso:</p> <pre><code>Cars_by_common_mods = [ { mods: { 'a' }, cars: { 'W1', 'W2' } }, { mods: { 'a', 'b' }, cars: { 'X1', 'X2', 'X3' }, }, { mods: { 'b' }, cars: { 'Y1', 'Y2' } }, { mods: { 'a', 'b', 'c' }, cars: { 'Z1' } }, ] </code></pre> <p>I've been thinking of something like:</p> <pre><code>def cars_by_common_mods(): cars = Cars.objects.all() mod_list = [] for car in cars: mod_list.append( { 'car': car, 'mods': list(car.mods.all()) } ret = [] for key, mods_group in groupby(list(mods), lambda x: set(x.mods)): ret.append(mods_group) return ret </code></pre> <p>However, that doesn't work because (perhaps among other reasons) the groupby doesn't seem to group by the mods sets. I guess the mod_list has to be sorted to work with groupby. All to say, I'm confident there's something simple and elegant out there that will be both enlightening and illuminating.</p> <p><em>Cheers &amp; thanks!</em></p>
5
2008-10-01T23:59:52Z
161,082
<p>Have you tried sorting the list first? The algorithm you proposed should work, albeit with lots of database hits.</p> <pre><code>import itertools cars = [ {'car': 'X2', 'mods': [1,2]}, {'car': 'Y2', 'mods': [2]}, {'car': 'W2', 'mods': [1]}, {'car': 'X1', 'mods': [1,2]}, {'car': 'W1', 'mods': [1]}, {'car': 'Y1', 'mods': [2]}, {'car': 'Z1', 'mods': [1,2,3]}, {'car': 'X3', 'mods': [1,2]}, ] cars.sort(key=lambda car: car['mods']) cars_by_common_mods = {} for k, g in itertools.groupby(cars, lambda car: car['mods']): cars_by_common_mods[frozenset(k)] = [car['car'] for car in g] print cars_by_common_mods </code></pre> <p>Now, about those queries:</p> <pre><code>import collections import itertools from operator import itemgetter from django.db import connection cursor = connection.cursor() cursor.execute('SELECT car_id, mod_id FROM someapp_car_mod ORDER BY 1, 2') cars = collections.defaultdict(list) for row in cursor.fetchall(): cars[row[0]].append(row[1]) # Here's one I prepared earlier, which emulates the sample data we've been working # with so far, but using the car id instead of the previous string. cars = { 1: [1,2], 2: [2], 3: [1], 4: [1,2], 5: [1], 6: [2], 7: [1,2,3], 8: [1,2], } sorted_cars = sorted(cars.iteritems(), key=itemgetter(1)) cars_by_common_mods = [] for k, g in itertools.groupby(sorted_cars, key=itemgetter(1)): cars_by_common_mods.append({'mods': k, 'cars': map(itemgetter(0), g)}) print cars_by_common_mods # Which, for the sample data gives me (reformatted by hand for clarity) [{'cars': [3, 5], 'mods': [1]}, {'cars': [1, 4, 8], 'mods': [1, 2]}, {'cars': [7], 'mods': [1, 2, 3]}, {'cars': [2, 6], 'mods': [2]}] </code></pre> <p>Now that you've got your lists of car ids and mod ids, if you need the complete objects to work with, you could do a single query for each to get a complete list for each model and create a lookup <code>dict</code> for those, keyed by their ids - then, I believe, Bob is your proverbial father's brother.</p>
4
2008-10-02T06:20:53Z
[ "python", "django", "algorithm", "puzzle" ]