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
listlengths
1
5
Loading and saving data from m2m relationships in Textarea widgets with ModelForm
1,257,062
<p>I have a Model that looks something like this:</p> <pre><code>class Business(models.Model): name = models.CharField('business name', max_length=100) # ... some other fields emails = models.ManyToManyField(Email, null=True) phone_numbers = models.ManyToManyField(PhoneNumber, null=True) urls = models.ManyToManyField(URL, null=True) </code></pre> <p>and a corresponding ModelForm:</p> <pre><code>class BusinessContactForm(forms.ModelForm): emails = forms.CharField(widget=forms.Textarea(attrs={'rows':4,'cols':32})) phone_numbers = forms.CharField(widget=forms.Textarea(attrs={'rows':4,'cols':32})) urls = forms.CharField(widget=forms.Textarea(attrs={'rows':4,'cols':32})) class Meta: model = Business fields = ['emails', 'phone_numbers', 'urls',] </code></pre> <p>My question: What is the best way to load the existing emails, phone_numbers, and urls into the Textarea widgets when presenting the form (one per line in their respective widgets)?</p> <p>Then, after the form has been modified and submitted, what is the best way to make sure to add any new emails, numbers, or urls (m2m relationships) and remove any that are no longer in the list (also making sure not to add duplicates)?</p>
0
2009-08-10T20:34:50Z
1,257,220
<p>This is not directly an answer to your question. It is more a suggestion to re-think your data model.</p> <p>It looks like your BusinessContactForm presents textarea widgets to insert multiple rows into the database. I would not use a Textarea widget for multiple items of more restricted type: I'd enter phone numbers with a phone number widget, URLs with a URL widget, and emails with an email widget.</p> <p>A business contact is really a person who works for a company and has an email address and phone number, correct? So why not model the business contact like that and have a foreign key to the business?</p> <p>That's more of the approach I would take.</p>
1
2009-08-10T21:07:41Z
[ "python", "django", "django-models", "django-forms" ]
Loading and saving data from m2m relationships in Textarea widgets with ModelForm
1,257,062
<p>I have a Model that looks something like this:</p> <pre><code>class Business(models.Model): name = models.CharField('business name', max_length=100) # ... some other fields emails = models.ManyToManyField(Email, null=True) phone_numbers = models.ManyToManyField(PhoneNumber, null=True) urls = models.ManyToManyField(URL, null=True) </code></pre> <p>and a corresponding ModelForm:</p> <pre><code>class BusinessContactForm(forms.ModelForm): emails = forms.CharField(widget=forms.Textarea(attrs={'rows':4,'cols':32})) phone_numbers = forms.CharField(widget=forms.Textarea(attrs={'rows':4,'cols':32})) urls = forms.CharField(widget=forms.Textarea(attrs={'rows':4,'cols':32})) class Meta: model = Business fields = ['emails', 'phone_numbers', 'urls',] </code></pre> <p>My question: What is the best way to load the existing emails, phone_numbers, and urls into the Textarea widgets when presenting the form (one per line in their respective widgets)?</p> <p>Then, after the form has been modified and submitted, what is the best way to make sure to add any new emails, numbers, or urls (m2m relationships) and remove any that are no longer in the list (also making sure not to add duplicates)?</p>
0
2009-08-10T20:34:50Z
1,257,249
<p>This really isn't a good way to do it. Dealing with related items on forms is what <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#id1" rel="nofollow">formsets</a> are for.</p> <p>Instead of defining the related fields as extra fields on the BusinessForm model, use a standard form for a contact, with email, phone and url. Then pass this into the modelformset_factory to create an inline formset for your BusinessContact form.</p>
1
2009-08-10T21:13:55Z
[ "python", "django", "django-models", "django-forms" ]
What's Python's equivalent to Java InputStream's available method?
1,257,264
<p>Java's InputStream provides a method named <code>available</code> which returns the number of bytes that can be read without blocking. </p> <p>How can I achieve this in Python?</p>
2
2009-08-10T21:16:47Z
1,257,332
<p>You've got to tell us what type of object you're working with. I'm assuming you're talking about a socket read. Either you read the socket with blocking or you read without blocking. You can measure how you have just read in a non-blocking read, if you are interested in that. However, it sounds like you are trying to bend python into a java.io style stream-buffer paradigm that it just doesn't support in detail.</p>
3
2009-08-10T21:31:21Z
[ "java", "python", "sockets" ]
What's Python's equivalent to Java InputStream's available method?
1,257,264
<p>Java's InputStream provides a method named <code>available</code> which returns the number of bytes that can be read without blocking. </p> <p>How can I achieve this in Python?</p>
2
2009-08-10T21:16:47Z
1,257,532
<p>Maybe the answers to <a href="http://stackoverflow.com/questions/375427">this question</a> will help.</p> <p>Or <a href="http://www.darkcoding.net/software/non-blocking-console-io-is-not-possible/" rel="nofollow">that link</a>.</p> <p>To summarize, you could use <a href="http://www.python.org/doc/2.5.2/lib/module-select.html" rel="nofollow">select</a>, which works for sockets in Windows and for sockets and other files (and pipes) in UNIX.</p>
1
2009-08-10T22:16:03Z
[ "java", "python", "sockets" ]
Iterate over pairs in a list (circular fashion) in Python
1,257,413
<p>The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).</p> <p>I've thought about two unpythonic ways of doing it:</p> <pre><code>def pairs(lst): n = len(lst) for i in range(n): yield lst[i],lst[(i+1)%n] </code></pre> <p>and:</p> <pre><code>def pairs(lst): return zip(lst,lst[1:]+[lst[0]]) </code></pre> <p>expected output:</p> <pre><code>&gt;&gt;&gt; for i in pairs(range(10)): print i (0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 7) (7, 8) (8, 9) (9, 0) &gt;&gt;&gt; </code></pre> <p>any suggestions about a more pythonic way of doing this? maybe there is a predefined function out there I haven't heard about?</p> <p>also a more general n-fold (with triplets, quartets, etc. instead of pairs) version could be interesting.</p>
31
2009-08-10T21:50:38Z
1,257,446
<pre><code>def pairs(lst): i = iter(lst) first = prev = item = i.next() for item in i: yield prev, item prev = item yield item, first </code></pre> <p>Works on any non-empty sequence, no indexing required.</p>
26
2009-08-10T21:57:01Z
[ "list", "iteration", "tuples", "python" ]
Iterate over pairs in a list (circular fashion) in Python
1,257,413
<p>The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).</p> <p>I've thought about two unpythonic ways of doing it:</p> <pre><code>def pairs(lst): n = len(lst) for i in range(n): yield lst[i],lst[(i+1)%n] </code></pre> <p>and:</p> <pre><code>def pairs(lst): return zip(lst,lst[1:]+[lst[0]]) </code></pre> <p>expected output:</p> <pre><code>&gt;&gt;&gt; for i in pairs(range(10)): print i (0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 7) (7, 8) (8, 9) (9, 0) &gt;&gt;&gt; </code></pre> <p>any suggestions about a more pythonic way of doing this? maybe there is a predefined function out there I haven't heard about?</p> <p>also a more general n-fold (with triplets, quartets, etc. instead of pairs) version could be interesting.</p>
31
2009-08-10T21:50:38Z
1,257,463
<p>This might be satisfactory:</p> <pre><code>def pairs(lst): for i in range(1, len(lst)): yield lst[i-1], lst[i] yield lst[-1], lst[0] &gt;&gt;&gt; a = list(range(5)) &gt;&gt;&gt; for a1, a2 in pairs(a): ... print a1, a2 ... 0 1 1 2 2 3 3 4 4 0 </code></pre> <p>If you like this kind of stuff, look at python articles on <a href="http://wordaligned.org/">wordaligned.org</a>. The author has a special love of generators in python.</p>
5
2009-08-10T22:00:18Z
[ "list", "iteration", "tuples", "python" ]
Iterate over pairs in a list (circular fashion) in Python
1,257,413
<p>The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).</p> <p>I've thought about two unpythonic ways of doing it:</p> <pre><code>def pairs(lst): n = len(lst) for i in range(n): yield lst[i],lst[(i+1)%n] </code></pre> <p>and:</p> <pre><code>def pairs(lst): return zip(lst,lst[1:]+[lst[0]]) </code></pre> <p>expected output:</p> <pre><code>&gt;&gt;&gt; for i in pairs(range(10)): print i (0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 7) (7, 8) (8, 9) (9, 0) &gt;&gt;&gt; </code></pre> <p>any suggestions about a more pythonic way of doing this? maybe there is a predefined function out there I haven't heard about?</p> <p>also a more general n-fold (with triplets, quartets, etc. instead of pairs) version could be interesting.</p>
31
2009-08-10T21:50:38Z
1,257,579
<p>To answer your question about solving for the general case:</p> <pre><code>import itertools def pair(series, n): s = list(itertools.tee(series, n)) try: [ s[i].next() for i in range(1, n) for j in range(i)] except StopIteration: pass while True: result = [] try: for j, ss in enumerate(s): result.append(ss.next()) except StopIteration: if j == 0: break else: s[j] = iter(series) for ss in s[j:]: result.append(ss.next()) yield result </code></pre> <p>The output is like this:</p> <pre><code>&gt;&gt;&gt; for a in pair(range(10), 2): ... print a ... [0, 1] [1, 2] [2, 3] [3, 4] [4, 5] [5, 6] [6, 7] [7, 8] [8, 9] [9, 0] &gt;&gt;&gt; for a in pair(range(10), 3): ... print a ... [0, 1, 2] [1, 2, 3] [2, 3, 4] [3, 4, 5] [4, 5, 6] [5, 6, 7] [6, 7, 8] [7, 8, 9] [8, 9, 0] [9, 0, 1] </code></pre>
0
2009-08-10T22:27:19Z
[ "list", "iteration", "tuples", "python" ]
Iterate over pairs in a list (circular fashion) in Python
1,257,413
<p>The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).</p> <p>I've thought about two unpythonic ways of doing it:</p> <pre><code>def pairs(lst): n = len(lst) for i in range(n): yield lst[i],lst[(i+1)%n] </code></pre> <p>and:</p> <pre><code>def pairs(lst): return zip(lst,lst[1:]+[lst[0]]) </code></pre> <p>expected output:</p> <pre><code>&gt;&gt;&gt; for i in pairs(range(10)): print i (0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 7) (7, 8) (8, 9) (9, 0) &gt;&gt;&gt; </code></pre> <p>any suggestions about a more pythonic way of doing this? maybe there is a predefined function out there I haven't heard about?</p> <p>also a more general n-fold (with triplets, quartets, etc. instead of pairs) version could be interesting.</p>
31
2009-08-10T21:50:38Z
1,257,624
<p>I've coded myself the tuple general versions, I like the first one for it's ellegant simplicity, the more I look at it, the more Pythonic it feels to me... after all, what is more Pythonic than a one liner with zip, asterisk argument expansion, list comprehensions, list slicing, list concatenation and "range"?</p> <pre><code>def ntuples(lst, n): return zip(*[lst[i:]+lst[:i] for i in range(n)]) </code></pre> <p>The itertools version should be efficient enough even for large lists...</p> <pre><code>from itertools import * def ntuples(lst, n): return izip(*[chain(islice(lst,i,None), islice(lst,None,i)) for i in range(n)]) </code></pre> <p>And a version for non-indexable sequences:</p> <pre><code>from itertools import * def ntuples(seq, n): iseq = iter(seq) curr = head = tuple(islice(iseq, n)) for x in chain(iseq, head): yield curr curr = curr[1:] + (x,) </code></pre> <p>Anyway, thanks everybody for your suggestions! :-)</p>
7
2009-08-10T22:37:22Z
[ "list", "iteration", "tuples", "python" ]
Iterate over pairs in a list (circular fashion) in Python
1,257,413
<p>The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).</p> <p>I've thought about two unpythonic ways of doing it:</p> <pre><code>def pairs(lst): n = len(lst) for i in range(n): yield lst[i],lst[(i+1)%n] </code></pre> <p>and:</p> <pre><code>def pairs(lst): return zip(lst,lst[1:]+[lst[0]]) </code></pre> <p>expected output:</p> <pre><code>&gt;&gt;&gt; for i in pairs(range(10)): print i (0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 7) (7, 8) (8, 9) (9, 0) &gt;&gt;&gt; </code></pre> <p>any suggestions about a more pythonic way of doing this? maybe there is a predefined function out there I haven't heard about?</p> <p>also a more general n-fold (with triplets, quartets, etc. instead of pairs) version could be interesting.</p>
31
2009-08-10T21:50:38Z
1,257,723
<p>I'd do it like this (mostly because I can read this):</p> <pre><code>class Pairs(object): def __init__(self, start): self.i = start def next(self): p, p1 = self.i, self.i + 1 self.i = p1 return p, p1 def __iter__(self): return self if __name__ == "__main__": x = Pairs(0) y = 1 while y &lt; 20: print x.next() y += 1 </code></pre> <p>gives:</p> <pre><code>(0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 7) (7, 8) (8, 9) </code></pre>
2
2009-08-10T23:08:30Z
[ "list", "iteration", "tuples", "python" ]
Iterate over pairs in a list (circular fashion) in Python
1,257,413
<p>The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).</p> <p>I've thought about two unpythonic ways of doing it:</p> <pre><code>def pairs(lst): n = len(lst) for i in range(n): yield lst[i],lst[(i+1)%n] </code></pre> <p>and:</p> <pre><code>def pairs(lst): return zip(lst,lst[1:]+[lst[0]]) </code></pre> <p>expected output:</p> <pre><code>&gt;&gt;&gt; for i in pairs(range(10)): print i (0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 7) (7, 8) (8, 9) (9, 0) &gt;&gt;&gt; </code></pre> <p>any suggestions about a more pythonic way of doing this? maybe there is a predefined function out there I haven't heard about?</p> <p>also a more general n-fold (with triplets, quartets, etc. instead of pairs) version could be interesting.</p>
31
2009-08-10T21:50:38Z
1,257,966
<p>This infinitely cycles, for good or ill, but is algorithmically very clear. </p> <pre><code>from itertools import tee, cycle def nextn(iterable,n=2): ''' generator that yields a tuple of the next n items in iterable. This generator cycles infinitely ''' cycled = cycle(iterable) gens = tee(cycled,n) # advance the iterators, this is O(n^2) for (ii,g) in zip(xrange(n),gens): for jj in xrange(ii): gens[ii].next() while True: yield tuple([x.next() for x in gens]) def test(): data = ((range(10),2), (range(5),3), (list("abcdef"),4),) for (iterable, n) in data: gen = nextn(iterable,n) for j in range(len(iterable)+n): print gen.next() test() </code></pre> <p>gives:</p> <pre><code>(0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 7) (7, 8) (8, 9) (9, 0) (0, 1) (1, 2) (0, 1, 2) (1, 2, 3) (2, 3, 4) (3, 4, 0) (4, 0, 1) (0, 1, 2) (1, 2, 3) (2, 3, 4) ('a', 'b', 'c', 'd') ('b', 'c', 'd', 'e') ('c', 'd', 'e', 'f') ('d', 'e', 'f', 'a') ('e', 'f', 'a', 'b') ('f', 'a', 'b', 'c') ('a', 'b', 'c', 'd') ('b', 'c', 'd', 'e') ('c', 'd', 'e', 'f') ('d', 'e', 'f', 'a') </code></pre>
0
2009-08-11T00:42:37Z
[ "list", "iteration", "tuples", "python" ]
Iterate over pairs in a list (circular fashion) in Python
1,257,413
<p>The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).</p> <p>I've thought about two unpythonic ways of doing it:</p> <pre><code>def pairs(lst): n = len(lst) for i in range(n): yield lst[i],lst[(i+1)%n] </code></pre> <p>and:</p> <pre><code>def pairs(lst): return zip(lst,lst[1:]+[lst[0]]) </code></pre> <p>expected output:</p> <pre><code>&gt;&gt;&gt; for i in pairs(range(10)): print i (0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 7) (7, 8) (8, 9) (9, 0) &gt;&gt;&gt; </code></pre> <p>any suggestions about a more pythonic way of doing this? maybe there is a predefined function out there I haven't heard about?</p> <p>also a more general n-fold (with triplets, quartets, etc. instead of pairs) version could be interesting.</p>
31
2009-08-10T21:50:38Z
2,231,702
<p>Even shorter version of Fortran's zip * range solution (with lambda this time;):</p> <pre><code>group = lambda t, n: zip(*[t[i::n] for i in range(n)]) group([1, 2, 3, 3], 2) </code></pre> <p>gives:</p> <pre><code>[(1, 2), (3, 4)] </code></pre>
0
2010-02-09T19:05:51Z
[ "list", "iteration", "tuples", "python" ]
Iterate over pairs in a list (circular fashion) in Python
1,257,413
<p>The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).</p> <p>I've thought about two unpythonic ways of doing it:</p> <pre><code>def pairs(lst): n = len(lst) for i in range(n): yield lst[i],lst[(i+1)%n] </code></pre> <p>and:</p> <pre><code>def pairs(lst): return zip(lst,lst[1:]+[lst[0]]) </code></pre> <p>expected output:</p> <pre><code>&gt;&gt;&gt; for i in pairs(range(10)): print i (0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 7) (7, 8) (8, 9) (9, 0) &gt;&gt;&gt; </code></pre> <p>any suggestions about a more pythonic way of doing this? maybe there is a predefined function out there I haven't heard about?</p> <p>also a more general n-fold (with triplets, quartets, etc. instead of pairs) version could be interesting.</p>
31
2009-08-10T21:50:38Z
4,590,062
<pre><code>i=(range(10)) for x in len(i): print i[:2] i=i[1:]+[i[1]] </code></pre> <p>more pythonic than this is impossible</p>
0
2011-01-04T01:59:53Z
[ "list", "iteration", "tuples", "python" ]
Iterate over pairs in a list (circular fashion) in Python
1,257,413
<p>The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).</p> <p>I've thought about two unpythonic ways of doing it:</p> <pre><code>def pairs(lst): n = len(lst) for i in range(n): yield lst[i],lst[(i+1)%n] </code></pre> <p>and:</p> <pre><code>def pairs(lst): return zip(lst,lst[1:]+[lst[0]]) </code></pre> <p>expected output:</p> <pre><code>&gt;&gt;&gt; for i in pairs(range(10)): print i (0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 7) (7, 8) (8, 9) (9, 0) &gt;&gt;&gt; </code></pre> <p>any suggestions about a more pythonic way of doing this? maybe there is a predefined function out there I haven't heard about?</p> <p>also a more general n-fold (with triplets, quartets, etc. instead of pairs) version could be interesting.</p>
31
2009-08-10T21:50:38Z
5,613,929
<p>Here's a version that supports an optional start index (for example to return (4, 0) as the first pair, use start = -1:</p> <pre><code>import itertools def iterrot(lst, start = 0): if start == 0: i = iter(lst) elif start &gt; 0: i1 = itertools.islice(lst, start, None) i2 = itertools.islice(lst, None, start) i = itertools.chain(i1, i2) else: # islice doesn't support negative slice indices so... lenl = len(lst) i1 = itertools.islice(lst, lenl + start, None) i2 = itertools.islice(lst, None, lenl + start) i = itertools.chain(i1, i2) return i def iterpairs(lst, start = 0): i = iterrot(lst, start) first = prev = i.next() for item in i: yield prev, item prev = item yield prev, first def itertrios(lst, start = 0): i = iterrot(lst, start) first = prevprev = i.next() second = prev = i.next() for item in i: yield prevprev, prev, item prevprev, prev = prev, item yield prevprev, prev, first yield prev, first, second </code></pre>
0
2011-04-10T18:44:48Z
[ "list", "iteration", "tuples", "python" ]
Iterate over pairs in a list (circular fashion) in Python
1,257,413
<p>The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).</p> <p>I've thought about two unpythonic ways of doing it:</p> <pre><code>def pairs(lst): n = len(lst) for i in range(n): yield lst[i],lst[(i+1)%n] </code></pre> <p>and:</p> <pre><code>def pairs(lst): return zip(lst,lst[1:]+[lst[0]]) </code></pre> <p>expected output:</p> <pre><code>&gt;&gt;&gt; for i in pairs(range(10)): print i (0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 7) (7, 8) (8, 9) (9, 0) &gt;&gt;&gt; </code></pre> <p>any suggestions about a more pythonic way of doing this? maybe there is a predefined function out there I haven't heard about?</p> <p>also a more general n-fold (with triplets, quartets, etc. instead of pairs) version could be interesting.</p>
31
2009-08-10T21:50:38Z
6,242,225
<pre><code>[(i,(i+1)%len(range(10))) for i in range(10)] </code></pre> <p>replace range(10) with the list you want.</p> <p>In general "circular indexing" is quite easy in python; just use: </p> <pre><code>a[i%len(a)] </code></pre>
1
2011-06-05T10:05:32Z
[ "list", "iteration", "tuples", "python" ]
Iterate over pairs in a list (circular fashion) in Python
1,257,413
<p>The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).</p> <p>I've thought about two unpythonic ways of doing it:</p> <pre><code>def pairs(lst): n = len(lst) for i in range(n): yield lst[i],lst[(i+1)%n] </code></pre> <p>and:</p> <pre><code>def pairs(lst): return zip(lst,lst[1:]+[lst[0]]) </code></pre> <p>expected output:</p> <pre><code>&gt;&gt;&gt; for i in pairs(range(10)): print i (0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 7) (7, 8) (8, 9) (9, 0) &gt;&gt;&gt; </code></pre> <p>any suggestions about a more pythonic way of doing this? maybe there is a predefined function out there I haven't heard about?</p> <p>also a more general n-fold (with triplets, quartets, etc. instead of pairs) version could be interesting.</p>
31
2009-08-10T21:50:38Z
9,885,130
<p>I, as always, like tee:</p> <pre><code>from itertools import tee, izip, chain def pairs(iterable): a, b = tee(iterable) return izip(a, chain(b, [next(b)])) </code></pre>
6
2012-03-27T07:32:21Z
[ "list", "iteration", "tuples", "python" ]
Iterate over pairs in a list (circular fashion) in Python
1,257,413
<p>The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).</p> <p>I've thought about two unpythonic ways of doing it:</p> <pre><code>def pairs(lst): n = len(lst) for i in range(n): yield lst[i],lst[(i+1)%n] </code></pre> <p>and:</p> <pre><code>def pairs(lst): return zip(lst,lst[1:]+[lst[0]]) </code></pre> <p>expected output:</p> <pre><code>&gt;&gt;&gt; for i in pairs(range(10)): print i (0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 7) (7, 8) (8, 9) (9, 0) &gt;&gt;&gt; </code></pre> <p>any suggestions about a more pythonic way of doing this? maybe there is a predefined function out there I haven't heard about?</p> <p>also a more general n-fold (with triplets, quartets, etc. instead of pairs) version could be interesting.</p>
31
2009-08-10T21:50:38Z
16,567,465
<pre><code>def pairs(ex_list): for i, v in enumerate(ex_list): if i &lt; len(list) - 1: print v, ex_list[i+1] else: print v, ex_list[0] </code></pre> <p>Enumerate returns a tuple with the index number and the value. I print the value and the following element of the list <code>ex_list[i+1]</code>. The if <code>i &lt; len(list) - 1</code> means if v is <strong>not</strong> the last member of the list. If it is: print v and the first element of the list <code>print v, ex_list[0]</code>.</p> <h2>Edit:</h2> <p>You can make it return a list. Just append the printed tuples to a list and return it.</p> <pre><code>def pairs(ex_list): result = [] for i, v in enumerate(ex_list): if i &lt; len(list) - 1: result.append((v, ex_list[i+1])) else: result.append((v, ex_list[0])) return result </code></pre>
0
2013-05-15T14:13:47Z
[ "list", "iteration", "tuples", "python" ]
Iterate over pairs in a list (circular fashion) in Python
1,257,413
<p>The problem is easy, I want to iterate over each element of the list and the next one in pairs (wrapping the last one with the first).</p> <p>I've thought about two unpythonic ways of doing it:</p> <pre><code>def pairs(lst): n = len(lst) for i in range(n): yield lst[i],lst[(i+1)%n] </code></pre> <p>and:</p> <pre><code>def pairs(lst): return zip(lst,lst[1:]+[lst[0]]) </code></pre> <p>expected output:</p> <pre><code>&gt;&gt;&gt; for i in pairs(range(10)): print i (0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 7) (7, 8) (8, 9) (9, 0) &gt;&gt;&gt; </code></pre> <p>any suggestions about a more pythonic way of doing this? maybe there is a predefined function out there I haven't heard about?</p> <p>also a more general n-fold (with triplets, quartets, etc. instead of pairs) version could be interesting.</p>
31
2009-08-10T21:50:38Z
23,176,598
<p>Of course, you can always use a <strong>deque</strong>:</p> <pre><code>from collections import deque from itertools import * def pairs(lst, n=2): itlst = iter(lst) start = list(islice(itlst, 0, n-1)) deq = deque(start, n) for elt in chain(itlst, start): deq.append(elt) yield list(deq) </code></pre>
0
2014-04-19T23:07:20Z
[ "list", "iteration", "tuples", "python" ]
python: slow timeit() function
1,257,727
<p>When I run the code below outside of timeit(), it appears to complete instantaneously. However when I run it within the timeit() function, it takes much longer. Why?</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; t = timeit.Timer("3**4**5") &gt;&gt;&gt; t.timeit() 16.55522028637718 </code></pre> <p>Using: Python 3.1 (x86) - AMD Athlon 64 X2 - WinXP (32 bit)</p>
12
2009-08-10T23:09:51Z
1,257,737
<p>The <code>timeit()</code> function runs the code many times (default one million) and takes an average of the timings.</p> <p>To run the code only once, do this:</p> <pre><code>t.timeit(1) </code></pre> <p>but that will give you skewed results - it repeats for good reason.</p> <p>To get the per-loop time having let it repeat, divide the result by the number of loops. Use a smaller value for the number of repeats if one million is too many:</p> <pre><code>count = 1000 print t.timeit(count) / count </code></pre>
23
2009-08-10T23:12:42Z
[ "python", "timer", "timeit" ]
python: slow timeit() function
1,257,727
<p>When I run the code below outside of timeit(), it appears to complete instantaneously. However when I run it within the timeit() function, it takes much longer. Why?</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; t = timeit.Timer("3**4**5") &gt;&gt;&gt; t.timeit() 16.55522028637718 </code></pre> <p>Using: Python 3.1 (x86) - AMD Athlon 64 X2 - WinXP (32 bit)</p>
12
2009-08-10T23:09:51Z
1,257,739
<p>Because timeit defaults to running it one million times. The point is to do micro-benchmarks, and the only way to get accurate timings of short events is to repeat them many times.</p>
5
2009-08-10T23:13:25Z
[ "python", "timer", "timeit" ]
python: slow timeit() function
1,257,727
<p>When I run the code below outside of timeit(), it appears to complete instantaneously. However when I run it within the timeit() function, it takes much longer. Why?</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; t = timeit.Timer("3**4**5") &gt;&gt;&gt; t.timeit() 16.55522028637718 </code></pre> <p>Using: Python 3.1 (x86) - AMD Athlon 64 X2 - WinXP (32 bit)</p>
12
2009-08-10T23:09:51Z
1,257,751
<p>According to the <a href="http://docs.python.org/library/timeit.html" rel="nofollow">docs</a>, Timer.timeit() runs your code one million times by default. Use the "number" parameter to change this default:</p> <pre><code>t.timeit(number=100) </code></pre> <p>for example.</p>
2
2009-08-10T23:18:12Z
[ "python", "timer", "timeit" ]
python: slow timeit() function
1,257,727
<p>When I run the code below outside of timeit(), it appears to complete instantaneously. However when I run it within the timeit() function, it takes much longer. Why?</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; t = timeit.Timer("3**4**5") &gt;&gt;&gt; t.timeit() 16.55522028637718 </code></pre> <p>Using: Python 3.1 (x86) - AMD Athlon 64 X2 - WinXP (32 bit)</p>
12
2009-08-10T23:09:51Z
1,257,754
<p><a href="http://docs.python.org/library/timeit.html#timeit.Timer.timeit" rel="nofollow">Timeit</a> runs for one million loops by default.</p> <p>You also may have order of operations issues: <code>(3**4)**5 != 3**4**5</code>.</p>
2
2009-08-10T23:18:49Z
[ "python", "timer", "timeit" ]
python: slow timeit() function
1,257,727
<p>When I run the code below outside of timeit(), it appears to complete instantaneously. However when I run it within the timeit() function, it takes much longer. Why?</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; t = timeit.Timer("3**4**5") &gt;&gt;&gt; t.timeit() 16.55522028637718 </code></pre> <p>Using: Python 3.1 (x86) - AMD Athlon 64 X2 - WinXP (32 bit)</p>
12
2009-08-10T23:09:51Z
1,257,784
<pre><code>&gt;&gt;&gt; 3**4**5 37339184874102004353295975418486658822540977678373400775063693172207904061726525 12299936889388039772204687650654314751581087270545921608585813513369828091873141 91748594262580938807019951956404285571818041046681288797402925517668012340617298 39657473161915238672304623512593489605859058828465479354050593620237654780744273 05821445270589887562514528177934133521419207446230275187291854328623757370639854 85319476416926263819972887006907013899256524297198527698749274196276811060702333 710356481L </code></pre> <p>whereas:</p> <pre><code>&gt;&gt;&gt; (3**4)**5 3486784401L </code></pre>
0
2009-08-10T23:25:46Z
[ "python", "timer", "timeit" ]
How do I get omnicompletion for Python external libraries?
1,257,742
<p>I've setup my gVim to have omnicompletion, but only for the standard library atm.. How do I include other libraries (Django, Pygame, etc...)?</p> <p>Thanks!</p>
5
2009-08-10T23:13:54Z
1,257,793
<p>Here's a <a href="http://blog.fluther.com/blog/2008/10/17/django-vim/" rel="nofollow">tutorial on using omnicomplete with Django</a>.</p>
1
2009-08-10T23:28:07Z
[ "python", "vim" ]
python/genshi newline to html <p> paragraphs
1,257,746
<p>I'm trying to output the content of a comment with genshi, but I can't figure out how to transform the newlines into HTML paragraphs.</p> <p>Here's a test case of what it should look like:</p> <p>input: <code>'foo\n\n\n\n\nbar\nbaz'</code></p> <p>output: <code>&lt;p&gt;foo&lt;/p&gt;&lt;p&gt;bar&lt;/p&gt;&lt;p&gt;baz&lt;/p&gt;</code></p> <p>I've looked everywhere for this function. I couldn't find it in genshi or in python's std lib. I'm using TG 1.0.</p>
3
2009-08-10T23:16:36Z
1,257,780
<p>There may be a built-in function in Genshi, but if not, this will do it for you:</p> <pre><code>output = ''.join([("&lt;p&gt;%s&lt;/p&gt;" % l) for l in input.split('\n')]) </code></pre>
2
2009-08-10T23:24:38Z
[ "python", "turbogears", "genshi" ]
python/genshi newline to html <p> paragraphs
1,257,746
<p>I'm trying to output the content of a comment with genshi, but I can't figure out how to transform the newlines into HTML paragraphs.</p> <p>Here's a test case of what it should look like:</p> <p>input: <code>'foo\n\n\n\n\nbar\nbaz'</code></p> <p>output: <code>&lt;p&gt;foo&lt;/p&gt;&lt;p&gt;bar&lt;/p&gt;&lt;p&gt;baz&lt;/p&gt;</code></p> <p>I've looked everywhere for this function. I couldn't find it in genshi or in python's std lib. I'm using TG 1.0.</p>
3
2009-08-10T23:16:36Z
1,258,080
<pre><code>def tohtml(manylinesstr): return ''.join("&lt;p&gt;%s&lt;/p&gt;" % line for line in manylinesstr.splitlines() if line) </code></pre> <p>So for example,</p> <pre><code>print repr(tohtml('foo\n\n\n\n\nbar\nbaz')) </code></pre> <p>emits:</p> <pre><code>'&lt;p&gt;foo&lt;/p&gt;&lt;p&gt;bar&lt;/p&gt;&lt;p&gt;baz&lt;/p&gt;' </code></pre> <p>as required.</p>
3
2009-08-11T01:35:32Z
[ "python", "turbogears", "genshi" ]
python/genshi newline to html <p> paragraphs
1,257,746
<p>I'm trying to output the content of a comment with genshi, but I can't figure out how to transform the newlines into HTML paragraphs.</p> <p>Here's a test case of what it should look like:</p> <p>input: <code>'foo\n\n\n\n\nbar\nbaz'</code></p> <p>output: <code>&lt;p&gt;foo&lt;/p&gt;&lt;p&gt;bar&lt;/p&gt;&lt;p&gt;baz&lt;/p&gt;</code></p> <p>I've looked everywhere for this function. I couldn't find it in genshi or in python's std lib. I'm using TG 1.0.</p>
3
2009-08-10T23:16:36Z
1,387,182
<p>I know you said TG1 my solution is TG2 but can be backported or simply depend on webhelpers but IMO all other implementations are flawed. </p> <p>Take a look at the <a href="http://bitbucket.org/bbangert/webhelpers/src/tip/webhelpers/html/converters.py" rel="nofollow">converters module</a> both nl2br and format_paragraphs.</p>
1
2009-09-07T01:03:11Z
[ "python", "turbogears", "genshi" ]
Problem reading an Integer in java that was written using python’s struct.pack method
1,257,856
<p>First I write the integer using python:<br /> <code>out.write( struct.pack("&gt;i", int(i)) );</code></p> <p>I then read the integer using <code>DataInputStream.readInt()</code> in Java.<br /> I works but when it tries to read the number 10, and probably some other numbers too, it starts to read garbage.<br /> Reading the numbers:<br /> <code>0, 4, 5, 0, 5, 13, 10, 1, 5, 6</code><br /> Java reads:<br /> <code>0, 4, 5, 0, 5, 13, 167772160, 16777216, 83886080</code> </p> <p>What am I doing wrong?</p>
0
2009-08-10T23:57:19Z
1,257,870
<p>Psychic debugging: You're writing the output in text mode on Windows using code like this:</p> <pre><code>f = open("output.dat", "w") f.write(my_data) </code></pre> <p>and that's making your 13 (which is a newline) become carriage return / newline (10, 13).</p> <p>You need to write your output in binary mode:</p> <pre><code>f = open("output.dat", "wb") f.write(my_data) </code></pre>
7
2009-08-11T00:02:48Z
[ "java", "python" ]
Starting semantic image recognition
1,257,933
<p>How to recognize (in)appropriate images?</p> <p>To facilitate, enable and easify photo and image moderation and administration targeting gae, I try get started with basic python image recognition ie basic semantic information what the image looks like to hold back doubtful material until human can judge it, and to approve the most that are good. A test batch > 10 000 images had one or just a very few so avoiding false positives naturally is good. I found the following links to follow and thank you all in advance for all advice, suggestions and recommendations. Very basically moderation will display a number of images and just a button "ok" or viceversa default "ok" and a button "Disapprove" depending on default decision (default probably publish everything and ad hoc (human) disapproval if some unsuitable since the absolute major part > 99 % material is suitably good) <a href="http://www.scipy.org/PyLab" rel="nofollow">link text</a></p> <p><a href="http://gamera.informatik.hsnr.de/" rel="nofollow">link text</a></p>
1
2009-08-11T00:27:02Z
1,258,035
<p>In python you could always:</p> <pre><code>import supreme_court </code></pre> <p>Because when it comes to pornography, they know it when they see it.</p> <p>Mediocre jokes aside, I would develop a bunch of fuzzy image recognizers that match <em>easy</em> things (like how much of the image is made up of a skin color tone?). You could probably come up with a good amount of suspicious variables at this point - this is the hard(ish) part. Then use Classification and Regression Trees to implement the actual decision engine. Train it with your training sample, then do cross-sample validation to get a sense of the false positives/negatives. </p>
2
2009-08-11T01:17:12Z
[ "python", "image", "computer-vision", "pattern-recognition", "image-recognition" ]
Starting semantic image recognition
1,257,933
<p>How to recognize (in)appropriate images?</p> <p>To facilitate, enable and easify photo and image moderation and administration targeting gae, I try get started with basic python image recognition ie basic semantic information what the image looks like to hold back doubtful material until human can judge it, and to approve the most that are good. A test batch > 10 000 images had one or just a very few so avoiding false positives naturally is good. I found the following links to follow and thank you all in advance for all advice, suggestions and recommendations. Very basically moderation will display a number of images and just a button "ok" or viceversa default "ok" and a button "Disapprove" depending on default decision (default probably publish everything and ad hoc (human) disapproval if some unsuitable since the absolute major part > 99 % material is suitably good) <a href="http://www.scipy.org/PyLab" rel="nofollow">link text</a></p> <p><a href="http://gamera.informatik.hsnr.de/" rel="nofollow">link text</a></p>
1
2009-08-11T00:27:02Z
1,258,045
<p>I believe you will want to start here</p> <p><a href="http://en.wikipedia.org/wiki/Feature_detection_%28computer_vision%29" rel="nofollow">http://en.wikipedia.org/wiki/Feature_detection_%28computer_vision%29</a></p> <p>and then brush up on your statistical theory, reading any papers on the topic.</p>
2
2009-08-11T01:21:35Z
[ "python", "image", "computer-vision", "pattern-recognition", "image-recognition" ]
Generic view 'archive_year' produces blank page
1,257,943
<p>I am using Django's generic views to create a blog site. The templates I created, <code>entry_archive_day</code>, <code>entry_archive_month</code>, <code>entry_archive</code>, and <code>entry_detail</code> all work perfectly. </p> <p>But <strong><code>entry_archive_year</code></strong> does not. Instead, it is simply a valid page with no content (not a 404 or other error. It looks like it sees no objects in <code>**object_list**</code>.</p> <p>I know that <code>archive</code> uses a <code>latest</code> list instead of <code>object_list</code>, but that's not the case with <code>archive_year</code>, correct?</p> <p>Thanks!</p>
3
2009-08-11T00:30:42Z
1,257,956
<p><strong>To solve your problem:</strong></p> <p>If you set <code>make_object_list=True</code> when calling <code>archive_year</code>, then the list of objects for that year will be available as <code>object_list</code>.</p> <p>As a quick example, if your url pattern looks like</p> <pre><code>url(r'^(?P&lt;year&gt;\d{4})/$', 'archive_year', info_dict, name="entry_archive_year") </code></pre> <p>where <code>info_dict</code> is a dictionary containing the <code>queryset</code> and <code>date_field</code>, change it to</p> <pre><code>url(r'^(?P&lt;year&gt;\d{4}/$', 'archive_year', dict(info_dict,make_object_list=True), name="entry_archive_year") </code></pre> <p><strong>Explanation:</strong></p> <p>The generic view <code>archive_year</code> has an optional argument <code>make_object_list</code>. By default, it is set to false, and <code>object_list</code> is passed to the template as an empty list.</p> <blockquote> <p><code>make_object_list</code>: A boolean specifying whether to retrieve the full list of objects for this year and pass those to the template. If <code>True</code>, this list of objects will be made available to the template as <code>object_list</code>. (The name <code>object_list</code> may be different; see the docs for <code>object_list</code> in the "Template context" section below.) By default, this is <code>False</code>.</p> </blockquote> <p>A reason for this is that you might not always want to display the entire object list in the <code>entry_archive_year</code> view. You may have hundreds of blog posts for that year, too many to display on one page.</p> <p>Instead, <code>archive_year</code> adds <code>date_list</code> to the template context. This allows you to create links to the monthly archive pages of that year, for the months which have entries.</p> <blockquote> <p><code>date_list</code>: A list of <code>datetime.date</code> objects representing all months that have objects available in the given year, according to queryset, in ascending order.</p> </blockquote> <p>There's more info in the <a href="https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-date-based-archive-year" rel="nofollow">Django docs</a>.</p> <p><strong>As requested in the comment below, an example of how to use <code>date_list</code>:</strong></p> <p>To use <code>date_list</code>, your <code>entry_archive_year</code> template would contain something like this:</p> <pre><code>&lt;ul&gt; {% for month in date_list %} &lt;li&gt;&lt;a href="/blog/{{month|date:"Y"}}/{{month|date:"b"}}&gt; {{month|date:"F"}}&lt;/a&gt;&lt;/li&gt; {% endfor %} &lt;/ul&gt; </code></pre> <p>Note that I've hardcoded the url - in practice it would be better to use the <a href="https://docs.djangoproject.com/en/1.4/ref/templates/builtins/#url" rel="nofollow">url template tag</a>. For an example of <code>date_list</code> being used in the wild, look at the <a href="http://www.djangoproject.com/weblog/2009/" rel="nofollow">Django Weblog 2009 Archive</a>.</p>
5
2009-08-11T00:39:13Z
[ "python", "django", "view", "generics" ]
python datetime strptime wildcard
1,258,199
<p>I want to parse dates like these into a datetime object:</p> <ul> <li>December 12th, 2008 </li> <li>January 1st, 2009</li> </ul> <p>The following will work for the first date:</p> <pre><code>datetime.strptime("December 12th, 2008", "%B %dth, %Y") </code></pre> <p>but will fail for the second because of the suffix to the day number ('st'). So, is there an undocumented wildcard character in strptime? Or a better approach altogether?</p>
13
2009-08-11T02:23:47Z
1,258,247
<p>Try using the dateutil.parser module.</p> <pre><code>import dateutil.parser date1 = dateutil.parser.parse("December 12th, 2008") date2 = dateutil.parser.parse("January 1st, 2009") </code></pre> <p>Additional documentation can be found here: <a href="http://labix.org/python-dateutil">http://labix.org/python-dateutil</a></p>
18
2009-08-11T02:41:28Z
[ "python", "datetime", "parsing", "strptime" ]
python datetime strptime wildcard
1,258,199
<p>I want to parse dates like these into a datetime object:</p> <ul> <li>December 12th, 2008 </li> <li>January 1st, 2009</li> </ul> <p>The following will work for the first date:</p> <pre><code>datetime.strptime("December 12th, 2008", "%B %dth, %Y") </code></pre> <p>but will fail for the second because of the suffix to the day number ('st'). So, is there an undocumented wildcard character in strptime? Or a better approach altogether?</p>
13
2009-08-11T02:23:47Z
1,258,248
<p>strptime is tricky because it relies on the underlying C library for its implementation, so some details differ between platforms. There doesn't seem to be a way to match the characters you need to. But you could clean the data first:</p> <pre><code># Remove ordinal suffixes from numbers. date_in = re.sub(r"(st|nd|rd|th),", ",", date_in) # Parse the pure date. date = datetime.strptime(date_in, "%B %d, %Y") </code></pre>
7
2009-08-11T02:42:09Z
[ "python", "datetime", "parsing", "strptime" ]
python datetime strptime wildcard
1,258,199
<p>I want to parse dates like these into a datetime object:</p> <ul> <li>December 12th, 2008 </li> <li>January 1st, 2009</li> </ul> <p>The following will work for the first date:</p> <pre><code>datetime.strptime("December 12th, 2008", "%B %dth, %Y") </code></pre> <p>but will fail for the second because of the suffix to the day number ('st'). So, is there an undocumented wildcard character in strptime? Or a better approach altogether?</p>
13
2009-08-11T02:23:47Z
1,258,249
<p>You need Gustavo Niemeyer's <a href="http://labix.org/python-dateutil">python_dateutil</a> -- once it's installed,</p> <pre><code>&gt;&gt;&gt; from dateutil import parser &gt;&gt;&gt; parser.parse('December 12th, 2008') datetime.datetime(2008, 12, 12, 0, 0) &gt;&gt;&gt; parser.parse('January 1st, 2009') datetime.datetime(2009, 1, 1, 0, 0) &gt;&gt;&gt; </code></pre>
8
2009-08-11T02:42:26Z
[ "python", "datetime", "parsing", "strptime" ]
Can you get more information about the online file?
1,258,280
<p>I have a online file: <a href="http://dl_dir.qq.com/qqfile/tm/TM2009Beta_chs.exe" rel="nofollow">http://dl_dir.qq.com/qqfile/tm/TM2009Beta_chs.exe</a> ,please donot download it, i want to determine the software version whether is changed, so i want more information about it. for example, using python,i can get this:</p> <pre><code>import urllib2,urllib req = urllib2.Request('http://dl_dir.qq.com/qqfile/tm/TM2009Beta_chs.exe') response = urllib2.urlopen(req) print response.info() print response.geturl() Content-Length: 16868680 Server: qqdlsrv(1.84 for linux) Connection: close Content-Disposition: attachment; filename=TM2009Beta_chs.exe Accept-Ranges: bytes Content-Type: application/octet-stream http://dl_dir.qq.com/qqfile/tm/TM2009Beta_chs.exe </code></pre> <p>Can you get more imformation to let me determine the software version is changed?</p>
-2
2009-08-11T02:58:01Z
1,258,295
<p>You can get all kinds of information about an EXE Windows file if you download it (the easy way, by running external utilities on it, or up to a point the hard way, via APIs and your own code simulating those utilities) -- a lot depends on what info was put into it when it was built. Without downloading, you can get only the info the server is giving you, which in this case seems pretty scarce -- I can't believe that server's configured to NOT tell you latest modified date &amp;c. In your shoes, I'd see what can be done on the server side to remedy that dearth of info, so you don't have to download the EXE just to find out more!</p>
2
2009-08-11T03:04:14Z
[ "python" ]
Can you get more information about the online file?
1,258,280
<p>I have a online file: <a href="http://dl_dir.qq.com/qqfile/tm/TM2009Beta_chs.exe" rel="nofollow">http://dl_dir.qq.com/qqfile/tm/TM2009Beta_chs.exe</a> ,please donot download it, i want to determine the software version whether is changed, so i want more information about it. for example, using python,i can get this:</p> <pre><code>import urllib2,urllib req = urllib2.Request('http://dl_dir.qq.com/qqfile/tm/TM2009Beta_chs.exe') response = urllib2.urlopen(req) print response.info() print response.geturl() Content-Length: 16868680 Server: qqdlsrv(1.84 for linux) Connection: close Content-Disposition: attachment; filename=TM2009Beta_chs.exe Accept-Ranges: bytes Content-Type: application/octet-stream http://dl_dir.qq.com/qqfile/tm/TM2009Beta_chs.exe </code></pre> <p>Can you get more imformation to let me determine the software version is changed?</p>
-2
2009-08-11T02:58:01Z
1,258,304
<ol> <li><p>Download the first thousand bytes or so of the file using the range header.</p></li> <li><p>Use <a href="http://code.google.com/p/pefile/" rel="nofollow">pefile</a> to parse the PE header and extract version information.</p></li> <li><p>With the data, <a href="http://books.google.com/books?id=Pas0YoxygnkC&amp;pg=PA40&amp;lpg=PA40&amp;dq=pe+header+layout&amp;source=bl&amp;ots=QmWK2D3niq&amp;sig=FEWTlTHlaukrlQ-mHybNqW81BjY&amp;hl=en&amp;ei=LuGASpnPH42YsgOj5JH9CA&amp;sa=X&amp;oi=book%5Fresult&amp;ct=result&amp;resnum=3#v=onepage&amp;q=pe%20header%20layout&amp;f=false" rel="nofollow">extract useful information</a> such as the time date stamp and other goodies that let you find changes in files without reading the whole thing.</p></li> </ol>
4
2009-08-11T03:09:39Z
[ "python" ]
Can you get more information about the online file?
1,258,280
<p>I have a online file: <a href="http://dl_dir.qq.com/qqfile/tm/TM2009Beta_chs.exe" rel="nofollow">http://dl_dir.qq.com/qqfile/tm/TM2009Beta_chs.exe</a> ,please donot download it, i want to determine the software version whether is changed, so i want more information about it. for example, using python,i can get this:</p> <pre><code>import urllib2,urllib req = urllib2.Request('http://dl_dir.qq.com/qqfile/tm/TM2009Beta_chs.exe') response = urllib2.urlopen(req) print response.info() print response.geturl() Content-Length: 16868680 Server: qqdlsrv(1.84 for linux) Connection: close Content-Disposition: attachment; filename=TM2009Beta_chs.exe Accept-Ranges: bytes Content-Type: application/octet-stream http://dl_dir.qq.com/qqfile/tm/TM2009Beta_chs.exe </code></pre> <p>Can you get more imformation to let me determine the software version is changed?</p>
-2
2009-08-11T02:58:01Z
1,258,329
<p>Configure your server to provide a <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.29" rel="nofollow">Last-Modified</a> header, and use <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.25" rel="nofollow">If-Modified-Since</a> in your request.</p>
2
2009-08-11T03:20:09Z
[ "python" ]
How to make python urllib2 follow redirect and keep post method
1,258,428
<p>I am using urllib2 to post data to a form. The problem is that the form replies with a 302 redirect. According to <a href="http://docs.python.org/library/urllib2.html#urllib2.HTTPRedirectHandler.redirect%5Frequest" rel="nofollow">Python HTTPRedirectHandler</a> the redirect handler will take the request and convert it from POST to GET and follow the 301 or 302. I would like to preserve the POST method and the data passed to the opener. I made an unsuccessful attempt at a custom HTTPRedirectHandler by simply adding data=req.get_data() to the new Request. </p> <p>I am sure this has been done before so I thought I would make a post.</p> <p>Note: this is similar to <a href="http://stackoverflow.com/questions/554446/how-do-i-prevent-pythons-urllib2-from-following-a-redirect">this post</a> and <a href="http://stackoverflow.com/questions/110498/is-there-an-easy-way-to-request-a-url-in-python-and-not-follow-redirects/110808">this one</a> but I don't want to prevent the redirect I just want to keep the POST data.</p> <p>Here is my HTTPRedirectHandler that does not work</p> <pre><code>class MyHTTPRedirectHandler(urllib2.HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): """Return a Request or None in response to a redirect. This is called by the http_error_30x methods when a redirection response is received. If a redirection should take place, return a new Request to allow http_error_30x to perform the redirect. Otherwise, raise HTTPError if no-one else should try to handle this url. Return None if you can't but another Handler might. """ m = req.get_method() if (code in (301, 302, 303, 307) and m in ("GET", "HEAD") or code in (301, 302, 303) and m == "POST"): # Strictly (according to RFC 2616), 301 or 302 in response # to a POST MUST NOT cause a redirection without confirmation # from the user (of urllib2, in this case). In practice, # essentially all clients do redirect in this case, so we # do the same. # be conciliant with URIs containing a space newurl = newurl.replace(' ', '%20') return Request(newurl, headers=req.headers, data=req.get_data(), origin_req_host=req.get_origin_req_host(), unverifiable=True) else: raise HTTPError(req.get_full_url(), code, msg, headers, fp) </code></pre>
2
2009-08-11T04:06:53Z
1,258,603
<p>This is actually a really bad thing to do the more I thought about it. For instance, if I submit a form to <a href="http://example.com/add">http://example.com/add</a> (with post data to add a item) and the response is a 302 redirect to <a href="http://example.com/add">http://example.com/add</a> and I post the same data that I posted the first time I will end up in an infinite loop. Not sure why I didn't think of this before. I'll leave the question here just as a warning to anyone else thinking about doing this.</p>
6
2009-08-11T05:40:57Z
[ "python", "automation", "urllib2" ]
How to get webcam info with WMI
1,258,455
<p>Which class that we can obtain webcam info? Thank</p>
0
2009-08-11T04:28:46Z
1,258,571
<p>I think you may actually need <a href="http://msdn.microsoft.com/en-us/library/ms630827%28VS.85%29.aspx" rel="nofollow">WIA</a> -- though the URL I'm quoting is all about images, not videos, I'm sure WIA also has video functionality, I just can't find good docs on that!-(</p>
1
2009-08-11T05:28:43Z
[ "python", "wmi" ]
How to get user input during a while loop without blocking
1,258,566
<p>I'm trying to write a while loop that constantly updates the screen by using os.system("clear") and then printing out a different text message every few seconds. How do I get user input during the loop? raw_input() just pauses and waits, which is not the functionality I want.</p> <pre><code>import os import time string = "the fox jumped over the lazy dog" words = string.split(" ") i = 0 while 1: os.system("clear") print words[i] time.sleep(1) i += 1 i = i%len(words) </code></pre> <p>I would like to be able to press 'q' or 'p' in the middle to quit and pause respectively.</p>
2
2009-08-11T05:27:05Z
1,258,581
<p>The <a href="http://docs.python.org/library/select.html">select</a> module in Python's standard library may be what you're looking for -- standard input has FD 0, though you may also need to put a terminal in "raw" (as opposed to "cooked") mode, on unix-y systems, to get single keypresses from it as opposed to whole lines complete with line-end. If on Windows, <a href="http://docs.python.org/library/msvcrt.html?highlight=msvcrt#module-msvcrt">msvcrt</a>, also in Python standard library, has all the functionality you need -- <code>msvcrt.kbhit()</code> tells you if any keystroke is pending, and, if so, <code>msvcrt.getch()</code> tells you what character it is.</p>
9
2009-08-11T05:33:24Z
[ "python" ]
How to get user input during a while loop without blocking
1,258,566
<p>I'm trying to write a while loop that constantly updates the screen by using os.system("clear") and then printing out a different text message every few seconds. How do I get user input during the loop? raw_input() just pauses and waits, which is not the functionality I want.</p> <pre><code>import os import time string = "the fox jumped over the lazy dog" words = string.split(" ") i = 0 while 1: os.system("clear") print words[i] time.sleep(1) i += 1 i = i%len(words) </code></pre> <p>I would like to be able to press 'q' or 'p' in the middle to quit and pause respectively.</p>
2
2009-08-11T05:27:05Z
1,258,952
<p>You can also check <a href="http://code.activestate.com/recipes/134892/" rel="nofollow">one of the recipes</a> available out there, which gives you the functionality you're looking for for both Unix and Windows.</p>
3
2009-08-11T07:53:02Z
[ "python" ]
How to get user input during a while loop without blocking
1,258,566
<p>I'm trying to write a while loop that constantly updates the screen by using os.system("clear") and then printing out a different text message every few seconds. How do I get user input during the loop? raw_input() just pauses and waits, which is not the functionality I want.</p> <pre><code>import os import time string = "the fox jumped over the lazy dog" words = string.split(" ") i = 0 while 1: os.system("clear") print words[i] time.sleep(1) i += 1 i = i%len(words) </code></pre> <p>I would like to be able to press 'q' or 'p' in the middle to quit and pause respectively.</p>
2
2009-08-11T05:27:05Z
1,261,079
<p>You can do that with threads, here is a basic example :</p> <pre><code>import threading, os, time, itertools, Queue # setting a cross platform getch like function # thks to the Python Cookbook # why isn't standard on this battery included language ? try : # on windows from msvcrt import getch except ImportError : # on unix like systems import sys, tty, termios def getch() : fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) try : tty.setraw(fd) ch = sys.stdin.read(1) finally : termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) return ch # this will allow us to communicate between the two threads # Queue is a FIFO list, the param is the size limit, 0 for infinite commands = Queue.Queue(0) # the thread reading the command from the user input def control(commands) : while 1 : command = getch() commands.put(command) # put the command in the queue so the other thread can read it # don't forget to quit here as well, or you will have memory leaks if command == "q" : break # your function displaying the words in an infinite loop def display(commands): string = "the fox jumped over the lazy dog" words = string.split(" ") pause = False command = "" # we create an infinite generator from you list # much better than using indices word_list = itertools.cycle(words) # BTW, in Python itertools is your best friend while 1 : # parsing the command queue try: # false means "do not block the thread if the queue is empty" # a second parameter can set a millisecond time out command = commands.get(False) except Queue.Empty, e: command = "" # behave according to the command if command == "q" : break if command == "p" : pause = True if command == "r" : pause = False # if pause is set to off, then print the word # your initial code, rewritten with a generator if not pause : os.system("clear") print word_list.next() # getting the next item from the infinite generator # wait anyway for a second, you can tweak that time.sleep(1) # then start the two threads displayer = threading.Thread(None, # always to None since the ThreadGroup class is not implemented yet display, # the function the thread will run None, # doo, don't remember and too lazy to look in the doc (commands,), # *args to pass to the function {}) # **kwargs to pass to the function controler = threading.Thread(None, control, None, (commands,), {}) if __name__ == "__main__" : displayer.start() controler.start() </code></pre> <p>As usual, using threads is tricky, so be sure you understand what you do before coding that.</p> <p>Warning : Queue will be rename in queue in Python 3.</p>
1
2009-08-11T15:21:46Z
[ "python" ]
storing classmethod reference in tuple does not work as in variable
1,258,690
<pre><code>#!/usr/bin/python class Bar(object): @staticmethod def ruleOn(rule): if isinstance(rule, tuple): print rule[0] print rule[0].__get__(None, Foo) else: print rule class Foo(object): @classmethod def callRule(cls): Bar.ruleOn(cls.RULE1) Bar.ruleOn(cls.RULE2) @classmethod def check(cls): print "I am check" RULE1 = check RULE2 = (check,) Foo.callRule() </code></pre> <p><strong>Output:</strong></p> <pre><code>&lt;bound method type.check of &lt;class '__main__.Foo'&gt;&gt; &lt;classmethod object at 0xb7d313a4&gt; &lt;bound method type.check of &lt;class '__main__.Foo'&gt;&gt; </code></pre> <p>As you can see I'm trying to store a reference to a classmethod function in a tuple for future use.</p> <p>However, it seems to store the object itself rather then reference to the bound function.</p> <p>As you see it works for a variable reference.</p> <p>The only way to get it is to use <code>__get__</code>, which requires the name of the class it belongs to, which is not available at the time of the <code>RULE</code> variable assignment.</p> <p>Any ideas anyone?</p>
0
2009-08-11T06:19:34Z
1,258,710
<p>This is because method are actually functions in Python. They only become bound methods when you look them up on the constructed class instance. See my answer to <a href="http://stackoverflow.com/questions/852308/how-the-method-resolution-and-invocation-works-internally-in-python/870650#870650">this question</a> for more details. The non-tuple variant works because it is conceptually the same as accessing a classmethod.</p> <p>If you want to assign bound classmethods to class attributes you'll have to do that after you construct the class:</p> <pre><code>class Foo(object): @classmethod def callRule(cls): Bar.ruleOn(cls.RULE1) Bar.ruleOn(cls.RULE2) @classmethod def check(cls): print "I am check" Foo.RULE1 = Foo.check Foo.RULE2 = (Foo.check,) </code></pre>
0
2009-08-11T06:28:50Z
[ "python" ]
fuzzy timestamp parsing with Python
1,258,712
<p>Is there a Python module to interpret fuzzy timestamps like the date command in unix:</p> <pre><code>&gt; date -d "2 minutes ago" Tue Aug 11 16:24:05 EST 2009 </code></pre> <p>The closest I have found so far is dateutil.parser, which fails for the above example.</p> <p>thanks</p>
5
2009-08-11T06:29:11Z
1,258,858
<p>Check out this open source module: <a href="https://github.com/bear/parsedatetime" rel="nofollow">parsedatetime</a></p>
8
2009-08-11T07:21:47Z
[ "python", "date", "parsing", "timestamp" ]
fuzzy timestamp parsing with Python
1,258,712
<p>Is there a Python module to interpret fuzzy timestamps like the date command in unix:</p> <pre><code>&gt; date -d "2 minutes ago" Tue Aug 11 16:24:05 EST 2009 </code></pre> <p>The closest I have found so far is dateutil.parser, which fails for the above example.</p> <p>thanks</p>
5
2009-08-11T06:29:11Z
1,378,134
<p>I have been dabbling with this using pyparsing - you can find my latest attempt <a href="http://pyparsing.wikispaces.com/UnderDevelopment#toc0" rel="nofollow" title="Time expression parser">here</a>. It works for these test cases:</p> <pre><code>today tomorrow yesterday in a couple of days a couple of days from now a couple of days from today in a day 3 days ago 3 days from now a day ago now 10 minutes ago 10 minutes from now in 10 minutes in a minute in a couple of minutes 20 seconds ago in 30 seconds 20 seconds before noon 20 seconds before noon tomorrow noon midnight noon tomorrow </code></pre>
1
2009-09-04T09:20:43Z
[ "python", "date", "parsing", "timestamp" ]
Python Subprocess - Redirect stdout/err to two places
1,258,863
<p>I have a small python script which invokes an external process using <code>subprocess</code>. I want to redirect stdout and stderr to both a log file and to the terminal.</p> <p>How can this be done?</p>
9
2009-08-11T07:22:29Z
1,258,929
<p>You can do this with <a href="http://docs.python.org/library/subprocess.html#subprocess.PIPE"><code>subprocess.PIPE</code></a>.</p> <p>You can find <a href="http://blog.kagesenshi.org/2008/02/teeing-python-subprocesspopen-output.html">some sample code here</a>.</p>
8
2009-08-11T07:44:36Z
[ "python", "redirect", "subprocess", "stdout" ]
Python: How can I choose which module to import when they are named the same
1,259,106
<p>Lets say I'm in a file called <code>openid.py</code> and I do :</p> <pre><code>from openid.consumer.discover import discover, DiscoveryFailure </code></pre> <p>I have the <code>openid</code> module on my pythonpath but the interpreter seems to be trying to use my <code>openid.py</code> file. How can I get the library version?</p> <p>(Of course, something other than the obvious 'rename your file' answer would be nice).</p>
6
2009-08-11T08:44:44Z
1,259,132
<p><strong>Rename it</strong>. This is the idea behind name spaces. your <code>openid</code> could be a sub-module in your top module <code>project</code>. your <code>email</code> will clash with top module <code>email</code> in stdlib.</p> <p>because your openid is not universal, it provides a special case for your project.</p>
3
2009-08-11T08:51:01Z
[ "python", "import", "namespaces" ]
Python: How can I choose which module to import when they are named the same
1,259,106
<p>Lets say I'm in a file called <code>openid.py</code> and I do :</p> <pre><code>from openid.consumer.discover import discover, DiscoveryFailure </code></pre> <p>I have the <code>openid</code> module on my pythonpath but the interpreter seems to be trying to use my <code>openid.py</code> file. How can I get the library version?</p> <p>(Of course, something other than the obvious 'rename your file' answer would be nice).</p>
6
2009-08-11T08:44:44Z
1,259,151
<p>You can use relative or absolute imports (depending on the specifics of your situation), which are covered in <a href="http://www.python.org/dev/peps/pep-0328/" rel="nofollow">PEP 328</a> most recently. Of course, seriously, you should not be creating naming conflicts like this and should rename your file.</p>
1
2009-08-11T08:54:05Z
[ "python", "import", "namespaces" ]
Python: How can I choose which module to import when they are named the same
1,259,106
<p>Lets say I'm in a file called <code>openid.py</code> and I do :</p> <pre><code>from openid.consumer.discover import discover, DiscoveryFailure </code></pre> <p>I have the <code>openid</code> module on my pythonpath but the interpreter seems to be trying to use my <code>openid.py</code> file. How can I get the library version?</p> <p>(Of course, something other than the obvious 'rename your file' answer would be nice).</p>
6
2009-08-11T08:44:44Z
1,259,275
<p>Thats the reason absolute imports have been chosen as the new default behaviour. However, they are not yet the default in 2.6 (maybe in 2.7...). You can get their behaviour now by importing them from the future:</p> <pre><code>from __future__ import absolute_import </code></pre> <p>You can find out more about this in the PEP metnioned by Nick or (easier to understand, I think) in the document <a href="http://docs.python.org/whatsnew/2.5.html">"What's New in Python 2.5"</a>. </p>
9
2009-08-11T09:22:51Z
[ "python", "import", "namespaces" ]
Python: How can I choose which module to import when they are named the same
1,259,106
<p>Lets say I'm in a file called <code>openid.py</code> and I do :</p> <pre><code>from openid.consumer.discover import discover, DiscoveryFailure </code></pre> <p>I have the <code>openid</code> module on my pythonpath but the interpreter seems to be trying to use my <code>openid.py</code> file. How can I get the library version?</p> <p>(Of course, something other than the obvious 'rename your file' answer would be nice).</p>
6
2009-08-11T08:44:44Z
1,259,955
<p>You could try shuffling <code>sys.path</code>, to move the interesting directories to the front before doing the import.</p>
-1
2009-08-11T12:09:37Z
[ "python", "import", "namespaces" ]
Python: How can I choose which module to import when they are named the same
1,259,106
<p>Lets say I'm in a file called <code>openid.py</code> and I do :</p> <pre><code>from openid.consumer.discover import discover, DiscoveryFailure </code></pre> <p>I have the <code>openid</code> module on my pythonpath but the interpreter seems to be trying to use my <code>openid.py</code> file. How can I get the library version?</p> <p>(Of course, something other than the obvious 'rename your file' answer would be nice).</p>
6
2009-08-11T08:44:44Z
1,261,060
<p>I won't get into the polemics on renaming and instead focus on showing you how to do what you want (whether it's "good for you" or not;-). The solution is not difficult...</p> <p>Just set <code>__path__</code>! A little demonstration:</p> <pre><code>$ mkdir /tmp/modules /tmp/packages $ mkdir /tmp/packages/openid $ echo 'print "Package!"' &gt; /tmp/packages/openid/__init__.py $ gvim /tmp/modules/openid.py $ PYTHONPATH='/tmp/modules:/tmp/packages' python -c'import openid' Module! Package! </code></pre> <p>this shows a <em>module</em> openid managing to import a homonymous <em>package</em> even though the module's path comes earlier in sys.path, <strong>and</strong> <code>sys.modules['openid']</code> is clearly already set at that time. And all the "secret" is in openid.py's simple code...:</p> <pre><code>print "Module!" __path__ = ['/tmp/packages'] import openid </code></pre> <p>without the <code>__path__</code> assignment, of course, it would only emit <code>Module!</code>.</p> <p>Also works for importing submodules within the package, of course. Do:</p> <pre><code>$ echo 'print "Submod!"' &gt; /tmp/packages/openid/submod.py </code></pre> <p>and change openid.py's last line to</p> <pre><code>from openid import submod </code></pre> <p>and you'll see:</p> <pre><code>$ PYTHONPATH='/tmp/modules:/tmp/packages' python -c'import openid' Module! Package! Submod! $ </code></pre>
2
2009-08-11T15:20:26Z
[ "python", "import", "namespaces" ]
django Datefield to Unix timestamp
1,259,219
<p>Hello In a model I have a such field: mydate = models.DateField()</p> <p>now a javascript graph function requires unix timestamp such as "1196550000000", how can I return the unix timestamp of my mydate input.</p> <p>Thanks</p>
26
2009-08-11T09:11:07Z
1,259,333
<p>In your <code>views.py</code>, you can convert the value of <code>mydate</code> to seconds since the Unix epoch as follows:</p> <pre><code>seconds = time.mktime(mydate.timetuple()) </code></pre> <p>Then pass it in the dictionary you use as an argument to <code>render_to_response()</code> (or whatever you're using to render your view), and in your template, stick <code>{{seconds}}</code> into a hidden field, which you can then pull out of the DOM to pass to your javascript graph function.</p> <p>Note that a <code>DateField</code> maps to the Python object <code>datetime.date</code>, and as such, its <code>timetuple</code> will have its hours, minutes and seconds fields set to 0. If that's not fine-grained enough for you, you'll need to change <code>mydate</code> to a DateTimeField and it'll be a <code>datetime.datetime</code>. You can still use <code>mydate.timetuple()</code> if you do this.</p> <p>Also, I'm assuming you're using local time. If you're using UTC time, you want <code>calendar.gmtime()</code> rather than <code>time.mktime()</code> and <code>mydate.utctimetuple()</code> rather than <code>mydate.timetuple()</code>, but <code>utctimetuple()</code> is only a valid method for <code>datetime.datetime</code> objects. See the <a href="http://docs.python.org/library/datetime.html" rel="nofollow"><code>datetime</code></a> docs (also <code>time</code> and <code>calendar</code>) for more fiddly details.</p> <p>EDIT: fiddly details such as the fact that <code>mktime()</code> returns a float, which piquadrat remembered and I didn't. The custom-filter approach is also a good one. Voting that one up.</p>
4
2009-08-11T09:35:22Z
[ "python", "django", "unix-timestamp" ]
django Datefield to Unix timestamp
1,259,219
<p>Hello In a model I have a such field: mydate = models.DateField()</p> <p>now a javascript graph function requires unix timestamp such as "1196550000000", how can I return the unix timestamp of my mydate input.</p> <p>Thanks</p>
26
2009-08-11T09:11:07Z
1,259,378
<p><strong>edit: please check the second answer, it has a much better solution</strong></p> <p>In python code, you can do this to convert a date or datetime to the Unix Epoch</p> <pre><code>import time epoch = int(time.mktime(mydate.timetuple())*1000) </code></pre> <p>This doesn't work in a Django template though, so you need a custom filter, e.g:</p> <pre><code>import time from django import template register = template.Library() @register.filter def epoch(value): try: return int(time.mktime(value.timetuple())*1000) except AttributeError: return '' </code></pre>
23
2009-08-11T09:45:05Z
[ "python", "django", "unix-timestamp" ]
django Datefield to Unix timestamp
1,259,219
<p>Hello In a model I have a such field: mydate = models.DateField()</p> <p>now a javascript graph function requires unix timestamp such as "1196550000000", how can I return the unix timestamp of my mydate input.</p> <p>Thanks</p>
26
2009-08-11T09:11:07Z
3,376,435
<p>I know another answer was accepted a while ago, but this question appears high on Google's search results, so I will add another answer. </p> <p>If you are working at the template level, you can use the <a href="https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#std%3atemplatefilter-date"><code>U</code> parameter</a> to the <code>date</code> filter, e.g.:</p> <pre><code>{{ mydate|date:"U" }} </code></pre> <p>Note that it will be based upon the <code>TIMEZONE</code> in your settings.py.</p>
82
2010-07-31T01:44:11Z
[ "python", "django", "unix-timestamp" ]
django Datefield to Unix timestamp
1,259,219
<p>Hello In a model I have a such field: mydate = models.DateField()</p> <p>now a javascript graph function requires unix timestamp such as "1196550000000", how can I return the unix timestamp of my mydate input.</p> <p>Thanks</p>
26
2009-08-11T09:11:07Z
7,387,012
<p>And if you're not in the template layer, you can still use the same underlying django utils. Ex:</p> <pre><code>from django.utils.dateformat import format print format(mymodel.mydatefield, 'U') </code></pre>
47
2011-09-12T11:17:02Z
[ "python", "django", "unix-timestamp" ]
django Datefield to Unix timestamp
1,259,219
<p>Hello In a model I have a such field: mydate = models.DateField()</p> <p>now a javascript graph function requires unix timestamp such as "1196550000000", how can I return the unix timestamp of my mydate input.</p> <p>Thanks</p>
26
2009-08-11T09:11:07Z
40,096,453
<p>Another option:</p> <pre><code>import time from django.utils import timezone naive_date = timezone.make_naive(mydate, timezone.get_current_timezone()) print int(time.mktime(naive_date.timetuple())) </code></pre>
0
2016-10-17T22:07:32Z
[ "python", "django", "unix-timestamp" ]
How to find the installation path of IronPython
1,259,296
<p>I have few python scripts of which one is to be executed in IronPython interpreter. How to find the installation path of IronPython. I searched the registry. To my surprise, it was not there.</p>
0
2009-08-11T09:27:34Z
1,259,717
<p>Try this:</p> <pre><code>import sys print sys.executable </code></pre> <p>Disclaimer: I don't know if it will work on IronPython.</p>
1
2009-08-11T11:12:30Z
[ "python", "ironpython" ]
How to find the installation path of IronPython
1,259,296
<p>I have few python scripts of which one is to be executed in IronPython interpreter. How to find the installation path of IronPython. I searched the registry. To my surprise, it was not there.</p>
0
2009-08-11T09:27:34Z
20,639,321
<p>From the registry, you can check HKLM\SOFTWARE\IronPython\2.7\InstallPath</p> <p>It was useful for me.</p> <p><a href="https://ironpython.codeplex.com/workitem/34692" rel="nofollow">https://ironpython.codeplex.com/workitem/34692</a></p> <p>Version number can be retrieved like this (as of IPy 2.7.4):</p> <pre class="lang-cs prettyprint-override"><code>//Implementation::version backs "sys.version_info" var version_tuple = new IronPython.Runtime.Implementation().version; var version = version_tuple.major + "." + version_tuple.minor; </code></pre>
1
2013-12-17T16:20:19Z
[ "python", "ironpython" ]
Is it a good idea to use super() in Python?
1,259,547
<p>Or should I just explicitly reference the superclasses whose methods I want to call?</p> <p>It seems brittle to repeat the names of super classes when referencing their constructors, but this page <a href="http://fuhm.net/super-harmful/">http://fuhm.net/super-harmful/</a> makes some good arguments against using super().</p>
10
2009-08-11T10:32:51Z
1,259,584
<p>Yes, just stick to keyword arguments in your <code>__init__</code> methods and you shouldn't have too many problems.</p> <p>I agree that it is brittle, but no less so than using the name of the inherited class.</p>
1
2009-08-11T10:41:19Z
[ "python", "oop", "super" ]
Is it a good idea to use super() in Python?
1,259,547
<p>Or should I just explicitly reference the superclasses whose methods I want to call?</p> <p>It seems brittle to repeat the names of super classes when referencing their constructors, but this page <a href="http://fuhm.net/super-harmful/">http://fuhm.net/super-harmful/</a> makes some good arguments against using super().</p>
10
2009-08-11T10:32:51Z
1,259,592
<p>You can use super, but as the article says, there are drawbacks. As long as you know them, there is no problem with using the feature. It's like people saying "use composition, not inheritance" or "never use global variables". If the feature exists, there is a reason. Just be sure to understand the why and the what and use them wisely.</p>
5
2009-08-11T10:42:28Z
[ "python", "oop", "super" ]
Is it a good idea to use super() in Python?
1,259,547
<p>Or should I just explicitly reference the superclasses whose methods I want to call?</p> <p>It seems brittle to repeat the names of super classes when referencing their constructors, but this page <a href="http://fuhm.net/super-harmful/">http://fuhm.net/super-harmful/</a> makes some good arguments against using super().</p>
10
2009-08-11T10:32:51Z
1,259,594
<p>I like super() more because it allows you to change the inherited class (for example when you're refactoring and add an intermediate class) without changing it on all the methods.</p>
2
2009-08-11T10:43:21Z
[ "python", "oop", "super" ]
Is it a good idea to use super() in Python?
1,259,547
<p>Or should I just explicitly reference the superclasses whose methods I want to call?</p> <p>It seems brittle to repeat the names of super classes when referencing their constructors, but this page <a href="http://fuhm.net/super-harmful/">http://fuhm.net/super-harmful/</a> makes some good arguments against using super().</p>
10
2009-08-11T10:32:51Z
1,259,665
<p>The book <a href="http://www.packtpub.com/expert-python-programming/" rel="nofollow">Expert Python Programming</a> has discussed the topic of "super pitfalls" in chapter 3. It is worth reading. Below is the book's conclusion:</p> <blockquote> <p>Super usage has to be consistent: In a class hierarchy, super should be used everywhere or nowhere. Mixing super and classic calls is a confusing practice. People tend to avoid super, for their code to be more explicit. </p> </blockquote> <p><strong>Edit:</strong> Today I read this part of the book again. I'll copy some more sentences, since super usage is tricky:</p> <ul> <li>Avoid multiple inheritance in your code.</li> <li>Be consistent with its usage and don't mix new-style and old-style.</li> <li>Check the class hierarchy before calling its methods in your subclass.</li> </ul>
8
2009-08-11T10:59:23Z
[ "python", "oop", "super" ]
Is it a good idea to use super() in Python?
1,259,547
<p>Or should I just explicitly reference the superclasses whose methods I want to call?</p> <p>It seems brittle to repeat the names of super classes when referencing their constructors, but this page <a href="http://fuhm.net/super-harmful/">http://fuhm.net/super-harmful/</a> makes some good arguments against using super().</p>
10
2009-08-11T10:32:51Z
1,259,935
<p>The problem people have with <code>super</code> is more a problem of multiple inheritance. So it is a little unfair to blame <code>super</code>. Without <code>super</code> multiple inheritance is even worse. Michele Simionato nicely wrapped this up in his <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=237121" rel="nofollow">blog article</a> on super:</p> <blockquote> <p>On the other hand, one may wonder if all super warts aren't hints of some serious problem underlying. It may well be that the problem is not with super, nor with cooperative methods: the problem may be with multiple inheritance itself.</p> </blockquote> <p>So the main lesson is that you should try to avoid multiple inheritance.</p> <p>In the interest of consistency I always use super, even if for single inheritance it does not really matter (apart from the small advantage of not having to know the parent class name). In Python 3+ <code>super</code> is more convenient, so there one should definitely use super.</p>
3
2009-08-11T12:05:56Z
[ "python", "oop", "super" ]
Is it a good idea to use super() in Python?
1,259,547
<p>Or should I just explicitly reference the superclasses whose methods I want to call?</p> <p>It seems brittle to repeat the names of super classes when referencing their constructors, but this page <a href="http://fuhm.net/super-harmful/">http://fuhm.net/super-harmful/</a> makes some good arguments against using super().</p>
10
2009-08-11T10:32:51Z
1,261,712
<p>super() tries to solve for you the problem of multiple inheritance; it's hard to replicate its semantics and you certainly shouldn't create any new semantics unless you're completely sure. </p> <p>For single inheritance, there's really no difference between </p> <pre><code>class X(Y): def func(self): Y.func(self) </code></pre> <p>and</p> <pre><code>class X(Y): def func(self): super().func() </code></pre> <p>so I guess that's just the question of taste.</p>
2
2009-08-11T17:05:40Z
[ "python", "oop", "super" ]
iCalendar reader for Python?
1,259,857
<p>I'm looking to automate the status reports that I have to send to my manager. Since I use a to-do software that writes to iCalendar format, I would like be able to format an email out of the ics file.</p> <p>I'm starting my work with: <a href="http://codespeak.net/icalendar/" rel="nofollow">http://codespeak.net/icalendar/</a> which looks pretty good, but it does have some rough edges.</p> <p>What iCalendar reader would you suggest for python?</p>
2
2009-08-11T11:41:45Z
16,740,550
<p>I know this question is old, but this looks to be the most popular Python iCalendar parser these days. It's available on Pypi.</p> <p>Pypi page: <a href="https://pypi.python.org/pypi/icalendar" rel="nofollow">https://pypi.python.org/pypi/icalendar</a><br> Documentation: <a href="http://icalendar.readthedocs.org/en/latest/" rel="nofollow">http://icalendar.readthedocs.org/en/latest/</a><br> Github: <a href="https://github.com/collective/icalendar" rel="nofollow">https://github.com/collective/icalendar</a></p>
2
2013-05-24T17:28:32Z
[ "python", "icalendar" ]
iCalendar reader for Python?
1,259,857
<p>I'm looking to automate the status reports that I have to send to my manager. Since I use a to-do software that writes to iCalendar format, I would like be able to format an email out of the ics file.</p> <p>I'm starting my work with: <a href="http://codespeak.net/icalendar/" rel="nofollow">http://codespeak.net/icalendar/</a> which looks pretty good, but it does have some rough edges.</p> <p>What iCalendar reader would you suggest for python?</p>
2
2009-08-11T11:41:45Z
30,962,466
<p>There is <a href="https://github.com/C4ptainCrunch/ics.py" rel="nofollow">ics.py</a> which has a very "pythonic" interfaces and abstracts away the not very intuitive syntax of the iCalendar format <a href="http://tools.ietf.org/html/rfc5545" rel="nofollow">RFC5545</a>.</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; from ics import Calendar, Event &gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; c = Calendar() &gt;&gt;&gt; e = Event() &gt;&gt;&gt; e.name = "My cool event" &gt;&gt;&gt; e.begin = '20140101 10:00:00' &gt;&gt;&gt; e.end = datetime(2014, 1, 1, 11, 30) &gt;&gt;&gt; c.events.append(e) &gt;&gt;&gt; c.events [&lt;Event 'My cool event' begin:2014-01-01 10:00:00 end:2014-01-01 11:30:00&gt;] &gt;&gt;&gt; with open('my.ics', 'w') as my_file: &gt;&gt;&gt; my_file.writelines(c) </code></pre>
0
2015-06-21T08:07:40Z
[ "python", "icalendar" ]
How can I use Emacs Flymake mode for python with pyflakes and pylint checking code?
1,259,873
<p>For checking code in python mode I use flymake with <a href="http://www.emacswiki.org/cgi-bin/wiki/PythonMode#toc8">pyflakes</a></p> <p>Also I want check code style (pep8) with pylint (description on the same page with pyflakes)</p> <p>This solutions work. But I can't configure flymake for work with pyflakes and pylint together. How can I do it?</p>
22
2009-08-11T11:47:53Z
1,261,640
<p>You may want to check out the Lisp script here (<a href="http://charlie137-2.blogspot.com/2009/08/check-python-coding-style-on-fly-with.html" rel="nofollow">http://charlie137-2.blogspot.com/2009/08/check-python-coding-style-on-fly-with.html</a>), which should help with checking PEP8 a la pep8.py. I don't use pyflakes or pylint, but I imagine you could easily adjust this to work with other checkers. </p>
0
2009-08-11T16:54:28Z
[ "python", "emacs", "pylint", "pep8", "pyflakes" ]
How can I use Emacs Flymake mode for python with pyflakes and pylint checking code?
1,259,873
<p>For checking code in python mode I use flymake with <a href="http://www.emacswiki.org/cgi-bin/wiki/PythonMode#toc8">pyflakes</a></p> <p>Also I want check code style (pep8) with pylint (description on the same page with pyflakes)</p> <p>This solutions work. But I can't configure flymake for work with pyflakes and pylint together. How can I do it?</p>
22
2009-08-11T11:47:53Z
1,393,590
<p>Well, flymake is just looking for a executable command thats output lines in a predefined format. You can make a shell script for example that will call successively all the checkers you want...</p> <p>You must also make sure that your script ends by returning errorlevel 0. So this is an example:</p> <p>This is what I've done in a "pycheckers" script:</p> <pre><code>#!/bin/bash epylint "$1" 2&gt;/dev/null pyflakes "$1" pep8 --ignore=E221,E701,E202 --repeat "$1" true </code></pre> <p>For the emacs lisp part:</p> <pre><code>(when (load "flymake" t) (defun flymake-pyflakes-init () (let* ((temp-file (flymake-init-create-temp-buffer-copy 'flymake-create-temp-inplace)) (local-file (file-relative-name temp-file (file-name-directory buffer-file-name)))) (list "pycheckers" (list local-file)))) (add-to-list 'flymake-allowed-file-name-masks '("\\.py\\'" flymake-pyflakes-init))) </code></pre>
34
2009-09-08T11:57:18Z
[ "python", "emacs", "pylint", "pep8", "pyflakes" ]
How can I use Emacs Flymake mode for python with pyflakes and pylint checking code?
1,259,873
<p>For checking code in python mode I use flymake with <a href="http://www.emacswiki.org/cgi-bin/wiki/PythonMode#toc8">pyflakes</a></p> <p>Also I want check code style (pep8) with pylint (description on the same page with pyflakes)</p> <p>This solutions work. But I can't configure flymake for work with pyflakes and pylint together. How can I do it?</p>
22
2009-08-11T11:47:53Z
1,621,489
<p>Usually one can enable flymake mode in the python-mode-hook. Unfortunately that causes issues with things like py-execute-buffer which create temporary buffers which invoke the hook and then cause flymake mode to hiccup because of the lack of "real file". The solution is to modify the conditions where you add the hook:- e.g mine is:</p> <pre><code>(add-hook 'python-mode-hook (lambda () (unless (eq buffer-file-name nil) (flymake-mode 1)) ;dont invoke flymake on temporary buffers for the interpreter (local-set-key [f2] 'flymake-goto-prev-error) (local-set-key [f3] 'flymake-goto-next-error) )) </code></pre>
7
2009-10-25T17:31:25Z
[ "python", "emacs", "pylint", "pep8", "pyflakes" ]
How can I use Emacs Flymake mode for python with pyflakes and pylint checking code?
1,259,873
<p>For checking code in python mode I use flymake with <a href="http://www.emacswiki.org/cgi-bin/wiki/PythonMode#toc8">pyflakes</a></p> <p>Also I want check code style (pep8) with pylint (description on the same page with pyflakes)</p> <p>This solutions work. But I can't configure flymake for work with pyflakes and pylint together. How can I do it?</p>
22
2009-08-11T11:47:53Z
16,185,035
<p>Windows batch version of vaab's <code>pychechker</code></p> <pre><code>@echo on pylint %1 pep8 --ignore=E221,E701,E202 --repeat %1 pyflakes %1 </code></pre>
0
2013-04-24T06:39:12Z
[ "python", "emacs", "pylint", "pep8", "pyflakes" ]
Python : Assert that variable is instance method?
1,259,963
<p>How can one check if a variable is an instance method or not? I'm using python 2.5.</p> <p>Something like this:</p> <pre><code>class Test: def method(self): pass assert is_instance_method(Test().method) </code></pre>
25
2009-08-11T12:10:54Z
1,260,881
<p>If you want to know if it is precisely an instance method use the following function. (It considers methods that are defined on a metaclass and accessed on a class class methods, although they could also be considered instance methods)</p> <pre><code>import types def is_instance_method(obj): """Checks if an object is a bound method on an instance.""" if not isinstance(obj, types.MethodType): return False # Not a method if obj.im_self is None: return False # Method is not bound if issubclass(obj.im_class, type) or obj.im_class is types.ClassType: return False # Method is a classmethod return True </code></pre> <p>Usually checking for that is a bad idea. It is more flexible to be able to use any <em>callable()</em> interchangeably with methods.</p>
8
2009-08-11T14:53:48Z
[ "python", "methods", "instance", "assert" ]
Python : Assert that variable is instance method?
1,259,963
<p>How can one check if a variable is an instance method or not? I'm using python 2.5.</p> <p>Something like this:</p> <pre><code>class Test: def method(self): pass assert is_instance_method(Test().method) </code></pre>
25
2009-08-11T12:10:54Z
1,260,997
<p><a href="http://docs.python.org/library/inspect.html#inspect.ismethod"><code>inspect.ismethod</code></a> is what you want to find out if you definitely have a method, rather than just something you can call.</p> <pre><code>import inspect def foo(): pass class Test(object): def method(self): pass print inspect.ismethod(foo) # False print inspect.ismethod(Test) # False print inspect.ismethod(Test.method) # True print inspect.ismethod(Test().method) # True print callable(foo) # True print callable(Test) # True print callable(Test.method) # True print callable(Test().method) # True </code></pre> <p><code>callable</code> is true if the argument if the argument is a method, a function (including <code>lambda</code>s), an instance with <code>__call__</code> or a class. </p> <p>Methods have different properties than functions (like <code>im_class</code> and <code>im_self</code>). So you want</p> <pre><code>assert inspect.ismethod(Test().method) </code></pre>
39
2009-08-11T15:10:56Z
[ "python", "methods", "instance", "assert" ]
OS locale support for use in Python
1,259,971
<p>The following Python code works on my Windows machine (Python 2.5.4), but doesn't on my Debian machine (Python 2.5.0). I'm guessing it's OS dependent.</p> <pre><code>import locale locale.setlocale( locale.LC_ALL, 'English_United States.1252' ) </code></pre> <p>I receive the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.5/locale.py", line 476, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting </code></pre> <p>Questions:</p> <ul> <li>Is it OS dependent?</li> <li>How can I find the supported locale list within Python?</li> <li>How can I match between Windows locales and Debian locales?</li> </ul>
15
2009-08-11T12:12:19Z
1,260,005
<p>It is OS dependent.</p> <p>To get the list of local available you can use <code>locale -a</code> in a shell</p> <p>I think the local you want is something like <a href="http://en.wikipedia.org/wiki/Windows-1252"><code>Windows-1252</code></a></p>
21
2009-08-11T12:20:27Z
[ "python", "locale" ]
OS locale support for use in Python
1,259,971
<p>The following Python code works on my Windows machine (Python 2.5.4), but doesn't on my Debian machine (Python 2.5.0). I'm guessing it's OS dependent.</p> <pre><code>import locale locale.setlocale( locale.LC_ALL, 'English_United States.1252' ) </code></pre> <p>I receive the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.5/locale.py", line 476, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting </code></pre> <p>Questions:</p> <ul> <li>Is it OS dependent?</li> <li>How can I find the supported locale list within Python?</li> <li>How can I match between Windows locales and Debian locales?</li> </ul>
15
2009-08-11T12:12:19Z
1,260,101
<p>Look inside the <code>locale.locale_alias</code> dictionary.</p> <pre><code>&gt;&gt;&gt; import locale &gt;&gt;&gt; len(locale.locale_alias) 789 &gt;&gt;&gt; locale.locale_alias.keys()[:5] ['ko_kr.euc', 'is_is', 'ja_jp.mscode', 'kw_gb@euro', 'yi_us.cp1255'] &gt;&gt;&gt; </code></pre> <p>(In my 2.6.2 installation there are 789 locale names.)</p>
7
2009-08-11T12:40:55Z
[ "python", "locale" ]
OS locale support for use in Python
1,259,971
<p>The following Python code works on my Windows machine (Python 2.5.4), but doesn't on my Debian machine (Python 2.5.0). I'm guessing it's OS dependent.</p> <pre><code>import locale locale.setlocale( locale.LC_ALL, 'English_United States.1252' ) </code></pre> <p>I receive the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.5/locale.py", line 476, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting </code></pre> <p>Questions:</p> <ul> <li>Is it OS dependent?</li> <li>How can I find the supported locale list within Python?</li> <li>How can I match between Windows locales and Debian locales?</li> </ul>
15
2009-08-11T12:12:19Z
5,661,043
<p>try</p> <pre><code>apt-get install locales-all </code></pre> <p>for me it works like a charm</p>
9
2011-04-14T09:24:28Z
[ "python", "locale" ]
OS locale support for use in Python
1,259,971
<p>The following Python code works on my Windows machine (Python 2.5.4), but doesn't on my Debian machine (Python 2.5.0). I'm guessing it's OS dependent.</p> <pre><code>import locale locale.setlocale( locale.LC_ALL, 'English_United States.1252' ) </code></pre> <p>I receive the following error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/usr/lib/python2.5/locale.py", line 476, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting </code></pre> <p>Questions:</p> <ul> <li>Is it OS dependent?</li> <li>How can I find the supported locale list within Python?</li> <li>How can I match between Windows locales and Debian locales?</li> </ul>
15
2009-08-11T12:12:19Z
12,976,242
<p>On Ubuntu Precise type</p> <p>sudo locale-gen en_US</p>
1
2012-10-19T14:19:59Z
[ "python", "locale" ]
How to comply to PEP 257 docstrings when using Python's optparse module?
1,259,982
<p>According to <a href="http://www.python.org/dev/peps/pep-0257/#multi-line-docstrings" rel="nofollow">PEP 257</a> the docstring of command line script should be its usage message.</p> <blockquote> <p>The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.</p> </blockquote> <p>So my docstring would look something like this:</p> <pre> &lt;tool name&gt; &lt;copyright info&gt; Usage: &lt;prog name&gt; [options] [args] some text explaining the usage... Options: -h, --help show this help message and exit ... </pre> <p>Now I want to use the optparse module. optparse generates the "Options" sections and a "usage" explaining the command line syntax:</p> <pre><code>from optparse import OptionParser if __name__ == "__main__": parser = OptionParser() (options, args) = parser.parse_args() </code></pre> <p>So calling the script with the "-h" flag prints:</p> <pre> Usage: script.py [options] Options: -h, --help show this help message and exit </pre> <p>This can be modified as follows:</p> <pre><code>parser = OptionParser(usage="Usage: %prog [options] [args]", description="some text explaining the usage...") </code></pre> <p>which results in</p> <pre> Usage: script.py [options] [args] some text explaining the usage... Options: -h, --help show this help message and exit </pre> <p>But how can I use the docstring here? Passing the docstring as the usage message has two problems.</p> <ol> <li>optparse appends "Usage: " to the docstring if it does not start with "Usage: "</li> <li>The placeholder '%prog' must be used in the docstring</li> </ol> <p><strong>Result</strong></p> <p>According to the answers it seems that there is no way to reuse the docstring intended by the optparse module. So the remaining option is to parse the docstring manually and construct the OptionParser. (So I'll accept S.Loot's answer)</p> <p>The "Usage: " part is introduced by the IndentedHelpFormatter which can be replaced with the formatter parameter in OptionParser.__init__().</p>
5
2009-08-11T12:14:49Z
1,260,007
<p>Choice 1: Copy and paste. Not DRY, but workable.</p> <p>Choice 2: Parse your own docstring to strip out the description paragraph. It's always paragraph two, so you can split on '\n\n'.</p> <pre><code>usage, description= __doc__.split('\n\n')[:2] </code></pre> <p>Since <code>optparse</code> generates usage, you may not want to supply the usage sentence to it. Your version of the usage my be wrong. If you insist on providing a usage string to <code>optparse</code>, I'll leave it as an exercise for the reader to work out how to remove <code>"Usage: "</code> from the front of the <code>usage</code> string produced above.</p>
4
2009-08-11T12:21:22Z
[ "python", "optparse" ]
How to comply to PEP 257 docstrings when using Python's optparse module?
1,259,982
<p>According to <a href="http://www.python.org/dev/peps/pep-0257/#multi-line-docstrings" rel="nofollow">PEP 257</a> the docstring of command line script should be its usage message.</p> <blockquote> <p>The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.</p> </blockquote> <p>So my docstring would look something like this:</p> <pre> &lt;tool name&gt; &lt;copyright info&gt; Usage: &lt;prog name&gt; [options] [args] some text explaining the usage... Options: -h, --help show this help message and exit ... </pre> <p>Now I want to use the optparse module. optparse generates the "Options" sections and a "usage" explaining the command line syntax:</p> <pre><code>from optparse import OptionParser if __name__ == "__main__": parser = OptionParser() (options, args) = parser.parse_args() </code></pre> <p>So calling the script with the "-h" flag prints:</p> <pre> Usage: script.py [options] Options: -h, --help show this help message and exit </pre> <p>This can be modified as follows:</p> <pre><code>parser = OptionParser(usage="Usage: %prog [options] [args]", description="some text explaining the usage...") </code></pre> <p>which results in</p> <pre> Usage: script.py [options] [args] some text explaining the usage... Options: -h, --help show this help message and exit </pre> <p>But how can I use the docstring here? Passing the docstring as the usage message has two problems.</p> <ol> <li>optparse appends "Usage: " to the docstring if it does not start with "Usage: "</li> <li>The placeholder '%prog' must be used in the docstring</li> </ol> <p><strong>Result</strong></p> <p>According to the answers it seems that there is no way to reuse the docstring intended by the optparse module. So the remaining option is to parse the docstring manually and construct the OptionParser. (So I'll accept S.Loot's answer)</p> <p>The "Usage: " part is introduced by the IndentedHelpFormatter which can be replaced with the formatter parameter in OptionParser.__init__().</p>
5
2009-08-11T12:14:49Z
1,261,663
<p>I think we have to be reasonable about this PEP's advice -- I would think it's fine to leave the module with <code>__doc__</code> being the short description that summarizes long usage. But if you're perfectionist:</p> <pre><code>'''&lt;tool name&gt; The full description and usage can be generated by optparse module. Description: ... ''' ... # Generate usage and options using optparse. usage, options = ... # Modify the docstring on the fly. docstring = __doc__.split('\n\n') docstring[1:2] = [__license__, usage, options] __doc__ = '\n\n'.join(docstring) </code></pre>
1
2009-08-11T16:57:39Z
[ "python", "optparse" ]
How to comply to PEP 257 docstrings when using Python's optparse module?
1,259,982
<p>According to <a href="http://www.python.org/dev/peps/pep-0257/#multi-line-docstrings" rel="nofollow">PEP 257</a> the docstring of command line script should be its usage message.</p> <blockquote> <p>The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.</p> </blockquote> <p>So my docstring would look something like this:</p> <pre> &lt;tool name&gt; &lt;copyright info&gt; Usage: &lt;prog name&gt; [options] [args] some text explaining the usage... Options: -h, --help show this help message and exit ... </pre> <p>Now I want to use the optparse module. optparse generates the "Options" sections and a "usage" explaining the command line syntax:</p> <pre><code>from optparse import OptionParser if __name__ == "__main__": parser = OptionParser() (options, args) = parser.parse_args() </code></pre> <p>So calling the script with the "-h" flag prints:</p> <pre> Usage: script.py [options] Options: -h, --help show this help message and exit </pre> <p>This can be modified as follows:</p> <pre><code>parser = OptionParser(usage="Usage: %prog [options] [args]", description="some text explaining the usage...") </code></pre> <p>which results in</p> <pre> Usage: script.py [options] [args] some text explaining the usage... Options: -h, --help show this help message and exit </pre> <p>But how can I use the docstring here? Passing the docstring as the usage message has two problems.</p> <ol> <li>optparse appends "Usage: " to the docstring if it does not start with "Usage: "</li> <li>The placeholder '%prog' must be used in the docstring</li> </ol> <p><strong>Result</strong></p> <p>According to the answers it seems that there is no way to reuse the docstring intended by the optparse module. So the remaining option is to parse the docstring manually and construct the OptionParser. (So I'll accept S.Loot's answer)</p> <p>The "Usage: " part is introduced by the IndentedHelpFormatter which can be replaced with the formatter parameter in OptionParser.__init__().</p>
5
2009-08-11T12:14:49Z
10,065,543
<p>I wrote a module <code>docopt</code> to do exactly what you want – write usage-message in docstring and stay DRY. It also allows to avoid writing tedious <code>OptionParser</code> code at all, since <code>docopt</code> is generating parser based on the usage-message. </p> <p>Check it out: <a href="http://github.com/docopt/docopt" rel="nofollow">http://github.com/docopt/docopt</a></p> <pre><code>"""Naval Fate. Usage: naval_fate.py ship new &lt;name&gt;... naval_fate.py ship [&lt;name&gt;] move &lt;x&gt; &lt;y&gt; [--speed=&lt;kn&gt;] naval_fate.py ship shoot &lt;x&gt; &lt;y&gt; naval_fate.py mine (set|remove) &lt;x&gt; &lt;y&gt; [--moored|--drifting] naval_fate.py -h | --help naval_fate.py --version Options: -h --help Show this screen. --version Show version. --speed=&lt;kn&gt; Speed in knots [default: 10]. --moored Moored (anchored) mine. --drifting Drifting mine. """ from docopt import docopt if __name__ == '__main__': arguments = docopt(__doc__, version='Naval Fate 2.0') print(arguments) </code></pre>
6
2012-04-08T19:02:58Z
[ "python", "optparse" ]
Interrupt Python program deadlocked in a DLL
1,260,259
<p>How can I ensure a python program can be interrupted via Ctrl-C, or a similar mechanism, when it is deadlocked in code within a DLL?</p>
2
2009-08-11T13:12:48Z
1,260,378
<p>Not sure if this is exactly what you are asking, but there are issues when trying to interrupt (via Ctrl-C) a multi-threaded python process. Here is a video of a talk about the python Global Interpreter Lock that also discusses that issue:</p> <p><a href="http://blip.tv/file/2232410" rel="nofollow">Mindblowing Python GIL</a></p>
1
2009-08-11T13:29:39Z
[ "python", "dll" ]
Interrupt Python program deadlocked in a DLL
1,260,259
<p>How can I ensure a python program can be interrupted via Ctrl-C, or a similar mechanism, when it is deadlocked in code within a DLL?</p>
2
2009-08-11T13:12:48Z
1,261,643
<p>You might want to take a look at <a href="http://mail.python.org/pipermail/python-list/2005-October/346842.html" rel="nofollow">this mailing list</a> for a couple other suggestions, but there aren't any conclusive answers.</p> <p>I've encountered the issue several times, and I can at least confirm that this happens when using FFI in Haskell. I could have sworn that I once saw something in Haskell's FFI documentation mentioning that DLLs would not return from a ctrl-c signal, but I'm not having any luck finding that document.</p> <p>You can try <a href="http://msdn.microsoft.com/en-us/library/ms682541%28VS.85%29.aspx" rel="nofollow">using ctrl-break</a>, but that's not working to break out of a DLL in Haskell and I'm doubting it will work in Python either. <hr/> <strong>Update</strong>: ctrl-break does work for me in Python when ctrl-c does not, during a call to a DLL function in an infinite loop.</p>
0
2009-08-11T16:54:44Z
[ "python", "dll" ]
Locking a custom dictionary
1,260,649
<p>Good day pythonians,</p> <p>I want to make a custom dictionary with two main features:</p> <ol> <li>All keys are declared on creation</li> <li>It is impossible to add new keys or modify current ones (values are still modifiable)</li> </ol> <p>Right now code is this:</p> <pre><code>class pick(dict): """This will make delicious toffee when finished""" def __init__(self, *args): dict.__init__(self) for arg in args: self[arg] = None </code></pre> <p>Any help is much appreciated.</p> <p><strong>upd:</strong></p> <p>While solution is what I was looking for there is one problem:</p> <p>dictionary calls the <code>__setitem__</code> to add the items on the initialization and not finding the keys it raises the error.</p> <pre><code>cupboard = pick('milk') #raises error </code></pre> <p><strong>upd1:</strong></p> <p>all solved, thank you very much.</p>
2
2009-08-11T14:16:08Z
1,260,683
<p>Override the <code>__setitem__</code> method with your desired behavior, call <code>dict.__setitem__(self, key, value</code>) to modify the base dictionary without going through your base logic.</p> <pre><code>class ImmutableDict(dict): def __setitem__(self, key, value): if key not in self: raise KeyError("Immutable dict") dict.__setitem__(self, key, value) d = ImmutableDict(foo=1, bar=2) d['foo'] = 3 print(d) d['baz'] = 4 # Raises error </code></pre> <p>You'll also need to override <code>dict.update()</code> and <code>setdefault()</code> to avoid addition of keys. And possibly <code>dict.__delitem__()</code>, <code>dict.clear()</code>, <code>dict.pop()</code> and <code>dict.popitem()</code> to avoid removal of keys.</p>
12
2009-08-11T14:21:13Z
[ "python", "dictionary", "locking" ]
Locking a custom dictionary
1,260,649
<p>Good day pythonians,</p> <p>I want to make a custom dictionary with two main features:</p> <ol> <li>All keys are declared on creation</li> <li>It is impossible to add new keys or modify current ones (values are still modifiable)</li> </ol> <p>Right now code is this:</p> <pre><code>class pick(dict): """This will make delicious toffee when finished""" def __init__(self, *args): dict.__init__(self) for arg in args: self[arg] = None </code></pre> <p>Any help is much appreciated.</p> <p><strong>upd:</strong></p> <p>While solution is what I was looking for there is one problem:</p> <p>dictionary calls the <code>__setitem__</code> to add the items on the initialization and not finding the keys it raises the error.</p> <pre><code>cupboard = pick('milk') #raises error </code></pre> <p><strong>upd1:</strong></p> <p>all solved, thank you very much.</p>
2
2009-08-11T14:16:08Z
1,260,688
<p>Something like</p> <pre><code>class UniqueDict(dict): def __init__(self, *args, **kwargs): dict.__init__(self, *args, **kwargs) def __setitem__(self, name, value): if name not in self: raise KeyError("%s not present") dict.__setitem__(self, name, value) </code></pre>
2
2009-08-11T14:21:31Z
[ "python", "dictionary", "locking" ]
Locking a custom dictionary
1,260,649
<p>Good day pythonians,</p> <p>I want to make a custom dictionary with two main features:</p> <ol> <li>All keys are declared on creation</li> <li>It is impossible to add new keys or modify current ones (values are still modifiable)</li> </ol> <p>Right now code is this:</p> <pre><code>class pick(dict): """This will make delicious toffee when finished""" def __init__(self, *args): dict.__init__(self) for arg in args: self[arg] = None </code></pre> <p>Any help is much appreciated.</p> <p><strong>upd:</strong></p> <p>While solution is what I was looking for there is one problem:</p> <p>dictionary calls the <code>__setitem__</code> to add the items on the initialization and not finding the keys it raises the error.</p> <pre><code>cupboard = pick('milk') #raises error </code></pre> <p><strong>upd1:</strong></p> <p>all solved, thank you very much.</p>
2
2009-08-11T14:16:08Z
1,260,695
<p>I suggest you to use delegation, rather than inheritance. If you inherit, all the previous methods of the dict will be inherited, but they could behave as you don't expect, thus ruining the assumptions you have on the class, and doing it silently.</p> <p>If you do delegation, you can fully control the methods you provide, and if you try to use your dict in a context requiring a method you have not implemented, you will get an exception, failing fast to the problem.</p>
2
2009-08-11T14:22:31Z
[ "python", "dictionary", "locking" ]
Python: import a file from a subdirectory
1,260,792
<p>I have a file called <code>tester.py</code>, located on <code>/project</code>.</p> <p><code>/project</code> has a subdirectory called <code>lib</code>, with a file called <code>BoxTime.py</code>:</p> <pre><code>/project/tester.py /project/lib/BoxTime.py </code></pre> <p>I want to import <code>BoxTime</code> from <code>tester</code>. I have tried this:</p> <pre><code>import lib.BoxTime </code></pre> <p>Which resulted:</p> <pre><code>Traceback (most recent call last): File "./tester.py", line 3, in &lt;module&gt; import lib.BoxTime ImportError: No module named lib.BoxTime </code></pre> <p>Any ideas how to import <code>BoxTime</code> from the subdirectory?</p> <p><strong>EDIT</strong></p> <p>The <code>__init__.py</code> was the problem, but don't forget to refer to <code>BoxTime</code> as <code>lib.BoxTime</code>, or use:</p> <pre><code>import lib.BoxTime as BT ... BT.bt_function() </code></pre>
180
2009-08-11T14:39:05Z
1,260,813
<p>Take a look at the Packages documentation (Section 6.4) here: <a href="http://docs.python.org/tutorial/modules.html">http://docs.python.org/tutorial/modules.html</a></p> <p>In short, you need to put a blank file named </p> <pre><code>__init__.py </code></pre> <p>in the "lib" directory.</p>
232
2009-08-11T14:42:10Z
[ "python", "module", "subdirectory", "python-import" ]
Python: import a file from a subdirectory
1,260,792
<p>I have a file called <code>tester.py</code>, located on <code>/project</code>.</p> <p><code>/project</code> has a subdirectory called <code>lib</code>, with a file called <code>BoxTime.py</code>:</p> <pre><code>/project/tester.py /project/lib/BoxTime.py </code></pre> <p>I want to import <code>BoxTime</code> from <code>tester</code>. I have tried this:</p> <pre><code>import lib.BoxTime </code></pre> <p>Which resulted:</p> <pre><code>Traceback (most recent call last): File "./tester.py", line 3, in &lt;module&gt; import lib.BoxTime ImportError: No module named lib.BoxTime </code></pre> <p>Any ideas how to import <code>BoxTime</code> from the subdirectory?</p> <p><strong>EDIT</strong></p> <p>The <code>__init__.py</code> was the problem, but don't forget to refer to <code>BoxTime</code> as <code>lib.BoxTime</code>, or use:</p> <pre><code>import lib.BoxTime as BT ... BT.bt_function() </code></pre>
180
2009-08-11T14:39:05Z
1,260,814
<p>Try <code>import .lib.BoxTime</code>. For more information read about relative import in <a href="http://dinsdale.python.org/dev/peps/pep-0328/#guido-s-decision">PEP 328</a>.</p>
8
2009-08-11T14:42:13Z
[ "python", "module", "subdirectory", "python-import" ]
Python: import a file from a subdirectory
1,260,792
<p>I have a file called <code>tester.py</code>, located on <code>/project</code>.</p> <p><code>/project</code> has a subdirectory called <code>lib</code>, with a file called <code>BoxTime.py</code>:</p> <pre><code>/project/tester.py /project/lib/BoxTime.py </code></pre> <p>I want to import <code>BoxTime</code> from <code>tester</code>. I have tried this:</p> <pre><code>import lib.BoxTime </code></pre> <p>Which resulted:</p> <pre><code>Traceback (most recent call last): File "./tester.py", line 3, in &lt;module&gt; import lib.BoxTime ImportError: No module named lib.BoxTime </code></pre> <p>Any ideas how to import <code>BoxTime</code> from the subdirectory?</p> <p><strong>EDIT</strong></p> <p>The <code>__init__.py</code> was the problem, but don't forget to refer to <code>BoxTime</code> as <code>lib.BoxTime</code>, or use:</p> <pre><code>import lib.BoxTime as BT ... BT.bt_function() </code></pre>
180
2009-08-11T14:39:05Z
1,260,832
<p>Does your lib directory contain a <code>__init__.py</code> file?</p> <p>Python uses <code>__init__.py</code> to determine if a directory is a module.</p>
15
2009-08-11T14:44:44Z
[ "python", "module", "subdirectory", "python-import" ]
Python: import a file from a subdirectory
1,260,792
<p>I have a file called <code>tester.py</code>, located on <code>/project</code>.</p> <p><code>/project</code> has a subdirectory called <code>lib</code>, with a file called <code>BoxTime.py</code>:</p> <pre><code>/project/tester.py /project/lib/BoxTime.py </code></pre> <p>I want to import <code>BoxTime</code> from <code>tester</code>. I have tried this:</p> <pre><code>import lib.BoxTime </code></pre> <p>Which resulted:</p> <pre><code>Traceback (most recent call last): File "./tester.py", line 3, in &lt;module&gt; import lib.BoxTime ImportError: No module named lib.BoxTime </code></pre> <p>Any ideas how to import <code>BoxTime</code> from the subdirectory?</p> <p><strong>EDIT</strong></p> <p>The <code>__init__.py</code> was the problem, but don't forget to refer to <code>BoxTime</code> as <code>lib.BoxTime</code>, or use:</p> <pre><code>import lib.BoxTime as BT ... BT.bt_function() </code></pre>
180
2009-08-11T14:39:05Z
1,260,846
<ul> <li>Create a subdirectory named lib.</li> <li>Create an empty file named lib\__init__.py.</li> <li><p>In lib\BoxTime.py, write a function foo() like this:</p> <pre><code>def foo(): print "foo!" </code></pre></li> <li><p>In your client code in the directory above lib, write:</p> <pre><code>from lib import BoxTime BoxTime.foo() </code></pre></li> <li><p>Run your client code. You will get:</p> <pre><code>foo! </code></pre></li> </ul> <hr> <p>Much later -- in linux, it would look like this:</p> <pre><code>% cd ~/tmp % mkdir lib % touch lib/__init__.py % cat &gt; lib/BoxTime.py &lt;&lt; EOF heredoc&gt; def foo(): heredoc&gt; print "foo!" heredoc&gt; EOF % tree lib lib ├── BoxTime.py └── __init__.py 0 directories, 2 files % python Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from lib import BoxTime &gt;&gt;&gt; BoxTime.foo() foo! </code></pre>
63
2009-08-11T14:46:34Z
[ "python", "module", "subdirectory", "python-import" ]
Python: import a file from a subdirectory
1,260,792
<p>I have a file called <code>tester.py</code>, located on <code>/project</code>.</p> <p><code>/project</code> has a subdirectory called <code>lib</code>, with a file called <code>BoxTime.py</code>:</p> <pre><code>/project/tester.py /project/lib/BoxTime.py </code></pre> <p>I want to import <code>BoxTime</code> from <code>tester</code>. I have tried this:</p> <pre><code>import lib.BoxTime </code></pre> <p>Which resulted:</p> <pre><code>Traceback (most recent call last): File "./tester.py", line 3, in &lt;module&gt; import lib.BoxTime ImportError: No module named lib.BoxTime </code></pre> <p>Any ideas how to import <code>BoxTime</code> from the subdirectory?</p> <p><strong>EDIT</strong></p> <p>The <code>__init__.py</code> was the problem, but don't forget to refer to <code>BoxTime</code> as <code>lib.BoxTime</code>, or use:</p> <pre><code>import lib.BoxTime as BT ... BT.bt_function() </code></pre>
180
2009-08-11T14:39:05Z
14,999,050
<p>You can try inserting it in <code>sys.path</code>:</p> <pre><code>sys.path.insert(0, './lib') import BoxTime </code></pre>
19
2013-02-21T09:47:42Z
[ "python", "module", "subdirectory", "python-import" ]
Python: import a file from a subdirectory
1,260,792
<p>I have a file called <code>tester.py</code>, located on <code>/project</code>.</p> <p><code>/project</code> has a subdirectory called <code>lib</code>, with a file called <code>BoxTime.py</code>:</p> <pre><code>/project/tester.py /project/lib/BoxTime.py </code></pre> <p>I want to import <code>BoxTime</code> from <code>tester</code>. I have tried this:</p> <pre><code>import lib.BoxTime </code></pre> <p>Which resulted:</p> <pre><code>Traceback (most recent call last): File "./tester.py", line 3, in &lt;module&gt; import lib.BoxTime ImportError: No module named lib.BoxTime </code></pre> <p>Any ideas how to import <code>BoxTime</code> from the subdirectory?</p> <p><strong>EDIT</strong></p> <p>The <code>__init__.py</code> was the problem, but don't forget to refer to <code>BoxTime</code> as <code>lib.BoxTime</code>, or use:</p> <pre><code>import lib.BoxTime as BT ... BT.bt_function() </code></pre>
180
2009-08-11T14:39:05Z
32,831,635
<p>try this:</p> <p><code>from lib import BoxTime</code></p>
0
2015-09-28T20:53:28Z
[ "python", "module", "subdirectory", "python-import" ]
Python: import a file from a subdirectory
1,260,792
<p>I have a file called <code>tester.py</code>, located on <code>/project</code>.</p> <p><code>/project</code> has a subdirectory called <code>lib</code>, with a file called <code>BoxTime.py</code>:</p> <pre><code>/project/tester.py /project/lib/BoxTime.py </code></pre> <p>I want to import <code>BoxTime</code> from <code>tester</code>. I have tried this:</p> <pre><code>import lib.BoxTime </code></pre> <p>Which resulted:</p> <pre><code>Traceback (most recent call last): File "./tester.py", line 3, in &lt;module&gt; import lib.BoxTime ImportError: No module named lib.BoxTime </code></pre> <p>Any ideas how to import <code>BoxTime</code> from the subdirectory?</p> <p><strong>EDIT</strong></p> <p>The <code>__init__.py</code> was the problem, but don't forget to refer to <code>BoxTime</code> as <code>lib.BoxTime</code>, or use:</p> <pre><code>import lib.BoxTime as BT ... BT.bt_function() </code></pre>
180
2009-08-11T14:39:05Z
35,272,100
<p>I do this which basically covers all cases (make sure you have the blank <code>__init__.py</code> in relative/path/to/your/lib/folder):</p> <pre><code>import sys, os sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/relative/path/to/your/lib/folder") import someFileNameWhichIsInTheFolder ... somefile.foo() </code></pre> <p><br> <strong>Example:</strong> <br> You have in your project folder: <br></p> <pre><code>/root/myproject/app.py </code></pre> <p>You have in another project folder: <br></p> <pre><code>/root/anotherproject/utils.py /root/anotherproject/__init__.py </code></pre> <p>You want to use /root/otherproject/utils.py and call foo function which is in it.</p> <p>So you write in app.py:</p> <pre><code>import sys, os sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../anotherproject") import utils utils.foo() </code></pre>
2
2016-02-08T14:32:09Z
[ "python", "module", "subdirectory", "python-import" ]
Which credentials should I put in for Google App Engine BulkLoader at development server?
1,260,835
<p>I would like to ask which kind of credentials do I need to put on for importing data using the Google App Engine BulkLoader class</p> <pre><code>appcfg.py upload_data --config_file=models.py --filename=listcountries.csv --kind=CMSCountry --url=http://localhost:8178/remote_api vit/ </code></pre> <p>And then it asks me for credentials:</p> <blockquote> <p>Please enter login credentials for localhost</p> </blockquote> <p>Here is an extraction of the content of the models.py, I use this <a href="http://www.andrewpatton.com/countrylist.html">listcountries.csv</a> file</p> <pre><code>class CMSCountry(db.Model): sortorder = db.StringProperty() name = db.StringProperty(required=True) formalname = db.StringProperty() type = db.StringProperty() subtype = db.StringProperty() sovereignt = db.StringProperty() capital = db.StringProperty() currencycode = db.StringProperty() currencyname = db.StringProperty() telephonecode = db.StringProperty() lettercode = db.StringProperty() lettercode2 = db.StringProperty() number = db.StringProperty() countrycode = db.StringProperty() class CMSCountryLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'CMSCountry', [('sortorder', str), ('name', str), ('formalname', str), ('type', str), ('subtype', str), ('sovereignt', str), ('capital', str), ('currencycode', str), ('currencyname', str), ('telephonecode', str), ('lettercode', str), ('lettercode2', str), ('number', str), ('countrycode', str) ]) loaders = [CMSCountryLoader] </code></pre> <p>Every tries to enter the email and password result in "Authentication Failed", so I could not import the data to the development server. </p> <p>I don't think that I have any problem with my files neither my models because I have successfully uploaded the data to the appspot.com application.<br /> So what should I put in for localhost credentials?<br /> I also tried to use <strong>Eclipse with Pydev</strong> but I still got the same message :(<br /> Here is the output:</p> <pre><code>Uploading data records. [INFO ] Logging to bulkloader-log-20090820.121659 [INFO ] Opening database: bulkloader-progress-20090820.121659.sql3 [INFO ] [Thread-1] WorkerThread: started [INFO ] [Thread-2] WorkerThread: started [INFO ] [Thread-3] WorkerThread: started [INFO ] [Thread-4] WorkerThread: started [INFO ] [Thread-5] WorkerThread: started [INFO ] [Thread-6] WorkerThread: started [INFO ] [Thread-7] WorkerThread: started [INFO ] [Thread-8] WorkerThread: started [INFO ] [Thread-9] WorkerThread: started [INFO ] [Thread-10] WorkerThread: started Password for foobar@nowhere.com: [DEBUG ] Configuring remote_api. url_path = /remote_api, servername = localhost:8178 [DEBUG ] Bulkloader using app_id: abc [INFO ] Connecting to /remote_api [ERROR ] Exception during authentication Traceback (most recent call last): File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 2802, in Run request_manager.Authenticate() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 1126, in Authenticate remote_api_stub.MaybeInvokeAuthentication() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\remote_api\remote_api_stub.py", line 488, in MaybeInvokeAuthentication datastore_stub._server.Send(datastore_stub._path, payload=None) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\appengine_rpc.py", line 344, in Send f = self.opener.open(req) File "C:\Python25\lib\urllib2.py", line 381, in open response = self._open(req, data) File "C:\Python25\lib\urllib2.py", line 399, in _open '_open', req) File "C:\Python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 1107, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python25\lib\urllib2.py", line 1082, in do_open raise URLError(err) URLError: &lt;urlopen error (10061, 'Connection refused')&gt; [INFO ] Authentication Failed </code></pre> <p>Thank you! </p>
5
2009-08-11T14:45:05Z
1,262,651
<p>I recommend you follow the advice given <a href="http://blog.suinova.com/2009/03/tutorial-on-bulkloading-data-onto-app.html" rel="nofollow">here</a>, and I quote:</p> <blockquote> <p>add this to app.yaml file:</p> <pre><code>-- url: /loadusers script: myloader.py login: admin </code></pre> <p>Note that if you run it <strong>on local development machine, comment off the last line login:admin so that you don't need a credential to run the bulkloader</strong>.</p> </blockquote> <p>(my emphasis).</p>
4
2009-08-11T20:12:34Z
[ "python", "google-app-engine" ]
Which credentials should I put in for Google App Engine BulkLoader at development server?
1,260,835
<p>I would like to ask which kind of credentials do I need to put on for importing data using the Google App Engine BulkLoader class</p> <pre><code>appcfg.py upload_data --config_file=models.py --filename=listcountries.csv --kind=CMSCountry --url=http://localhost:8178/remote_api vit/ </code></pre> <p>And then it asks me for credentials:</p> <blockquote> <p>Please enter login credentials for localhost</p> </blockquote> <p>Here is an extraction of the content of the models.py, I use this <a href="http://www.andrewpatton.com/countrylist.html">listcountries.csv</a> file</p> <pre><code>class CMSCountry(db.Model): sortorder = db.StringProperty() name = db.StringProperty(required=True) formalname = db.StringProperty() type = db.StringProperty() subtype = db.StringProperty() sovereignt = db.StringProperty() capital = db.StringProperty() currencycode = db.StringProperty() currencyname = db.StringProperty() telephonecode = db.StringProperty() lettercode = db.StringProperty() lettercode2 = db.StringProperty() number = db.StringProperty() countrycode = db.StringProperty() class CMSCountryLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'CMSCountry', [('sortorder', str), ('name', str), ('formalname', str), ('type', str), ('subtype', str), ('sovereignt', str), ('capital', str), ('currencycode', str), ('currencyname', str), ('telephonecode', str), ('lettercode', str), ('lettercode2', str), ('number', str), ('countrycode', str) ]) loaders = [CMSCountryLoader] </code></pre> <p>Every tries to enter the email and password result in "Authentication Failed", so I could not import the data to the development server. </p> <p>I don't think that I have any problem with my files neither my models because I have successfully uploaded the data to the appspot.com application.<br /> So what should I put in for localhost credentials?<br /> I also tried to use <strong>Eclipse with Pydev</strong> but I still got the same message :(<br /> Here is the output:</p> <pre><code>Uploading data records. [INFO ] Logging to bulkloader-log-20090820.121659 [INFO ] Opening database: bulkloader-progress-20090820.121659.sql3 [INFO ] [Thread-1] WorkerThread: started [INFO ] [Thread-2] WorkerThread: started [INFO ] [Thread-3] WorkerThread: started [INFO ] [Thread-4] WorkerThread: started [INFO ] [Thread-5] WorkerThread: started [INFO ] [Thread-6] WorkerThread: started [INFO ] [Thread-7] WorkerThread: started [INFO ] [Thread-8] WorkerThread: started [INFO ] [Thread-9] WorkerThread: started [INFO ] [Thread-10] WorkerThread: started Password for foobar@nowhere.com: [DEBUG ] Configuring remote_api. url_path = /remote_api, servername = localhost:8178 [DEBUG ] Bulkloader using app_id: abc [INFO ] Connecting to /remote_api [ERROR ] Exception during authentication Traceback (most recent call last): File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 2802, in Run request_manager.Authenticate() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 1126, in Authenticate remote_api_stub.MaybeInvokeAuthentication() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\remote_api\remote_api_stub.py", line 488, in MaybeInvokeAuthentication datastore_stub._server.Send(datastore_stub._path, payload=None) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\appengine_rpc.py", line 344, in Send f = self.opener.open(req) File "C:\Python25\lib\urllib2.py", line 381, in open response = self._open(req, data) File "C:\Python25\lib\urllib2.py", line 399, in _open '_open', req) File "C:\Python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 1107, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python25\lib\urllib2.py", line 1082, in do_open raise URLError(err) URLError: &lt;urlopen error (10061, 'Connection refused')&gt; [INFO ] Authentication Failed </code></pre> <p>Thank you! </p>
5
2009-08-11T14:45:05Z
1,741,088
<p>Next worked for me: </p> <ul> <li><p>removing the line</p> <pre><code>login:admin </code></pre> <p>from app.yaml</p></li> <li><p>Updating app cofig: </p> <pre><code>appcfg.py update [app-id] </code></pre></li> <li><p>(Re)starting local server: </p> <pre><code>appserver [app-id] </code></pre></li> <li><p>Upload data: </p> <pre><code>appcfg.py upload_data --config_file=album_loader.py --filename album_data.csv --kind Album --url=http://localhost:8080/remote_api ../[app-id] </code></pre> <p>Ask for mail and password type anything </p></li> </ul>
0
2009-11-16T09:37:49Z
[ "python", "google-app-engine" ]
Which credentials should I put in for Google App Engine BulkLoader at development server?
1,260,835
<p>I would like to ask which kind of credentials do I need to put on for importing data using the Google App Engine BulkLoader class</p> <pre><code>appcfg.py upload_data --config_file=models.py --filename=listcountries.csv --kind=CMSCountry --url=http://localhost:8178/remote_api vit/ </code></pre> <p>And then it asks me for credentials:</p> <blockquote> <p>Please enter login credentials for localhost</p> </blockquote> <p>Here is an extraction of the content of the models.py, I use this <a href="http://www.andrewpatton.com/countrylist.html">listcountries.csv</a> file</p> <pre><code>class CMSCountry(db.Model): sortorder = db.StringProperty() name = db.StringProperty(required=True) formalname = db.StringProperty() type = db.StringProperty() subtype = db.StringProperty() sovereignt = db.StringProperty() capital = db.StringProperty() currencycode = db.StringProperty() currencyname = db.StringProperty() telephonecode = db.StringProperty() lettercode = db.StringProperty() lettercode2 = db.StringProperty() number = db.StringProperty() countrycode = db.StringProperty() class CMSCountryLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'CMSCountry', [('sortorder', str), ('name', str), ('formalname', str), ('type', str), ('subtype', str), ('sovereignt', str), ('capital', str), ('currencycode', str), ('currencyname', str), ('telephonecode', str), ('lettercode', str), ('lettercode2', str), ('number', str), ('countrycode', str) ]) loaders = [CMSCountryLoader] </code></pre> <p>Every tries to enter the email and password result in "Authentication Failed", so I could not import the data to the development server. </p> <p>I don't think that I have any problem with my files neither my models because I have successfully uploaded the data to the appspot.com application.<br /> So what should I put in for localhost credentials?<br /> I also tried to use <strong>Eclipse with Pydev</strong> but I still got the same message :(<br /> Here is the output:</p> <pre><code>Uploading data records. [INFO ] Logging to bulkloader-log-20090820.121659 [INFO ] Opening database: bulkloader-progress-20090820.121659.sql3 [INFO ] [Thread-1] WorkerThread: started [INFO ] [Thread-2] WorkerThread: started [INFO ] [Thread-3] WorkerThread: started [INFO ] [Thread-4] WorkerThread: started [INFO ] [Thread-5] WorkerThread: started [INFO ] [Thread-6] WorkerThread: started [INFO ] [Thread-7] WorkerThread: started [INFO ] [Thread-8] WorkerThread: started [INFO ] [Thread-9] WorkerThread: started [INFO ] [Thread-10] WorkerThread: started Password for foobar@nowhere.com: [DEBUG ] Configuring remote_api. url_path = /remote_api, servername = localhost:8178 [DEBUG ] Bulkloader using app_id: abc [INFO ] Connecting to /remote_api [ERROR ] Exception during authentication Traceback (most recent call last): File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 2802, in Run request_manager.Authenticate() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 1126, in Authenticate remote_api_stub.MaybeInvokeAuthentication() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\remote_api\remote_api_stub.py", line 488, in MaybeInvokeAuthentication datastore_stub._server.Send(datastore_stub._path, payload=None) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\appengine_rpc.py", line 344, in Send f = self.opener.open(req) File "C:\Python25\lib\urllib2.py", line 381, in open response = self._open(req, data) File "C:\Python25\lib\urllib2.py", line 399, in _open '_open', req) File "C:\Python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 1107, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python25\lib\urllib2.py", line 1082, in do_open raise URLError(err) URLError: &lt;urlopen error (10061, 'Connection refused')&gt; [INFO ] Authentication Failed </code></pre> <p>Thank you! </p>
5
2009-08-11T14:45:05Z
1,936,912
<p>Edit: Look at my <a href="#2195685" rel="nofollow">new solution</a></p> <p>This problem is still present. I have opened <a href="http://code.google.com/p/googleappengine/issues/detail?id=2440" rel="nofollow">a ticket</a> to ask if the authentication could be bypassed on the local dev server. Please vote for this issue so that we can have it resolved [quickly].</p> <p>I have been able to upload data to the dev server by:</p> <ul> <li>leaving the "login:admin" line in app.yaml</li> <li>adding "--email=foobar@nowhere.com" to your command</li> <li>pressing Enter when prompted for a password (nothing required)</li> </ul> <p>Leaving the "login:admin" line is a good thing, as you will not upload your app on the production servers without this line, which could expose you to someone adding data to your datastore...</p> <blockquote> <p>Blockquote</p> </blockquote>
3
2009-12-20T20:27:27Z
[ "python", "google-app-engine" ]
Which credentials should I put in for Google App Engine BulkLoader at development server?
1,260,835
<p>I would like to ask which kind of credentials do I need to put on for importing data using the Google App Engine BulkLoader class</p> <pre><code>appcfg.py upload_data --config_file=models.py --filename=listcountries.csv --kind=CMSCountry --url=http://localhost:8178/remote_api vit/ </code></pre> <p>And then it asks me for credentials:</p> <blockquote> <p>Please enter login credentials for localhost</p> </blockquote> <p>Here is an extraction of the content of the models.py, I use this <a href="http://www.andrewpatton.com/countrylist.html">listcountries.csv</a> file</p> <pre><code>class CMSCountry(db.Model): sortorder = db.StringProperty() name = db.StringProperty(required=True) formalname = db.StringProperty() type = db.StringProperty() subtype = db.StringProperty() sovereignt = db.StringProperty() capital = db.StringProperty() currencycode = db.StringProperty() currencyname = db.StringProperty() telephonecode = db.StringProperty() lettercode = db.StringProperty() lettercode2 = db.StringProperty() number = db.StringProperty() countrycode = db.StringProperty() class CMSCountryLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'CMSCountry', [('sortorder', str), ('name', str), ('formalname', str), ('type', str), ('subtype', str), ('sovereignt', str), ('capital', str), ('currencycode', str), ('currencyname', str), ('telephonecode', str), ('lettercode', str), ('lettercode2', str), ('number', str), ('countrycode', str) ]) loaders = [CMSCountryLoader] </code></pre> <p>Every tries to enter the email and password result in "Authentication Failed", so I could not import the data to the development server. </p> <p>I don't think that I have any problem with my files neither my models because I have successfully uploaded the data to the appspot.com application.<br /> So what should I put in for localhost credentials?<br /> I also tried to use <strong>Eclipse with Pydev</strong> but I still got the same message :(<br /> Here is the output:</p> <pre><code>Uploading data records. [INFO ] Logging to bulkloader-log-20090820.121659 [INFO ] Opening database: bulkloader-progress-20090820.121659.sql3 [INFO ] [Thread-1] WorkerThread: started [INFO ] [Thread-2] WorkerThread: started [INFO ] [Thread-3] WorkerThread: started [INFO ] [Thread-4] WorkerThread: started [INFO ] [Thread-5] WorkerThread: started [INFO ] [Thread-6] WorkerThread: started [INFO ] [Thread-7] WorkerThread: started [INFO ] [Thread-8] WorkerThread: started [INFO ] [Thread-9] WorkerThread: started [INFO ] [Thread-10] WorkerThread: started Password for foobar@nowhere.com: [DEBUG ] Configuring remote_api. url_path = /remote_api, servername = localhost:8178 [DEBUG ] Bulkloader using app_id: abc [INFO ] Connecting to /remote_api [ERROR ] Exception during authentication Traceback (most recent call last): File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 2802, in Run request_manager.Authenticate() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 1126, in Authenticate remote_api_stub.MaybeInvokeAuthentication() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\remote_api\remote_api_stub.py", line 488, in MaybeInvokeAuthentication datastore_stub._server.Send(datastore_stub._path, payload=None) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\appengine_rpc.py", line 344, in Send f = self.opener.open(req) File "C:\Python25\lib\urllib2.py", line 381, in open response = self._open(req, data) File "C:\Python25\lib\urllib2.py", line 399, in _open '_open', req) File "C:\Python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 1107, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python25\lib\urllib2.py", line 1082, in do_open raise URLError(err) URLError: &lt;urlopen error (10061, 'Connection refused')&gt; [INFO ] Authentication Failed </code></pre> <p>Thank you! </p>
5
2009-08-11T14:45:05Z
1,954,545
<p>Yes, comment out the admin requirement for the remote_api:</p> <p>[app.yaml] <PRE> - url: /remote_api script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py # login: admin </PRE></p> <p>Then run this command:</p> <p><PRE> $ bulkloader.py --dump --kind=DbMyKind --url=<a href="http://localhost:8080/remote%5Fapi" rel="nofollow">http://localhost:8080/remote%5Fapi</a> --filename=export.csv --app_id=my_appid --auth_domain=localhost:8080 </PRE></p> <p>Note: verify that --auth_domain is passed, and proper port is passed for localhost.</p>
2
2009-12-23T18:33:08Z
[ "python", "google-app-engine" ]
Which credentials should I put in for Google App Engine BulkLoader at development server?
1,260,835
<p>I would like to ask which kind of credentials do I need to put on for importing data using the Google App Engine BulkLoader class</p> <pre><code>appcfg.py upload_data --config_file=models.py --filename=listcountries.csv --kind=CMSCountry --url=http://localhost:8178/remote_api vit/ </code></pre> <p>And then it asks me for credentials:</p> <blockquote> <p>Please enter login credentials for localhost</p> </blockquote> <p>Here is an extraction of the content of the models.py, I use this <a href="http://www.andrewpatton.com/countrylist.html">listcountries.csv</a> file</p> <pre><code>class CMSCountry(db.Model): sortorder = db.StringProperty() name = db.StringProperty(required=True) formalname = db.StringProperty() type = db.StringProperty() subtype = db.StringProperty() sovereignt = db.StringProperty() capital = db.StringProperty() currencycode = db.StringProperty() currencyname = db.StringProperty() telephonecode = db.StringProperty() lettercode = db.StringProperty() lettercode2 = db.StringProperty() number = db.StringProperty() countrycode = db.StringProperty() class CMSCountryLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'CMSCountry', [('sortorder', str), ('name', str), ('formalname', str), ('type', str), ('subtype', str), ('sovereignt', str), ('capital', str), ('currencycode', str), ('currencyname', str), ('telephonecode', str), ('lettercode', str), ('lettercode2', str), ('number', str), ('countrycode', str) ]) loaders = [CMSCountryLoader] </code></pre> <p>Every tries to enter the email and password result in "Authentication Failed", so I could not import the data to the development server. </p> <p>I don't think that I have any problem with my files neither my models because I have successfully uploaded the data to the appspot.com application.<br /> So what should I put in for localhost credentials?<br /> I also tried to use <strong>Eclipse with Pydev</strong> but I still got the same message :(<br /> Here is the output:</p> <pre><code>Uploading data records. [INFO ] Logging to bulkloader-log-20090820.121659 [INFO ] Opening database: bulkloader-progress-20090820.121659.sql3 [INFO ] [Thread-1] WorkerThread: started [INFO ] [Thread-2] WorkerThread: started [INFO ] [Thread-3] WorkerThread: started [INFO ] [Thread-4] WorkerThread: started [INFO ] [Thread-5] WorkerThread: started [INFO ] [Thread-6] WorkerThread: started [INFO ] [Thread-7] WorkerThread: started [INFO ] [Thread-8] WorkerThread: started [INFO ] [Thread-9] WorkerThread: started [INFO ] [Thread-10] WorkerThread: started Password for foobar@nowhere.com: [DEBUG ] Configuring remote_api. url_path = /remote_api, servername = localhost:8178 [DEBUG ] Bulkloader using app_id: abc [INFO ] Connecting to /remote_api [ERROR ] Exception during authentication Traceback (most recent call last): File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 2802, in Run request_manager.Authenticate() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 1126, in Authenticate remote_api_stub.MaybeInvokeAuthentication() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\remote_api\remote_api_stub.py", line 488, in MaybeInvokeAuthentication datastore_stub._server.Send(datastore_stub._path, payload=None) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\appengine_rpc.py", line 344, in Send f = self.opener.open(req) File "C:\Python25\lib\urllib2.py", line 381, in open response = self._open(req, data) File "C:\Python25\lib\urllib2.py", line 399, in _open '_open', req) File "C:\Python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 1107, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python25\lib\urllib2.py", line 1082, in do_open raise URLError(err) URLError: &lt;urlopen error (10061, 'Connection refused')&gt; [INFO ] Authentication Failed </code></pre> <p>Thank you! </p>
5
2009-08-11T14:45:05Z
2,018,126
<p>You need create an admin credential in your local development server first. </p> <p>With your firefox (or chrome safari etc), open <a href="http://localhost:8178/remote_api" rel="nofollow">http://localhost:8178/remote_api</a>, you will be asked to login (without password), enter an email as your login, and tick the <code>login as administrater</code> box, login. This will create you a local admin credential for you, use this when bulkloading locally.</p> <p>It applies to other admin required local access.</p> <p>Leaving (or commenting) out <code>login:admin</code> is a bad practice, since you might deploy that into production, too. Take care!</p>
1
2010-01-07T03:59:15Z
[ "python", "google-app-engine" ]
Which credentials should I put in for Google App Engine BulkLoader at development server?
1,260,835
<p>I would like to ask which kind of credentials do I need to put on for importing data using the Google App Engine BulkLoader class</p> <pre><code>appcfg.py upload_data --config_file=models.py --filename=listcountries.csv --kind=CMSCountry --url=http://localhost:8178/remote_api vit/ </code></pre> <p>And then it asks me for credentials:</p> <blockquote> <p>Please enter login credentials for localhost</p> </blockquote> <p>Here is an extraction of the content of the models.py, I use this <a href="http://www.andrewpatton.com/countrylist.html">listcountries.csv</a> file</p> <pre><code>class CMSCountry(db.Model): sortorder = db.StringProperty() name = db.StringProperty(required=True) formalname = db.StringProperty() type = db.StringProperty() subtype = db.StringProperty() sovereignt = db.StringProperty() capital = db.StringProperty() currencycode = db.StringProperty() currencyname = db.StringProperty() telephonecode = db.StringProperty() lettercode = db.StringProperty() lettercode2 = db.StringProperty() number = db.StringProperty() countrycode = db.StringProperty() class CMSCountryLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'CMSCountry', [('sortorder', str), ('name', str), ('formalname', str), ('type', str), ('subtype', str), ('sovereignt', str), ('capital', str), ('currencycode', str), ('currencyname', str), ('telephonecode', str), ('lettercode', str), ('lettercode2', str), ('number', str), ('countrycode', str) ]) loaders = [CMSCountryLoader] </code></pre> <p>Every tries to enter the email and password result in "Authentication Failed", so I could not import the data to the development server. </p> <p>I don't think that I have any problem with my files neither my models because I have successfully uploaded the data to the appspot.com application.<br /> So what should I put in for localhost credentials?<br /> I also tried to use <strong>Eclipse with Pydev</strong> but I still got the same message :(<br /> Here is the output:</p> <pre><code>Uploading data records. [INFO ] Logging to bulkloader-log-20090820.121659 [INFO ] Opening database: bulkloader-progress-20090820.121659.sql3 [INFO ] [Thread-1] WorkerThread: started [INFO ] [Thread-2] WorkerThread: started [INFO ] [Thread-3] WorkerThread: started [INFO ] [Thread-4] WorkerThread: started [INFO ] [Thread-5] WorkerThread: started [INFO ] [Thread-6] WorkerThread: started [INFO ] [Thread-7] WorkerThread: started [INFO ] [Thread-8] WorkerThread: started [INFO ] [Thread-9] WorkerThread: started [INFO ] [Thread-10] WorkerThread: started Password for foobar@nowhere.com: [DEBUG ] Configuring remote_api. url_path = /remote_api, servername = localhost:8178 [DEBUG ] Bulkloader using app_id: abc [INFO ] Connecting to /remote_api [ERROR ] Exception during authentication Traceback (most recent call last): File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 2802, in Run request_manager.Authenticate() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 1126, in Authenticate remote_api_stub.MaybeInvokeAuthentication() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\remote_api\remote_api_stub.py", line 488, in MaybeInvokeAuthentication datastore_stub._server.Send(datastore_stub._path, payload=None) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\appengine_rpc.py", line 344, in Send f = self.opener.open(req) File "C:\Python25\lib\urllib2.py", line 381, in open response = self._open(req, data) File "C:\Python25\lib\urllib2.py", line 399, in _open '_open', req) File "C:\Python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 1107, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python25\lib\urllib2.py", line 1082, in do_open raise URLError(err) URLError: &lt;urlopen error (10061, 'Connection refused')&gt; [INFO ] Authentication Failed </code></pre> <p>Thank you! </p>
5
2009-08-11T14:45:05Z
2,195,685
<p><strong>EUREKA:</strong> I found the way to use the <code>bulkloader.py</code> tool without having to manually enter login credentials.</p> <p>Here are the 2 steps:</p> <hr> <p>Set your <code>app.yaml</code> file up. Example:</p> <pre><code>- url: /remote_api script: $PYTHON_LIB/google/appengine/ext/remote_api/handler.py login: admin </code></pre> <p>You should put it BEFORE your <code>- url: .*</code> line in <code>app.yaml</code>, otherwise you will never access the <code>/remote_api</code> url.</p> <p>Note that I've left the <code>login: admin</code> part, as removing it is a VERY BAD practice, since you might deploy that into production...</p> <hr> <p>2 Launch this command (adapt it to your needs).</p> <pre><code>echo 'XX' | python2.5 ../google_appengine/bulkloader.py --dump --kind=NAMEOFMODEL --url=http://localhost:8080/remote_api --filename=FILENAME --app_id=APPID --email=foobar@nowhere.com --passin . </code></pre> <p>The trick is to use the combination of those 2 parameters:</p> <ul> <li><code>--email=</code> (you can put whichever email address you want, I use <code>foobar@nowhere.com</code>)</li> <li><code>--passin</code></li> </ul> <p>Specifying <code>--email=</code> will suppress the "enter credentials" prompt, and <code>--passin</code> will allow to read the password from <code>stdin</code> (that's where the <code>echo 'XX' |</code> comes into play!)</p> <hr> <p>Enjoy!</p> <p>P.S.: Don't forget to vote so that Google can provide an easier to use way to do that: <a href="http://code.google.com/p/googleappengine/issues/detail?id=2440">Issue 2440</a>.</p>
5
2010-02-03T21:41:56Z
[ "python", "google-app-engine" ]
Which credentials should I put in for Google App Engine BulkLoader at development server?
1,260,835
<p>I would like to ask which kind of credentials do I need to put on for importing data using the Google App Engine BulkLoader class</p> <pre><code>appcfg.py upload_data --config_file=models.py --filename=listcountries.csv --kind=CMSCountry --url=http://localhost:8178/remote_api vit/ </code></pre> <p>And then it asks me for credentials:</p> <blockquote> <p>Please enter login credentials for localhost</p> </blockquote> <p>Here is an extraction of the content of the models.py, I use this <a href="http://www.andrewpatton.com/countrylist.html">listcountries.csv</a> file</p> <pre><code>class CMSCountry(db.Model): sortorder = db.StringProperty() name = db.StringProperty(required=True) formalname = db.StringProperty() type = db.StringProperty() subtype = db.StringProperty() sovereignt = db.StringProperty() capital = db.StringProperty() currencycode = db.StringProperty() currencyname = db.StringProperty() telephonecode = db.StringProperty() lettercode = db.StringProperty() lettercode2 = db.StringProperty() number = db.StringProperty() countrycode = db.StringProperty() class CMSCountryLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'CMSCountry', [('sortorder', str), ('name', str), ('formalname', str), ('type', str), ('subtype', str), ('sovereignt', str), ('capital', str), ('currencycode', str), ('currencyname', str), ('telephonecode', str), ('lettercode', str), ('lettercode2', str), ('number', str), ('countrycode', str) ]) loaders = [CMSCountryLoader] </code></pre> <p>Every tries to enter the email and password result in "Authentication Failed", so I could not import the data to the development server. </p> <p>I don't think that I have any problem with my files neither my models because I have successfully uploaded the data to the appspot.com application.<br /> So what should I put in for localhost credentials?<br /> I also tried to use <strong>Eclipse with Pydev</strong> but I still got the same message :(<br /> Here is the output:</p> <pre><code>Uploading data records. [INFO ] Logging to bulkloader-log-20090820.121659 [INFO ] Opening database: bulkloader-progress-20090820.121659.sql3 [INFO ] [Thread-1] WorkerThread: started [INFO ] [Thread-2] WorkerThread: started [INFO ] [Thread-3] WorkerThread: started [INFO ] [Thread-4] WorkerThread: started [INFO ] [Thread-5] WorkerThread: started [INFO ] [Thread-6] WorkerThread: started [INFO ] [Thread-7] WorkerThread: started [INFO ] [Thread-8] WorkerThread: started [INFO ] [Thread-9] WorkerThread: started [INFO ] [Thread-10] WorkerThread: started Password for foobar@nowhere.com: [DEBUG ] Configuring remote_api. url_path = /remote_api, servername = localhost:8178 [DEBUG ] Bulkloader using app_id: abc [INFO ] Connecting to /remote_api [ERROR ] Exception during authentication Traceback (most recent call last): File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 2802, in Run request_manager.Authenticate() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 1126, in Authenticate remote_api_stub.MaybeInvokeAuthentication() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\remote_api\remote_api_stub.py", line 488, in MaybeInvokeAuthentication datastore_stub._server.Send(datastore_stub._path, payload=None) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\appengine_rpc.py", line 344, in Send f = self.opener.open(req) File "C:\Python25\lib\urllib2.py", line 381, in open response = self._open(req, data) File "C:\Python25\lib\urllib2.py", line 399, in _open '_open', req) File "C:\Python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 1107, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python25\lib\urllib2.py", line 1082, in do_open raise URLError(err) URLError: &lt;urlopen error (10061, 'Connection refused')&gt; [INFO ] Authentication Failed </code></pre> <p>Thank you! </p>
5
2009-08-11T14:45:05Z
2,534,705
<p>Another solution is to stub out the auth function with lambda: <a href="http://www.carlosble.com/?p=603" rel="nofollow">http://www.carlosble.com/?p=603</a></p>
0
2010-03-28T21:46:54Z
[ "python", "google-app-engine" ]
Which credentials should I put in for Google App Engine BulkLoader at development server?
1,260,835
<p>I would like to ask which kind of credentials do I need to put on for importing data using the Google App Engine BulkLoader class</p> <pre><code>appcfg.py upload_data --config_file=models.py --filename=listcountries.csv --kind=CMSCountry --url=http://localhost:8178/remote_api vit/ </code></pre> <p>And then it asks me for credentials:</p> <blockquote> <p>Please enter login credentials for localhost</p> </blockquote> <p>Here is an extraction of the content of the models.py, I use this <a href="http://www.andrewpatton.com/countrylist.html">listcountries.csv</a> file</p> <pre><code>class CMSCountry(db.Model): sortorder = db.StringProperty() name = db.StringProperty(required=True) formalname = db.StringProperty() type = db.StringProperty() subtype = db.StringProperty() sovereignt = db.StringProperty() capital = db.StringProperty() currencycode = db.StringProperty() currencyname = db.StringProperty() telephonecode = db.StringProperty() lettercode = db.StringProperty() lettercode2 = db.StringProperty() number = db.StringProperty() countrycode = db.StringProperty() class CMSCountryLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'CMSCountry', [('sortorder', str), ('name', str), ('formalname', str), ('type', str), ('subtype', str), ('sovereignt', str), ('capital', str), ('currencycode', str), ('currencyname', str), ('telephonecode', str), ('lettercode', str), ('lettercode2', str), ('number', str), ('countrycode', str) ]) loaders = [CMSCountryLoader] </code></pre> <p>Every tries to enter the email and password result in "Authentication Failed", so I could not import the data to the development server. </p> <p>I don't think that I have any problem with my files neither my models because I have successfully uploaded the data to the appspot.com application.<br /> So what should I put in for localhost credentials?<br /> I also tried to use <strong>Eclipse with Pydev</strong> but I still got the same message :(<br /> Here is the output:</p> <pre><code>Uploading data records. [INFO ] Logging to bulkloader-log-20090820.121659 [INFO ] Opening database: bulkloader-progress-20090820.121659.sql3 [INFO ] [Thread-1] WorkerThread: started [INFO ] [Thread-2] WorkerThread: started [INFO ] [Thread-3] WorkerThread: started [INFO ] [Thread-4] WorkerThread: started [INFO ] [Thread-5] WorkerThread: started [INFO ] [Thread-6] WorkerThread: started [INFO ] [Thread-7] WorkerThread: started [INFO ] [Thread-8] WorkerThread: started [INFO ] [Thread-9] WorkerThread: started [INFO ] [Thread-10] WorkerThread: started Password for foobar@nowhere.com: [DEBUG ] Configuring remote_api. url_path = /remote_api, servername = localhost:8178 [DEBUG ] Bulkloader using app_id: abc [INFO ] Connecting to /remote_api [ERROR ] Exception during authentication Traceback (most recent call last): File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 2802, in Run request_manager.Authenticate() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 1126, in Authenticate remote_api_stub.MaybeInvokeAuthentication() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\remote_api\remote_api_stub.py", line 488, in MaybeInvokeAuthentication datastore_stub._server.Send(datastore_stub._path, payload=None) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\appengine_rpc.py", line 344, in Send f = self.opener.open(req) File "C:\Python25\lib\urllib2.py", line 381, in open response = self._open(req, data) File "C:\Python25\lib\urllib2.py", line 399, in _open '_open', req) File "C:\Python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 1107, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python25\lib\urllib2.py", line 1082, in do_open raise URLError(err) URLError: &lt;urlopen error (10061, 'Connection refused')&gt; [INFO ] Authentication Failed </code></pre> <p>Thank you! </p>
5
2009-08-11T14:45:05Z
10,075,187
<p>I use this commands to transfer data from local to remote server. File's extension (json) is important. Framework: django-nonrel, os: Win7.</p> <pre><code>manage.py dumpdata &gt;dump.json manage.py remote loaddata dump.json </code></pre>
1
2012-04-09T15:02:35Z
[ "python", "google-app-engine" ]
Which credentials should I put in for Google App Engine BulkLoader at development server?
1,260,835
<p>I would like to ask which kind of credentials do I need to put on for importing data using the Google App Engine BulkLoader class</p> <pre><code>appcfg.py upload_data --config_file=models.py --filename=listcountries.csv --kind=CMSCountry --url=http://localhost:8178/remote_api vit/ </code></pre> <p>And then it asks me for credentials:</p> <blockquote> <p>Please enter login credentials for localhost</p> </blockquote> <p>Here is an extraction of the content of the models.py, I use this <a href="http://www.andrewpatton.com/countrylist.html">listcountries.csv</a> file</p> <pre><code>class CMSCountry(db.Model): sortorder = db.StringProperty() name = db.StringProperty(required=True) formalname = db.StringProperty() type = db.StringProperty() subtype = db.StringProperty() sovereignt = db.StringProperty() capital = db.StringProperty() currencycode = db.StringProperty() currencyname = db.StringProperty() telephonecode = db.StringProperty() lettercode = db.StringProperty() lettercode2 = db.StringProperty() number = db.StringProperty() countrycode = db.StringProperty() class CMSCountryLoader(bulkloader.Loader): def __init__(self): bulkloader.Loader.__init__(self, 'CMSCountry', [('sortorder', str), ('name', str), ('formalname', str), ('type', str), ('subtype', str), ('sovereignt', str), ('capital', str), ('currencycode', str), ('currencyname', str), ('telephonecode', str), ('lettercode', str), ('lettercode2', str), ('number', str), ('countrycode', str) ]) loaders = [CMSCountryLoader] </code></pre> <p>Every tries to enter the email and password result in "Authentication Failed", so I could not import the data to the development server. </p> <p>I don't think that I have any problem with my files neither my models because I have successfully uploaded the data to the appspot.com application.<br /> So what should I put in for localhost credentials?<br /> I also tried to use <strong>Eclipse with Pydev</strong> but I still got the same message :(<br /> Here is the output:</p> <pre><code>Uploading data records. [INFO ] Logging to bulkloader-log-20090820.121659 [INFO ] Opening database: bulkloader-progress-20090820.121659.sql3 [INFO ] [Thread-1] WorkerThread: started [INFO ] [Thread-2] WorkerThread: started [INFO ] [Thread-3] WorkerThread: started [INFO ] [Thread-4] WorkerThread: started [INFO ] [Thread-5] WorkerThread: started [INFO ] [Thread-6] WorkerThread: started [INFO ] [Thread-7] WorkerThread: started [INFO ] [Thread-8] WorkerThread: started [INFO ] [Thread-9] WorkerThread: started [INFO ] [Thread-10] WorkerThread: started Password for foobar@nowhere.com: [DEBUG ] Configuring remote_api. url_path = /remote_api, servername = localhost:8178 [DEBUG ] Bulkloader using app_id: abc [INFO ] Connecting to /remote_api [ERROR ] Exception during authentication Traceback (most recent call last): File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 2802, in Run request_manager.Authenticate() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\bulkloader.py", line 1126, in Authenticate remote_api_stub.MaybeInvokeAuthentication() File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\ext\remote_api\remote_api_stub.py", line 488, in MaybeInvokeAuthentication datastore_stub._server.Send(datastore_stub._path, payload=None) File "D:\Projects\GoogleAppEngine\google_appengine\google\appengine\tools\appengine_rpc.py", line 344, in Send f = self.opener.open(req) File "C:\Python25\lib\urllib2.py", line 381, in open response = self._open(req, data) File "C:\Python25\lib\urllib2.py", line 399, in _open '_open', req) File "C:\Python25\lib\urllib2.py", line 360, in _call_chain result = func(*args) File "C:\Python25\lib\urllib2.py", line 1107, in http_open return self.do_open(httplib.HTTPConnection, req) File "C:\Python25\lib\urllib2.py", line 1082, in do_open raise URLError(err) URLError: &lt;urlopen error (10061, 'Connection refused')&gt; [INFO ] Authentication Failed </code></pre> <p>Thank you! </p>
5
2009-08-11T14:45:05Z
22,672,978
<p>Use <code>aaa@gmail.com</code> for username.</p> <p>Use <code>a</code> for password.</p> <p>It works. Magically.</p>
2
2014-03-26T21:02:24Z
[ "python", "google-app-engine" ]
Pythonic way of searching for a substring in a list
1,260,947
<p>I have a list of strings - something like </p> <pre><code>mytext = ['This is some text','this is yet more text','This is text that contains the substring foobar123','yet more text'] </code></pre> <p>I want to find the first occurrence of anything that starts with foobar. If I was grepping then I would do search for foobar*. My current solution looks like this</p> <pre><code>for i in mytext: index = i.find("foobar") if(index!=-1): print i </code></pre> <p>Which works just fine but I am wondering if there is a 'better' (i.e more pythonic) way of doing this?</p> <p>Cheers, Mike</p>
3
2009-08-11T15:03:59Z
1,260,964
<pre><code>for s in lst: if 'foobar' in s: print(s) </code></pre>
6
2009-08-11T15:06:50Z
[ "string", "list", "python", "substrings" ]