title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
How do I do a case insensitive string comparison in Python?
319,426
<p>What's the best way to do case insensitive string comparison in Python?</p> <p>I would like to encapsulate comparison of a regular strings to a repository string using in a very simple and pythonic way. I also would like to have ability to look up values in a dict hashed by strings using regular python strings. Much obliged for advice.</p>
270
2008-11-26T01:06:44Z
319,437
<p>The usual approach is to uppercase the strings or lower case them for the lookups and comparisons. For example:</p> <pre><code>&gt;&gt;&gt; "hello".upper() == "HELLO".upper() True &gt;&gt;&gt; </code></pre>
2
2008-11-26T01:09:43Z
[ "python", "comparison", "case-insensitive" ]
How do I do a case insensitive string comparison in Python?
319,426
<p>What's the best way to do case insensitive string comparison in Python?</p> <p>I would like to encapsulate comparison of a regular strings to a repository string using in a very simple and pythonic way. I also would like to have ability to look up values in a dict hashed by strings using regular python strings. Much obliged for advice.</p>
270
2008-11-26T01:06:44Z
319,439
<p>How about converting to lowercase first? you can use <code>string.lower()</code>.</p>
3
2008-11-26T01:09:47Z
[ "python", "comparison", "case-insensitive" ]
How do I do a case insensitive string comparison in Python?
319,426
<p>What's the best way to do case insensitive string comparison in Python?</p> <p>I would like to encapsulate comparison of a regular strings to a repository string using in a very simple and pythonic way. I also would like to have ability to look up values in a dict hashed by strings using regular python strings. Much obliged for advice.</p>
270
2008-11-26T01:06:44Z
322,359
<pre><code>def insenStringCompare(s1, s2): """ Method that takes two strings and returns True or False, based on if they are equal, regardless of case.""" try: return s1.lower() == s2.lower() except AttributeError: print "Please only pass strings into this method." print "You passed a %s and %s" % (s1.__class__, s2.__class__) </code></pre>
3
2008-11-26T22:17:51Z
[ "python", "comparison", "case-insensitive" ]
How do I do a case insensitive string comparison in Python?
319,426
<p>What's the best way to do case insensitive string comparison in Python?</p> <p>I would like to encapsulate comparison of a regular strings to a repository string using in a very simple and pythonic way. I also would like to have ability to look up values in a dict hashed by strings using regular python strings. Much obliged for advice.</p>
270
2008-11-26T01:06:44Z
11,573,384
<p>Using Python 2, calling <code>.lower()</code> on each string or Unicode object...</p> <pre><code>string1.lower() == string2.lower() </code></pre> <p>...will work most of the time, but indeed doesn't work in the situations @tchrist has described.</p> <p>Assume we have a file called <code>unicode.txt</code> containing the two strings <code>Σίσυφος</code> and <code>ΣΊΣΥΦΟΣ</code>. With Python 2:</p> <pre><code>&gt;&gt;&gt; utf8_bytes = open("unicode.txt", 'r').read() &gt;&gt;&gt; print repr(utf8_bytes) '\xce\xa3\xce\xaf\xcf\x83\xcf\x85\xcf\x86\xce\xbf\xcf\x82\n\xce\xa3\xce\x8a\xce\xa3\xce\xa5\xce\xa6\xce\x9f\xce\xa3\n' &gt;&gt;&gt; u = utf8_bytes.decode('utf8') &gt;&gt;&gt; print u Σίσυφος ΣΊΣΥΦΟΣ &gt;&gt;&gt; first, second = u.splitlines() &gt;&gt;&gt; print first.lower() σίσυφος &gt;&gt;&gt; print second.lower() σίσυφοσ &gt;&gt;&gt; first.lower() == second.lower() False &gt;&gt;&gt; first.upper() == second.upper() True </code></pre> <p>The Σ character has two lowercase forms, ς and σ, and <code>.lower()</code> won't help compare them case-insensitively.</p> <p>However, as of Python 3, all three forms will resolve to ς, and calling lower() on both strings will work correctly:</p> <pre><code>&gt;&gt;&gt; s = open('unicode.txt', encoding='utf8').read() &gt;&gt;&gt; print(s) Σίσυφος ΣΊΣΥΦΟΣ &gt;&gt;&gt; first, second = s.splitlines() &gt;&gt;&gt; print(first.lower()) σίσυφος &gt;&gt;&gt; print(second.lower()) σίσυφος &gt;&gt;&gt; first.lower() == second.lower() True &gt;&gt;&gt; first.upper() == second.upper() True </code></pre> <p>So if you care about edge-cases like the three sigmas in Greek, use Python 3.</p> <p>(For reference, Python 2.7.3 and Python 3.3.0b1 are shown in the interpreter printouts above.)</p>
43
2012-07-20T05:27:24Z
[ "python", "comparison", "case-insensitive" ]
How do I do a case insensitive string comparison in Python?
319,426
<p>What's the best way to do case insensitive string comparison in Python?</p> <p>I would like to encapsulate comparison of a regular strings to a repository string using in a very simple and pythonic way. I also would like to have ability to look up values in a dict hashed by strings using regular python strings. Much obliged for advice.</p>
270
2008-11-26T01:06:44Z
18,419,193
<p>If you have lists with strings and you want to compare the strings in different list with case insensitive. Here is my solution. </p> <pre><code>list1 = map(lambda each:each.lower(), list1) list2 = map(lambda each:each.lower(), list2) </code></pre> <p>After doing that, you can make string comparision easly.</p>
-6
2013-08-24T13:39:51Z
[ "python", "comparison", "case-insensitive" ]
How do I do a case insensitive string comparison in Python?
319,426
<p>What's the best way to do case insensitive string comparison in Python?</p> <p>I would like to encapsulate comparison of a regular strings to a repository string using in a very simple and pythonic way. I also would like to have ability to look up values in a dict hashed by strings using regular python strings. Much obliged for advice.</p>
270
2008-11-26T01:06:44Z
27,628,260
<p>I've used this to accomplish something more useful for comparing two strings:</p> <pre><code>def strings_iequal(first, second): try: return first.upper() == second.upper() except AttributeError: if not first: if not second: return True </code></pre>
-5
2014-12-23T21:27:47Z
[ "python", "comparison", "case-insensitive" ]
How do I do a case insensitive string comparison in Python?
319,426
<p>What's the best way to do case insensitive string comparison in Python?</p> <p>I would like to encapsulate comparison of a regular strings to a repository string using in a very simple and pythonic way. I also would like to have ability to look up values in a dict hashed by strings using regular python strings. Much obliged for advice.</p>
270
2008-11-26T01:06:44Z
29,247,821
<p>Comparing string in a case insensitive way seems like something that's trivial, but it's not. I will be using Python 3, since Python 2 is underdeveloped here.</p> <p>The first thing to note it that case-removing conversions in unicode aren't trivial. There is text for which <code>text.lower() != text.upper().lower()</code>, such as <code>"ß"</code>:</p> <pre><code>"ß".lower() #&gt;&gt;&gt; 'ß' "ß".upper().lower() #&gt;&gt;&gt; 'ss' </code></pre> <p>But let's say you wanted to caselessly compare <code>"BUSSE"</code> and <code>"Buße"</code>. Heck, you probably also want to compare <code>"BUSSE"</code> and <code>"BUẞE"</code> equal - that's the newer capital form. The recommended way is to use <code>casefold</code>:</p> <pre><code>help(str.casefold) #&gt;&gt;&gt; Help on method_descriptor: #&gt;&gt;&gt; #&gt;&gt;&gt; casefold(...) #&gt;&gt;&gt; S.casefold() -&gt; str #&gt;&gt;&gt; #&gt;&gt;&gt; Return a version of S suitable for caseless comparisons. #&gt;&gt;&gt; </code></pre> <p>Do not just use <code>lower</code>. If <code>casefold</code> is not available, doing <code>.upper().lower()</code> helps (but only somewhat).</p> <p>Then you should consider accents. If your font renderer is good, you probably think <code>"ê" == "ê"</code> - but it doesn't:</p> <pre><code>"ê" == "ê" #&gt;&gt;&gt; False </code></pre> <p>This is because they are actually</p> <pre><code>import unicodedata [unicodedata.name(char) for char in "ê"] #&gt;&gt;&gt; ['LATIN SMALL LETTER E WITH CIRCUMFLEX'] [unicodedata.name(char) for char in "ê"] #&gt;&gt;&gt; ['LATIN SMALL LETTER E', 'COMBINING CIRCUMFLEX ACCENT'] </code></pre> <p>The simplest way to deal with this is <code>unicodedata.normalize</code>. You probably want to use <strong>NFKD</strong> normalization, but feel free to check the documentation. Then one does</p> <pre><code>unicodedata.normalize("NFKD", "ê") == unicodedata.normalize("NFKD", "ê") #&gt;&gt;&gt; True </code></pre> <p>To finish up, here this is expressed in functions:</p> <pre><code>import unicodedata def normalize_caseless(text): return unicodedata.normalize("NFKD", text.casefold()) def caseless_equal(left, right): return normalize_caseless(left) == normalize_caseless(right) </code></pre>
164
2015-03-25T05:01:44Z
[ "python", "comparison", "case-insensitive" ]
How do I do a case insensitive string comparison in Python?
319,426
<p>What's the best way to do case insensitive string comparison in Python?</p> <p>I would like to encapsulate comparison of a regular strings to a repository string using in a very simple and pythonic way. I also would like to have ability to look up values in a dict hashed by strings using regular python strings. Much obliged for advice.</p>
270
2008-11-26T01:06:44Z
38,627,691
<p>I saw this solution <a href="http://stackoverflow.com/questions/6579876/how-to-match-a-substring-in-a-string-ignoring-case-in-python">here</a> using <a href="https://docs.python.org/2/library/re.html#re.IGNORECASE" rel="nofollow">regex</a>.</p> <pre><code>import re if re.search('mandy', 'Mandy Pande', re.IGNORECASE): # is True </code></pre> <p>It works well with accents</p> <pre><code>In [42]: if re.search("ê","ê", re.IGNORECASE): ....: print(1) ....: 1 </code></pre> <p>However, it doesn't work with unicode characters case-insensitive. Thank you @Rhymoid for pointing out that as my understanding was that it needs the exact symbol, for the case to be true. The output is as follows:</p> <pre><code>In [36]: "ß".lower() Out[36]: 'ß' In [37]: "ß".upper() Out[37]: 'SS' In [38]: "ß".upper().lower() Out[38]: 'ss' In [39]: if re.search("ß","ßß", re.IGNORECASE): ....: print(1) ....: 1 In [40]: if re.search("SS","ßß", re.IGNORECASE): ....: print(1) ....: In [41]: if re.search("ß","SS", re.IGNORECASE): ....: print(1) ....: </code></pre>
1
2016-07-28T05:24:01Z
[ "python", "comparison", "case-insensitive" ]
How do I skip processing the attachments of an email which is an attachment of a different email
319,896
<p>using jython</p> <p>I have a situation where emails come in with different attachments. Certain file types I process others I ignore and dont write to file. I am caught in a rather nasty situation, because sometimes people send an email as an attachment, and that attached email has legal attachments. </p> <p>What I want to do is skip that attached email and all its attachments.</p> <p>using python/jythons std email lib how can i do this?</p> <p><hr /></p> <p>to make it clearer</p> <p>I need to parse an email (named ROOT email), I want to get the attachments from this email using jython. Next certain attachments are supported ie .pdf .doc etc now it just so happens that, the clients send an email (ROOT email) with another email message (CHILD email) as an attachment, and in CHILD email it has .pdf attachments and such like.</p> <p>What I need is: to get rid of any CHILD emails attached to the ROOT email AND the CHILD emails attachments. What happens is I walk over the whole email and it just parses every attachment, BOTH ROOT attachments and CHILD attachments as if they were ROOT attachments.</p> <p>I cannot have this. I am only interested in ROOT attachements that are legal ie .pdf .doc. xls .rtf .tif .tiff</p> <p>That should do for now, I have to run to catch a bus! thanks!</p>
3
2008-11-26T06:20:40Z
320,093
<p>What about the example named "<a href="http://docs.python.org/library/email-examples.html" rel="nofollow">Here’s an example of how to unpack a MIME message like the one above, into a directory of files</a>"? It looks close from what you want.</p> <pre><code>import email ... msg = email.message_from_file(fp) ... for part in msg.walk(): # multipart/* are just containers if part.get_content_maintype() == 'multipart': continue # Applications should really sanitize the given filename so that an # email message can't be used to overwrite important files filename = part.get_filename() if not filename: ext = mimetypes.guess_extension(part.get_content_type()) ... </code></pre>
0
2008-11-26T08:58:31Z
[ "python", "email", "jython", "attachment" ]
How do I skip processing the attachments of an email which is an attachment of a different email
319,896
<p>using jython</p> <p>I have a situation where emails come in with different attachments. Certain file types I process others I ignore and dont write to file. I am caught in a rather nasty situation, because sometimes people send an email as an attachment, and that attached email has legal attachments. </p> <p>What I want to do is skip that attached email and all its attachments.</p> <p>using python/jythons std email lib how can i do this?</p> <p><hr /></p> <p>to make it clearer</p> <p>I need to parse an email (named ROOT email), I want to get the attachments from this email using jython. Next certain attachments are supported ie .pdf .doc etc now it just so happens that, the clients send an email (ROOT email) with another email message (CHILD email) as an attachment, and in CHILD email it has .pdf attachments and such like.</p> <p>What I need is: to get rid of any CHILD emails attached to the ROOT email AND the CHILD emails attachments. What happens is I walk over the whole email and it just parses every attachment, BOTH ROOT attachments and CHILD attachments as if they were ROOT attachments.</p> <p>I cannot have this. I am only interested in ROOT attachements that are legal ie .pdf .doc. xls .rtf .tif .tiff</p> <p>That should do for now, I have to run to catch a bus! thanks!</p>
3
2008-11-26T06:20:40Z
320,285
<p>Have you tried the get_payload( [i[, decode]]) method? Unlike walk it is not documented to recursively open attachments.</p>
0
2008-11-26T10:52:21Z
[ "python", "email", "jython", "attachment" ]
How do I skip processing the attachments of an email which is an attachment of a different email
319,896
<p>using jython</p> <p>I have a situation where emails come in with different attachments. Certain file types I process others I ignore and dont write to file. I am caught in a rather nasty situation, because sometimes people send an email as an attachment, and that attached email has legal attachments. </p> <p>What I want to do is skip that attached email and all its attachments.</p> <p>using python/jythons std email lib how can i do this?</p> <p><hr /></p> <p>to make it clearer</p> <p>I need to parse an email (named ROOT email), I want to get the attachments from this email using jython. Next certain attachments are supported ie .pdf .doc etc now it just so happens that, the clients send an email (ROOT email) with another email message (CHILD email) as an attachment, and in CHILD email it has .pdf attachments and such like.</p> <p>What I need is: to get rid of any CHILD emails attached to the ROOT email AND the CHILD emails attachments. What happens is I walk over the whole email and it just parses every attachment, BOTH ROOT attachments and CHILD attachments as if they were ROOT attachments.</p> <p>I cannot have this. I am only interested in ROOT attachements that are legal ie .pdf .doc. xls .rtf .tif .tiff</p> <p>That should do for now, I have to run to catch a bus! thanks!</p>
3
2008-11-26T06:20:40Z
320,301
<p>I'm understanding your questions to mean "I have to check all attachments of an email, but if an attachment is also an email, I want to ignore it." Either way this answer should lead you down the right path.</p> <p>What I think you want is <code>mimetypes.guess_type()</code>. Using this method is also much better than just checking against a list of exentions.</p> <pre><code>def check(self, msg): import mimetypes for part in msg.walk(): if part.get_filename() is not None: filenames = [n for n in part.getaltnames() if n] for filename in filenames: type, enc = mimetypes.guess_type(filename) if type.startswith('message'): print "This is an email and I want to ignore it." else: print "I want to keep looking at this file." </code></pre> <p>Note that if this still looks through attached emails, change it to this:</p> <pre><code>def check(self, msg): import mimetypes for part in msg.walk(): filename = part.get_filename() if filename is not None: type, enc = mimetypes.guess_type(filename) if type.startswith('message'): print "This is an email and I want to ignore it." else: part_filenames = [n for n in part.getaltnames() if n] for part_filename in part_filenames: print "I want to keep looking at this file." </code></pre> <p><a href="http://docs.python.org/dev/library/mimetypes.html" rel="nofollow">MIME types documentation</a></p>
0
2008-11-26T10:59:27Z
[ "python", "email", "jython", "attachment" ]
How do I skip processing the attachments of an email which is an attachment of a different email
319,896
<p>using jython</p> <p>I have a situation where emails come in with different attachments. Certain file types I process others I ignore and dont write to file. I am caught in a rather nasty situation, because sometimes people send an email as an attachment, and that attached email has legal attachments. </p> <p>What I want to do is skip that attached email and all its attachments.</p> <p>using python/jythons std email lib how can i do this?</p> <p><hr /></p> <p>to make it clearer</p> <p>I need to parse an email (named ROOT email), I want to get the attachments from this email using jython. Next certain attachments are supported ie .pdf .doc etc now it just so happens that, the clients send an email (ROOT email) with another email message (CHILD email) as an attachment, and in CHILD email it has .pdf attachments and such like.</p> <p>What I need is: to get rid of any CHILD emails attached to the ROOT email AND the CHILD emails attachments. What happens is I walk over the whole email and it just parses every attachment, BOTH ROOT attachments and CHILD attachments as if they were ROOT attachments.</p> <p>I cannot have this. I am only interested in ROOT attachements that are legal ie .pdf .doc. xls .rtf .tif .tiff</p> <p>That should do for now, I have to run to catch a bus! thanks!</p>
3
2008-11-26T06:20:40Z
321,134
<p>The problem with existing suggestions is the walk method. This recursively, depth-first, walks the entire tree, including children.</p> <p>Look at the source of the walk method, and adapt it to skip the recursive part. A cursory reading suggests:</p> <pre><code>if msg.is_multipart(): for part in msg.get_payload(): """ Process message, but do not recurse """ filename = part.get_filename() </code></pre> <p>Reading the pydocs, get_payload should return a list of the top level messages, without recursing.</p>
1
2008-11-26T15:38:34Z
[ "python", "email", "jython", "attachment" ]
How to upload a file with django (python) and s3?
319,923
<p>I'm looking for a way to upload a file to s3. I am using django. I am currently using amazon's python library for uploading along with the following code: </p> <p>View:</p> <pre><code>def submitpicture(request): fuser = request.session["login"] copied_data = request.POST.copy() copied_data.update(request.FILES) content_type = copied_data['file'].get('content-type') ffile = copied_data['file']['content'] key = '%s-%s' % (fuser, ''.join(copied_data['file']['filename'].split(' '))) site_s3.save_s3_data(key, ffile, content_type) </code></pre> <p>Template:</p> <pre><code>&lt;form action="/submitpicture/" method="POST"&gt; &lt;input type="file" id="file" name="file" /&gt; &lt;input type="submit" value="submit" /&gt; &lt;/form&gt; </code></pre> <p>However, when I actually try to run it i get the following error:</p> <pre><code>"Key 'file' not found in &lt;QueryDict: {}&gt;" #MultiValueDictKeyError </code></pre> <p>I really don't see what I'm doing wrong. Can someone point me in the right direction?</p> <p>Edit: Just in case someone wonders, I am planning on adding some validation after I get the actual upload working. </p>
11
2008-11-26T06:39:33Z
319,943
<p>You will have to provide the enctype attribute to the FORM element (I've been bitten by this before). For example, your FORM tag should look like: </p> <pre><code>&lt;form action="/submitpicture/" method="POST" enctype="multipart/form-data" &gt; </code></pre> <p>Without the enctype, you will find yourself with an empty request.FILES.</p>
18
2008-11-26T06:57:11Z
[ "python", "django", "file-upload", "amazon-s3" ]
How to upload a file with django (python) and s3?
319,923
<p>I'm looking for a way to upload a file to s3. I am using django. I am currently using amazon's python library for uploading along with the following code: </p> <p>View:</p> <pre><code>def submitpicture(request): fuser = request.session["login"] copied_data = request.POST.copy() copied_data.update(request.FILES) content_type = copied_data['file'].get('content-type') ffile = copied_data['file']['content'] key = '%s-%s' % (fuser, ''.join(copied_data['file']['filename'].split(' '))) site_s3.save_s3_data(key, ffile, content_type) </code></pre> <p>Template:</p> <pre><code>&lt;form action="/submitpicture/" method="POST"&gt; &lt;input type="file" id="file" name="file" /&gt; &lt;input type="submit" value="submit" /&gt; &lt;/form&gt; </code></pre> <p>However, when I actually try to run it i get the following error:</p> <pre><code>"Key 'file' not found in &lt;QueryDict: {}&gt;" #MultiValueDictKeyError </code></pre> <p>I really don't see what I'm doing wrong. Can someone point me in the right direction?</p> <p>Edit: Just in case someone wonders, I am planning on adding some validation after I get the actual upload working. </p>
11
2008-11-26T06:39:33Z
319,947
<p>Instead of doing this manually I would take a look at the storage backend David Larlet has written for Django, it's here: <a href="http://code.larlet.fr/django-storages/" rel="nofollow">http://code.larlet.fr/django-storages/</a></p>
3
2008-11-26T07:01:06Z
[ "python", "django", "file-upload", "amazon-s3" ]
How to upload a file with django (python) and s3?
319,923
<p>I'm looking for a way to upload a file to s3. I am using django. I am currently using amazon's python library for uploading along with the following code: </p> <p>View:</p> <pre><code>def submitpicture(request): fuser = request.session["login"] copied_data = request.POST.copy() copied_data.update(request.FILES) content_type = copied_data['file'].get('content-type') ffile = copied_data['file']['content'] key = '%s-%s' % (fuser, ''.join(copied_data['file']['filename'].split(' '))) site_s3.save_s3_data(key, ffile, content_type) </code></pre> <p>Template:</p> <pre><code>&lt;form action="/submitpicture/" method="POST"&gt; &lt;input type="file" id="file" name="file" /&gt; &lt;input type="submit" value="submit" /&gt; &lt;/form&gt; </code></pre> <p>However, when I actually try to run it i get the following error:</p> <pre><code>"Key 'file' not found in &lt;QueryDict: {}&gt;" #MultiValueDictKeyError </code></pre> <p>I really don't see what I'm doing wrong. Can someone point me in the right direction?</p> <p>Edit: Just in case someone wonders, I am planning on adding some validation after I get the actual upload working. </p>
11
2008-11-26T06:39:33Z
675,326
<p>Adding enctype="multipart/form-data" seems like something that's worth mentioning in the "File Uploads" section of the django docs (<a href="http://docs.djangoproject.com/en/dev/topics/http/file-uploads/" rel="nofollow">http://docs.djangoproject.com/en/dev/topics/http/file-uploads/</a>). Thoughts?</p>
2
2009-03-23T21:34:01Z
[ "python", "django", "file-upload", "amazon-s3" ]
How do you iterate over a tree?
320,052
<p>What is your preferred method of traversing a tree data structure, since recursive method calls can be pretty inefficient in some circumstances. I am simply using a generator like the one above. Do you have any hints to make it faster?</p> <pre><code>def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) </code></pre> <p>Here is some test data. The first one is recursive, the second uses the generator:</p> <pre><code>s = time.time() for i in range(100000): e.inc_counter() print time.time() - s s = time.time() for i in range(100000): for e in e.children(): e.inc_counter_s() print time.time() - s </code></pre> <p>Results:</p> <pre><code>0.416000127792 0.298999786377 </code></pre> <p>Test code:</p> <pre><code>import random class Entity(): def __init__(self, name): self.entities = [] self.name = name self.counter = 1 self.depth = 0 def add_entity(self, e): e.depth = self.depth + 1 self.entities.append(e) def inc_counter_r(self): for e in self.entities: e.counter += 1 e.inc_counter_r() def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) root = Entity("main") def fill_node(root, max_depth): if root.depth &lt;= max_depth: for i in range(random.randint(10, 15)): e = Entity("node_%s_%s" % (root.depth, i)) root.add_entity(e) fill_node(e, max_depth) fill_node(root, 3) import time s = time.time() for i in range(100): root.inc_counter_r() print "recursive:", time.time() - s s = time.time() for i in range(100): for e in root.children(): e.counter += 1 print "generator:", time.time() - s </code></pre>
4
2008-11-26T08:26:22Z
320,060
<p>Unless your tree is really large or you have really high (real) requirements for speed, I would choose the recursive method. Easier to read, easier to code.</p>
5
2008-11-26T08:32:05Z
[ "python", "algorithm" ]
How do you iterate over a tree?
320,052
<p>What is your preferred method of traversing a tree data structure, since recursive method calls can be pretty inefficient in some circumstances. I am simply using a generator like the one above. Do you have any hints to make it faster?</p> <pre><code>def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) </code></pre> <p>Here is some test data. The first one is recursive, the second uses the generator:</p> <pre><code>s = time.time() for i in range(100000): e.inc_counter() print time.time() - s s = time.time() for i in range(100000): for e in e.children(): e.inc_counter_s() print time.time() - s </code></pre> <p>Results:</p> <pre><code>0.416000127792 0.298999786377 </code></pre> <p>Test code:</p> <pre><code>import random class Entity(): def __init__(self, name): self.entities = [] self.name = name self.counter = 1 self.depth = 0 def add_entity(self, e): e.depth = self.depth + 1 self.entities.append(e) def inc_counter_r(self): for e in self.entities: e.counter += 1 e.inc_counter_r() def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) root = Entity("main") def fill_node(root, max_depth): if root.depth &lt;= max_depth: for i in range(random.randint(10, 15)): e = Entity("node_%s_%s" % (root.depth, i)) root.add_entity(e) fill_node(e, max_depth) fill_node(root, 3) import time s = time.time() for i in range(100): root.inc_counter_r() print "recursive:", time.time() - s s = time.time() for i in range(100): for e in root.children(): e.counter += 1 print "generator:", time.time() - s </code></pre>
4
2008-11-26T08:26:22Z
320,061
<p>If you have a lot of RAM and the tree doesn't change often, you can cache the result of the call:</p> <pre><code>def children(self): if self._children_cache is not None: return self._children_cache # Put your code into collectChildren() self._children_cache = self.collectChildren() return self._children_cache </code></pre> <p>Whenever the tree changes, set the cache to None. In this case, using recursive calls might be more effective since the results will accumulate faster.</p>
3
2008-11-26T08:33:07Z
[ "python", "algorithm" ]
How do you iterate over a tree?
320,052
<p>What is your preferred method of traversing a tree data structure, since recursive method calls can be pretty inefficient in some circumstances. I am simply using a generator like the one above. Do you have any hints to make it faster?</p> <pre><code>def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) </code></pre> <p>Here is some test data. The first one is recursive, the second uses the generator:</p> <pre><code>s = time.time() for i in range(100000): e.inc_counter() print time.time() - s s = time.time() for i in range(100000): for e in e.children(): e.inc_counter_s() print time.time() - s </code></pre> <p>Results:</p> <pre><code>0.416000127792 0.298999786377 </code></pre> <p>Test code:</p> <pre><code>import random class Entity(): def __init__(self, name): self.entities = [] self.name = name self.counter = 1 self.depth = 0 def add_entity(self, e): e.depth = self.depth + 1 self.entities.append(e) def inc_counter_r(self): for e in self.entities: e.counter += 1 e.inc_counter_r() def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) root = Entity("main") def fill_node(root, max_depth): if root.depth &lt;= max_depth: for i in range(random.randint(10, 15)): e = Entity("node_%s_%s" % (root.depth, i)) root.add_entity(e) fill_node(e, max_depth) fill_node(root, 3) import time s = time.time() for i in range(100): root.inc_counter_r() print "recursive:", time.time() - s s = time.time() for i in range(100): for e in root.children(): e.counter += 1 print "generator:", time.time() - s </code></pre>
4
2008-11-26T08:26:22Z
320,099
<p>I'm not sure if you can reduce the overhead much on a <em>full</em> in-order traversal of a tree, if you use recursion the call stack will grow some, otherwise you must manually use a stack to push references of the children while visiting each node. Which way is fastest and uses less memory, depends on the expensiveness of the call stack vs. a normal stack. (I would guess the callstack is faster since it should be optimized for its use, and recursion is much easier to implement)</p> <p>If you don't care about the order you visit the nodes, some implementations of trees is actually stored in a dynamic array or linked list or stack wich you can traverse linearly if you don't care about the order it's traversed.</p> <p>But why is it important to have a fast traversal anyway? Trees are good for searching, arrays/linked lists is good for full traversal. If you often need full in-order traversal but few searches and insertions/deletions, an ordered linked list might be best, if searching is what you do most you use a tree. If the data is really massive, so that memory overhead may render recursion impossible, you should use a database.</p>
4
2008-11-26T09:01:37Z
[ "python", "algorithm" ]
How do you iterate over a tree?
320,052
<p>What is your preferred method of traversing a tree data structure, since recursive method calls can be pretty inefficient in some circumstances. I am simply using a generator like the one above. Do you have any hints to make it faster?</p> <pre><code>def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) </code></pre> <p>Here is some test data. The first one is recursive, the second uses the generator:</p> <pre><code>s = time.time() for i in range(100000): e.inc_counter() print time.time() - s s = time.time() for i in range(100000): for e in e.children(): e.inc_counter_s() print time.time() - s </code></pre> <p>Results:</p> <pre><code>0.416000127792 0.298999786377 </code></pre> <p>Test code:</p> <pre><code>import random class Entity(): def __init__(self, name): self.entities = [] self.name = name self.counter = 1 self.depth = 0 def add_entity(self, e): e.depth = self.depth + 1 self.entities.append(e) def inc_counter_r(self): for e in self.entities: e.counter += 1 e.inc_counter_r() def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) root = Entity("main") def fill_node(root, max_depth): if root.depth &lt;= max_depth: for i in range(random.randint(10, 15)): e = Entity("node_%s_%s" % (root.depth, i)) root.add_entity(e) fill_node(e, max_depth) fill_node(root, 3) import time s = time.time() for i in range(100): root.inc_counter_r() print "recursive:", time.time() - s s = time.time() for i in range(100): for e in root.children(): e.counter += 1 print "generator:", time.time() - s </code></pre>
4
2008-11-26T08:26:22Z
320,105
<p>I've written iterative tree-traversal code in the past: it's very ugly, and not fast, unless you know <em>exactly</em> how many children not only each subtree will have, but how many levels there are.</p>
1
2008-11-26T09:03:35Z
[ "python", "algorithm" ]
How do you iterate over a tree?
320,052
<p>What is your preferred method of traversing a tree data structure, since recursive method calls can be pretty inefficient in some circumstances. I am simply using a generator like the one above. Do you have any hints to make it faster?</p> <pre><code>def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) </code></pre> <p>Here is some test data. The first one is recursive, the second uses the generator:</p> <pre><code>s = time.time() for i in range(100000): e.inc_counter() print time.time() - s s = time.time() for i in range(100000): for e in e.children(): e.inc_counter_s() print time.time() - s </code></pre> <p>Results:</p> <pre><code>0.416000127792 0.298999786377 </code></pre> <p>Test code:</p> <pre><code>import random class Entity(): def __init__(self, name): self.entities = [] self.name = name self.counter = 1 self.depth = 0 def add_entity(self, e): e.depth = self.depth + 1 self.entities.append(e) def inc_counter_r(self): for e in self.entities: e.counter += 1 e.inc_counter_r() def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) root = Entity("main") def fill_node(root, max_depth): if root.depth &lt;= max_depth: for i in range(random.randint(10, 15)): e = Entity("node_%s_%s" % (root.depth, i)) root.add_entity(e) fill_node(e, max_depth) fill_node(root, 3) import time s = time.time() for i in range(100): root.inc_counter_r() print "recursive:", time.time() - s s = time.time() for i in range(100): for e in root.children(): e.counter += 1 print "generator:", time.time() - s </code></pre>
4
2008-11-26T08:26:22Z
320,109
<p>I don't know too much about Python internals of function calls, but I really can't imagine that your code snippet is faster than recursively traversing the tree.</p> <p>The call stack (used for function calls, including recursive ones) is typically very fast. Going to the next object will only cost you a single function call. But in your snippet - where you use a stack object, going to the next object will cost you a stack.append (possibly allocating memory on heap), a stack.push (possibly freeing memory from heap), and a yield.</p> <p>The main problem with recursive calls is that you might blow the stack if your tree gets too deep. This isn't likely to happen.</p>
0
2008-11-26T09:06:34Z
[ "python", "algorithm" ]
How do you iterate over a tree?
320,052
<p>What is your preferred method of traversing a tree data structure, since recursive method calls can be pretty inefficient in some circumstances. I am simply using a generator like the one above. Do you have any hints to make it faster?</p> <pre><code>def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) </code></pre> <p>Here is some test data. The first one is recursive, the second uses the generator:</p> <pre><code>s = time.time() for i in range(100000): e.inc_counter() print time.time() - s s = time.time() for i in range(100000): for e in e.children(): e.inc_counter_s() print time.time() - s </code></pre> <p>Results:</p> <pre><code>0.416000127792 0.298999786377 </code></pre> <p>Test code:</p> <pre><code>import random class Entity(): def __init__(self, name): self.entities = [] self.name = name self.counter = 1 self.depth = 0 def add_entity(self, e): e.depth = self.depth + 1 self.entities.append(e) def inc_counter_r(self): for e in self.entities: e.counter += 1 e.inc_counter_r() def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) root = Entity("main") def fill_node(root, max_depth): if root.depth &lt;= max_depth: for i in range(random.randint(10, 15)): e = Entity("node_%s_%s" % (root.depth, i)) root.add_entity(e) fill_node(e, max_depth) fill_node(root, 3) import time s = time.time() for i in range(100): root.inc_counter_r() print "recursive:", time.time() - s s = time.time() for i in range(100): for e in root.children(): e.counter += 1 print "generator:", time.time() - s </code></pre>
4
2008-11-26T08:26:22Z
320,248
<p>Recursive function calls are not incredibly inefficient, that is an old programming myth. (If they're badly implemented, they may incur a larger overhead than necessary, but calling them "incredibly inefficient" is plain wrong.)</p> <p>Remember: don't optimize prematurely, and <em>never</em> optimize without benchmarking first.</p>
4
2008-11-26T10:31:15Z
[ "python", "algorithm" ]
How do you iterate over a tree?
320,052
<p>What is your preferred method of traversing a tree data structure, since recursive method calls can be pretty inefficient in some circumstances. I am simply using a generator like the one above. Do you have any hints to make it faster?</p> <pre><code>def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) </code></pre> <p>Here is some test data. The first one is recursive, the second uses the generator:</p> <pre><code>s = time.time() for i in range(100000): e.inc_counter() print time.time() - s s = time.time() for i in range(100000): for e in e.children(): e.inc_counter_s() print time.time() - s </code></pre> <p>Results:</p> <pre><code>0.416000127792 0.298999786377 </code></pre> <p>Test code:</p> <pre><code>import random class Entity(): def __init__(self, name): self.entities = [] self.name = name self.counter = 1 self.depth = 0 def add_entity(self, e): e.depth = self.depth + 1 self.entities.append(e) def inc_counter_r(self): for e in self.entities: e.counter += 1 e.inc_counter_r() def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) root = Entity("main") def fill_node(root, max_depth): if root.depth &lt;= max_depth: for i in range(random.randint(10, 15)): e = Entity("node_%s_%s" % (root.depth, i)) root.add_entity(e) fill_node(e, max_depth) fill_node(root, 3) import time s = time.time() for i in range(100): root.inc_counter_r() print "recursive:", time.time() - s s = time.time() for i in range(100): for e in root.children(): e.counter += 1 print "generator:", time.time() - s </code></pre>
4
2008-11-26T08:26:22Z
320,252
<p>I can't think of any big algorithmic improvements, but a simple microoptimisation you can make is to bind frequently called methods (such as stack.append / stack.pop) to locals (this saves a dictionary lookup)</p> <pre><code>def children(self): stack = [self.entities] push = stack.append pop = stack.pop while stack: for e in pop(): yield e if e.entities: push(e.entities) </code></pre> <p>This gives a small (~15%) speedup by my tests (using 100 traversals of an 8-deep tree with 4 children at each node gives me the below timings:)</p> <pre><code>children : 5.53942348004 children_bind: 4.77636131253 </code></pre> <p>Not huge, but worth doing if speed is important.</p>
5
2008-11-26T10:33:04Z
[ "python", "algorithm" ]
How do you iterate over a tree?
320,052
<p>What is your preferred method of traversing a tree data structure, since recursive method calls can be pretty inefficient in some circumstances. I am simply using a generator like the one above. Do you have any hints to make it faster?</p> <pre><code>def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) </code></pre> <p>Here is some test data. The first one is recursive, the second uses the generator:</p> <pre><code>s = time.time() for i in range(100000): e.inc_counter() print time.time() - s s = time.time() for i in range(100000): for e in e.children(): e.inc_counter_s() print time.time() - s </code></pre> <p>Results:</p> <pre><code>0.416000127792 0.298999786377 </code></pre> <p>Test code:</p> <pre><code>import random class Entity(): def __init__(self, name): self.entities = [] self.name = name self.counter = 1 self.depth = 0 def add_entity(self, e): e.depth = self.depth + 1 self.entities.append(e) def inc_counter_r(self): for e in self.entities: e.counter += 1 e.inc_counter_r() def children(self): stack = [self.entities] while stack: for e in stack.pop(): yield e if e.entities: stack.append(e.entities) root = Entity("main") def fill_node(root, max_depth): if root.depth &lt;= max_depth: for i in range(random.randint(10, 15)): e = Entity("node_%s_%s" % (root.depth, i)) root.add_entity(e) fill_node(e, max_depth) fill_node(root, 3) import time s = time.time() for i in range(100): root.inc_counter_r() print "recursive:", time.time() - s s = time.time() for i in range(100): for e in root.children(): e.counter += 1 print "generator:", time.time() - s </code></pre>
4
2008-11-26T08:26:22Z
320,329
<p>Here's a pair of small corrections.</p> <pre><code>def children(self): stack = [self.entities] for e in stack: yield e if e.entities: stack.extend(e.entities) </code></pre> <p>I actually think the generator, using append, isn't visiting all the nodes. I think you mean to <code>extend</code> the stack with all entities, not <code>append</code> a simple list of entities to the stack.</p> <p>Also, when the <code>for</code> loop terminates, the <code>while</code> loop in your original example will also terminate because there's no change to the empty stack after the <code>for</code> loop.</p>
0
2008-11-26T11:08:40Z
[ "python", "algorithm" ]
email.retr retrieves strange =20 characters when the email body has chinese characters in it
320,166
<pre><code> self.logger.info(msg) popinstance=poplib.POP3(self.account[0]) self.logger.info(popinstance.getwelcome()) popinstance.user(self.account[1]) popinstance.pass_(self.account[2]) try: (numMsgs, totalSize)=popinstance.stat() self.logger.info("POP contains " + str(numMsgs) + " emails") for thisNum in xrange(1, numMsgs + 1): try: (server_msg, body, octets)=popinstance.retr(thisNum) except: self.logger.error("Could not download email") raise text="\n".join(body) mesg=StringIO.StringIO(text) msg=rfc822.Message(mesg) MessageID=email.Utils.parseaddr(msg["Message-ID"])[1] self.logger.info("downloading email " + MessageID) emailpath=os.path.join(self._emailpath + self._inboxfolder + "\\" + self._sanitize_string(MessageID + ".eml")) emailpath=self._replace_whitespace(emailpath) try: self._dual_dump(text,emailpath) except: pass self.logger.info(popinstance.dele(thisNum)) finally: self.logger.info(popinstance.quit()) </code></pre> <p>(server_msg, body, octets)=popinstance.retr(thisNum) returns =20 in the body of the email when the email contains chinese characters.</p> <p>How do I handle this?</p> <p>raw text of email:</p> <p></p> <p>Subject: (B/L:4363-0192-809.015) SI FOR 15680XXXX436</p> <p>=20</p> <p>Dear</p> <p>=20</p> <p>SI ENCLOSED</p> <p>PLS SEND US THE BL DRAFT AND DEBIT NOTE</p> <p>=20</p> <p>TKS</p> <p>=20</p> <p>MYRI</p> <p>----- Original Message -----=20 </p>
0
2008-11-26T09:41:42Z
320,192
<p>It is probably a Space character encoded in <a href="http://en.wikipedia.org/wiki/Quoted-printable">quoted-printable</a></p>
6
2008-11-26T09:59:28Z
[ "python", "email", "fonts", "jython", "asianfonts" ]
email.retr retrieves strange =20 characters when the email body has chinese characters in it
320,166
<pre><code> self.logger.info(msg) popinstance=poplib.POP3(self.account[0]) self.logger.info(popinstance.getwelcome()) popinstance.user(self.account[1]) popinstance.pass_(self.account[2]) try: (numMsgs, totalSize)=popinstance.stat() self.logger.info("POP contains " + str(numMsgs) + " emails") for thisNum in xrange(1, numMsgs + 1): try: (server_msg, body, octets)=popinstance.retr(thisNum) except: self.logger.error("Could not download email") raise text="\n".join(body) mesg=StringIO.StringIO(text) msg=rfc822.Message(mesg) MessageID=email.Utils.parseaddr(msg["Message-ID"])[1] self.logger.info("downloading email " + MessageID) emailpath=os.path.join(self._emailpath + self._inboxfolder + "\\" + self._sanitize_string(MessageID + ".eml")) emailpath=self._replace_whitespace(emailpath) try: self._dual_dump(text,emailpath) except: pass self.logger.info(popinstance.dele(thisNum)) finally: self.logger.info(popinstance.quit()) </code></pre> <p>(server_msg, body, octets)=popinstance.retr(thisNum) returns =20 in the body of the email when the email contains chinese characters.</p> <p>How do I handle this?</p> <p>raw text of email:</p> <p></p> <p>Subject: (B/L:4363-0192-809.015) SI FOR 15680XXXX436</p> <p>=20</p> <p>Dear</p> <p>=20</p> <p>SI ENCLOSED</p> <p>PLS SEND US THE BL DRAFT AND DEBIT NOTE</p> <p>=20</p> <p>TKS</p> <p>=20</p> <p>MYRI</p> <p>----- Original Message -----=20 </p>
0
2008-11-26T09:41:42Z
370,038
<p>Use the <a href="http://docs.python.org/library/quopri.html" rel="nofollow">quopri</a> module to decode the string.</p>
4
2008-12-15T23:13:38Z
[ "python", "email", "fonts", "jython", "asianfonts" ]
Ensuring subprocesses are dead on exiting Python program
320,232
<p>Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen().</p> <p>If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?</p>
36
2008-11-26T10:21:21Z
320,251
<blockquote> <p>poll( ) </p> <p>Check if child process has terminated. Returns returncode attribute.</p> </blockquote>
4
2008-11-26T10:32:24Z
[ "python", "subprocess", "kill", "zombie-process" ]
Ensuring subprocesses are dead on exiting Python program
320,232
<p>Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen().</p> <p>If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?</p>
36
2008-11-26T10:21:21Z
320,286
<blockquote> <p>Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen().</p> </blockquote> <p>You could violate encapsulation and <em>test</em> that all Popen processes have terminated by doing</p> <pre><code>subprocess._cleanup() print subprocess._active == [] </code></pre> <blockquote> <p>If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?</p> </blockquote> <p>You cannot ensure that all subprocesses are dead without going out and killing every survivor. But if you have this problem, it is probably because you have a deeper design problem.</p>
2
2008-11-26T10:54:03Z
[ "python", "subprocess", "kill", "zombie-process" ]
Ensuring subprocesses are dead on exiting Python program
320,232
<p>Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen().</p> <p>If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?</p>
36
2008-11-26T10:21:21Z
320,290
<p>The <code>subprocess.Popen.wait()</code> is the only way to assure that they're dead. Indeed, POSIX OS's require that you wait on your children. Many *nix's will create a "zombie" process: a dead child for which the parent didn't wait.</p> <p>If the child is reasonably well-written, it terminates. Often, children read from PIPE's. Closing the input is a big hint to the child that it should close up shop and exit.</p> <p>If the child has bugs and doesn't terminate, you may have to kill it. You should fix this bug. </p> <p>If the child is a "serve-forever" loop, and is not designed to terminate, you should either kill it or provide some input or message which will force it to terminate. </p> <p><hr /></p> <p>Edit.</p> <p>In standard OS's, you have <code>os.kill( PID, 9 )</code>. Kill -9 is harsh, BTW. If you can kill them with SIGABRT (6?) or SIGTERM (15) that's more polite.</p> <p>In Windows OS, you don't have an <code>os.kill</code> that works. Look at this <a href="http://code.activestate.com/recipes/347462/">ActiveState Recipe</a> for terminating a process in Windows.</p> <p>We have child processes that are WSGI servers. To terminate them we do a GET on a special URL; this causes the child to clean up and exit.</p>
13
2008-11-26T10:56:21Z
[ "python", "subprocess", "kill", "zombie-process" ]
Ensuring subprocesses are dead on exiting Python program
320,232
<p>Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen().</p> <p>If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?</p>
36
2008-11-26T10:21:21Z
320,408
<p>This is what I did for my posix app:</p> <p>When your app exists call the kill() method of this class: <a href="http://www.pixelbeat.org/libs/subProcess.py" rel="nofollow">http://www.pixelbeat.org/libs/subProcess.py</a></p> <p>Example use here: <a href="http://code.google.com/p/fslint/source/browse/trunk/fslint-gui#608" rel="nofollow">http://code.google.com/p/fslint/source/browse/trunk/fslint-gui#608</a></p>
1
2008-11-26T11:39:11Z
[ "python", "subprocess", "kill", "zombie-process" ]
Ensuring subprocesses are dead on exiting Python program
320,232
<p>Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen().</p> <p>If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?</p>
36
2008-11-26T10:21:21Z
320,712
<p>You can use <a href="http://docs.python.org/library/atexit.html" rel="nofollow"><strong>atexit</strong></a> for this, and register any clean up tasks to be run when your program exits. </p> <p><strong>atexit.register(func[, *args[, **kargs]])</strong></p> <p>In your cleanup process, you can also implement your own wait, and kill it when a your desired timeout occurs.</p> <pre><code>&gt;&gt;&gt; import atexit &gt;&gt;&gt; import sys &gt;&gt;&gt; import time &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; &gt;&gt;&gt; def cleanup(): ... timeout_sec = 5 ... for p in all_processes: # list of your processes ... p_sec = 0 ... for second in range(timeout_sec): ... if p.poll() == None: ... time.sleep(1) ... p_sec += 1 ... if p_sec &gt;= timeout_sec: ... p.kill() # supported from python 2.6 ... print 'cleaned up!' ... &gt;&gt;&gt; &gt;&gt;&gt; atexit.register(cleanup) &gt;&gt;&gt; &gt;&gt;&gt; sys.exit() cleaned up! </code></pre> <p><strong>Note</strong> -- Registered functions won't be run if this process (parent process) is killed.</p> <p><strong>The following windows method is no longer needed for python >= 2.6</strong></p> <p>Here's a way to kill a process in windows. Your Popen object has a pid attribute, so you can just call it by <strong>success = win_kill(p.pid)</strong> (Needs <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">pywin32</a> installed):</p> <pre><code> def win_kill(pid): '''kill a process by specified PID in windows''' import win32api import win32con hProc = None try: hProc = win32api.OpenProcess(win32con.PROCESS_TERMINATE, 0, pid) win32api.TerminateProcess(hProc, 0) except Exception: return False finally: if hProc != None: hProc.Close() return True </code></pre>
29
2008-11-26T13:36:39Z
[ "python", "subprocess", "kill", "zombie-process" ]
Ensuring subprocesses are dead on exiting Python program
320,232
<p>Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen().</p> <p>If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?</p>
36
2008-11-26T10:21:21Z
322,317
<p>On *nix's, maybe using process groups can help you out - you can catch subprocesses spawned by your subprocesses as well.</p> <pre><code>if __name__ == "__main__": os.setpgrp() # create new process group, become its leader try: # some code finally: os.killpg(0, signal.SIGKILL) # kill all processes in my group </code></pre> <p>Another consideration is to escalate the signals: from SIGTERM (default signal for <code>kill</code>) to SIGKILL (a.k.a <code>kill -9</code>). Wait a short while between the signals to give the process a chance to exit cleanly before you <code>kill -9</code> it.</p>
21
2008-11-26T22:02:49Z
[ "python", "subprocess", "kill", "zombie-process" ]
Ensuring subprocesses are dead on exiting Python program
320,232
<p>Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen().</p> <p>If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?</p>
36
2008-11-26T10:21:21Z
9,578,544
<p>help for python code: <a href="http://docs.python.org/dev/library/subprocess.html#subprocess.Popen.wait" rel="nofollow">http://docs.python.org/dev/library/subprocess.html#subprocess.Popen.wait</a></p>
1
2012-03-06T05:48:02Z
[ "python", "subprocess", "kill", "zombie-process" ]
Ensuring subprocesses are dead on exiting Python program
320,232
<p>Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen().</p> <p>If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?</p>
36
2008-11-26T10:21:21Z
22,582,659
<p>I needed a small variation of this problem (cleaning up subprocesses, but without exiting the Python program itself), and since it's not mentioned here among the other answers:</p> <pre><code>p=subprocess.Popen(your_command, preexec_fn=os.setsid) os.killpg(os.getpgid(p.pid), 15) </code></pre> <p><code>setsid</code> will run the program in a new session, thus assigning a new process group to it and its children. calling <code>os.killpg</code> on it thus won't bring down your own python process also.</p>
1
2014-03-22T19:46:18Z
[ "python", "subprocess", "kill", "zombie-process" ]
Ensuring subprocesses are dead on exiting Python program
320,232
<p>Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen().</p> <p>If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?</p>
36
2008-11-26T10:21:21Z
27,295,927
<p>Warning: Linux-only! You can make your child receive a signal when its parent dies.</p> <p>First install python-prctl==1.5.0 then change your parent code to launch your child processes as follows</p> <pre><code>subprocess.Popen(["sleep", "100"], preexec_fn=lambda: prctl.set_pdeathsig(signal.SIGKILL)) </code></pre> <p>What this says is:</p> <ul> <li>launch subprocess: sleep 100</li> <li>after forking and before exec of the subprocess, the child registers for "send me a SIGKILL when my parent terminates".</li> </ul>
2
2014-12-04T13:59:25Z
[ "python", "subprocess", "kill", "zombie-process" ]
Ensuring subprocesses are dead on exiting Python program
320,232
<p>Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen().</p> <p>If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?</p>
36
2008-11-26T10:21:21Z
27,831,932
<p>orip's answer is helpful but has the downside that it kills your process and returns an error code your parent. I avoided that like this:</p> <pre><code>class CleanChildProcesses: def __enter__(self): os.setpgrp() # create new process group, become its leader def __exit__(self, type, value, traceback): try: os.killpg(0, signal.SIGINT) # kill all processes in my group except KeyboardInterrupt: # SIGINT is delievered to this process as well as the child processes. # Ignore it so that the existing exception, if any, is returned. This # leaves us with a clean exit code if there was no exception. pass </code></pre> <p>And then:</p> <pre><code> with CleanChildProcesses(): # Do your work here </code></pre> <p>Of course you can do this with try/except/finally but you have to handle the exceptional and non-exceptional cases separately.</p>
3
2015-01-08T02:17:07Z
[ "python", "subprocess", "kill", "zombie-process" ]
Ensuring subprocesses are dead on exiting Python program
320,232
<p>Is there a way to ensure all created subprocess are dead at exit time of a Python program? By subprocess I mean those created with subprocess.Popen().</p> <p>If not, should I iterate over all of the issuing kills and then kills -9? anything cleaner?</p>
36
2008-11-26T10:21:21Z
35,565,039
<p>A solution for windows may be to use the win32 job api e.g. <a href="http://stackoverflow.com/questions/53208/how-do-i-automatically-destroy-child-processes-in-windows">How do I automatically destroy child processes in Windows?</a></p> <p>Here's an existing python implementation</p> <p><a href="https://gist.github.com/ubershmekel/119697afba2eaecc6330" rel="nofollow">https://gist.github.com/ubershmekel/119697afba2eaecc6330</a></p>
1
2016-02-22T22:17:02Z
[ "python", "subprocess", "kill", "zombie-process" ]
Python type-error issue
320,827
<p>I'm writing a simple program to help generate orders for a game I'm a member of. It falls into the catergory of programmes I don't actually need. But now I've started I want it to work. It all pretty much runs smoothly but I can't figure out how to stop a type-error ocurring about half way through. Here's the code;</p> <pre><code>status = 1 print "[b][u]magic[/u][/b]" while status == 1: print " " print "would you like to:" print " " print "1) add another spell" print "2) end" print " " choice = input("Choose your option: ") print " " if choice == 1: name = raw_input("What is the spell called?") level = raw_input("What level of the spell are you trying to research?") print "What tier is the spell: " print " " print "1) low" print "2) mid" print "3) high" print " " tier = input("Choose your option: ") if tier == 1: materials = 1 + (level * 1) rp = 10 + (level * 5) elif tier == 2: materials = 2 + (level * 1.5) rp = 10 + (level * 15) elif tier == 3: materials = 5 + (level * 2) rp = 60 + (level * 40) print "research ", name, "to level ", level, "--- material cost = ", materials, "and research point cost =", rp elif choice == 2: status = 0 </code></pre> <p>Can anyone help?</p> <p><em>edit</em></p> <p>The error I get is;</p> <pre><code>Traceback (most recent call last): File "C:\Users\Mike\Documents\python\magic orders", line 27, in &lt;module&gt; materials = 1 + (level * 1) TypeError: unsupported operand type(s) for +: 'int' and 'str' </code></pre>
1
2008-11-26T14:18:33Z
320,862
<p>A stacktrace would've helped, but presumably the error is:</p> <pre><code>materials = 1 + (level * 1) </code></pre> <p>‘level’ is a string, and you can't do arithmetic on strings. Python is a dynamically-typed language, but not a weakly-typed one.</p> <pre><code>level= raw_input('blah') try: level= int(level) except ValueError: # user put something non-numeric in, tell them off </code></pre> <p>In other parts of the program you are using input(), which will evaluate the entered string as Python, so for “1” will give you the number 1.</p> <p>But! This is super-dangerous — imagine what happens if the user types “os.remove(filename)” instead of a number. Unless the user is only you and you don't care, never use input(). It will be going away in Python 3.0 (raw_input's behaviour will be renamed input).</p>
12
2008-11-26T14:26:57Z
[ "python", "typeerror" ]
Currency formatting in Python
320,929
<p>I am looking to format a number like 188518982.18 to £188,518,982.18 using Python.</p> <p>How can I do this?</p>
99
2008-11-26T14:43:33Z
320,951
<p>See the <a href="https://docs.python.org/2/library/locale.html">locale</a> module.</p> <p>This does currency (and date) formatting.</p> <pre><code>&gt;&gt;&gt; import locale &gt;&gt;&gt; locale.setlocale( locale.LC_ALL, '' ) 'English_United States.1252' &gt;&gt;&gt; locale.currency( 188518982.18 ) '$188518982.18' &gt;&gt;&gt; locale.currency( 188518982.18, grouping=True ) '$188,518,982.18' </code></pre>
133
2008-11-26T14:50:59Z
[ "python", "formatting", "currency" ]
Currency formatting in Python
320,929
<p>I am looking to format a number like 188518982.18 to £188,518,982.18 using Python.</p> <p>How can I do this?</p>
99
2008-11-26T14:43:33Z
321,013
<p>Oh, that's an interesting beast.</p> <p>I've spent considerable time of getting that right, there are three main issues that differs from locale to locale: - currency symbol and direction - thousand separator - decimal point</p> <p>I've written my own rather extensive implementation of this which is part of the kiwi python framework, check out the LGPL:ed source here:</p> <p><a href="http://svn.async.com.br/cgi-bin/viewvc.cgi/kiwi/trunk/kiwi/currency.py?view=markup" rel="nofollow">http://svn.async.com.br/cgi-bin/viewvc.cgi/kiwi/trunk/kiwi/currency.py?view=markup</a></p> <p>The code is slightly Linux/Glibc specific, but shouldn't be too difficult to adopt to windows or other unixes.</p> <p>Once you have that installed you can do the following:</p> <pre><code>&gt;&gt;&gt; from kiwi.datatypes import currency &gt;&gt;&gt; v = currency('10.5').format() </code></pre> <p>Which will then give you:</p> <pre><code>'$10.50' </code></pre> <p>or</p> <pre><code>'10,50 kr' </code></pre> <p>Depending on the currently selected locale.</p> <p>The main point this post has over the other is that it will work with older versions of python. locale.currency was introduced in python 2.5.</p>
3
2008-11-26T15:06:36Z
[ "python", "formatting", "currency" ]
Currency formatting in Python
320,929
<p>I am looking to format a number like 188518982.18 to £188,518,982.18 using Python.</p> <p>How can I do this?</p>
99
2008-11-26T14:43:33Z
950,155
<p>I've come to look at the same thing and found <a href="http://code.google.com/p/python-money/" rel="nofollow">python-money</a> not really used it yet but maybe a mix of the two would be good</p>
0
2009-06-04T12:16:00Z
[ "python", "formatting", "currency" ]
Currency formatting in Python
320,929
<p>I am looking to format a number like 188518982.18 to £188,518,982.18 using Python.</p> <p>How can I do this?</p>
99
2008-11-26T14:43:33Z
1,082,547
<p>My locale settings seemed incomplete, so I had too look beyond this SO answer and found: </p> <p><a href="http://docs.python.org/library/decimal.html#recipes">http://docs.python.org/library/decimal.html#recipes</a></p> <p>OS-independent</p> <p>Just wanted to share here.</p>
15
2009-07-04T16:41:31Z
[ "python", "formatting", "currency" ]
Currency formatting in Python
320,929
<p>I am looking to format a number like 188518982.18 to £188,518,982.18 using Python.</p> <p>How can I do this?</p>
99
2008-11-26T14:43:33Z
3,393,776
<h2>New in 2.7</h2> <pre><code>&gt;&gt;&gt; '{:20,.2f}'.format(18446744073709551616.0) '18,446,744,073,709,551,616.00' </code></pre> <p><a href="http://docs.python.org/dev/whatsnew/2.7.html#pep-0378">http://docs.python.org/dev/whatsnew/2.7.html#pep-0378</a></p>
63
2010-08-03T05:20:21Z
[ "python", "formatting", "currency" ]
Currency formatting in Python
320,929
<p>I am looking to format a number like 188518982.18 to £188,518,982.18 using Python.</p> <p>How can I do this?</p>
99
2008-11-26T14:43:33Z
3,866,014
<p>If you are using OSX and have yet to set your locale module setting this first answer will not work you will receive the following error:</p> <pre><code>Traceback (most recent call last):File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/locale.py", line 221, in currency raise ValueError("Currency formatting is not possible using "ValueError: Currency formatting is not possible using the 'C' locale. </code></pre> <p>To remedy this you will have to do use the following:</p> <pre><code>locale.setlocale(locale.LC_ALL, 'en_US') </code></pre>
8
2010-10-05T17:08:55Z
[ "python", "formatting", "currency" ]
Currency formatting in Python
320,929
<p>I am looking to format a number like 188518982.18 to £188,518,982.18 using Python.</p> <p>How can I do this?</p>
99
2008-11-26T14:43:33Z
8,851,191
<p>Not quite sure why it's not mentioned more online (or on this thread), but the <a href="http://babel.pocoo.org/">Babel</a> package (and Django utilities) from the Edgewall guys is awesome for currency formatting (and lots of other i18n tasks). It's nice because it doesn't suffer from the need to do everything globally like the core Python locale module.</p> <p>The example the OP gave would simply be:</p> <pre><code>&gt;&gt;&gt; import babel.numbers &gt;&gt;&gt; import decimal &gt;&gt;&gt; babel.numbers.format_currency( decimal.Decimal( "188518982.18" ), "GBP" ) £188,518,982.18 </code></pre>
28
2012-01-13T13:17:00Z
[ "python", "formatting", "currency" ]
Currency formatting in Python
320,929
<p>I am looking to format a number like 188518982.18 to £188,518,982.18 using Python.</p> <p>How can I do this?</p>
99
2008-11-26T14:43:33Z
26,771,637
<p>A lambda for calculating it inside a function, with help from <a href="http://stackoverflow.com/a/3393776/1860929">@Nate's answer</a></p> <pre><code>converter = lambda amount, currency: "%s%s%s" %( "-" if amount &lt; 0 else "", currency, ('{:%d,.2f}'%(len(str(amount))+3)).format(abs(amount)).lstrip()) </code></pre> <p>and then,</p> <pre><code>&gt;&gt;&gt; converter(123132132.13, "$") '$123,132,132.13' &gt;&gt;&gt; converter(-123132132.13, "$") '-$123,132,132.13' </code></pre>
2
2014-11-06T04:18:24Z
[ "python", "formatting", "currency" ]
How to include output of PHP script in Python driven Plone site?
320,979
<p>I need to have the output of a PHP snippet in a Plone site. It was delivered to be a small library that has a display() function, in PHP, that outputs a line of text. But I need to put it in a Plone site. Do you have any recommendations?</p> <p>I was thinking a long the lines of having a display.php that just runs display() and from the Plone template to download that URL and output the content. Do you think it might work? What methods of hitting a URL, retrieve the content and outputting can I use from inside a Plone template?</p> <p>One important and critical constraint is that the output should be directly on the HTML and not an an iframe. This is a constraint coming from the outside, nothing technical.</p>
2
2008-11-26T14:58:46Z
321,123
<p>Probably the easiest way: install <a href="http://plone.org/products/windowz" rel="nofollow" title="windowz">windowz</a> inside your site. That way you get a page with an iframe in your plone layout. Make sure the php script outputs a regular html page and configure your windowz page with that url. Done.</p> <p>Works great for existing in-company phonebook applications and so.</p>
0
2008-11-26T15:37:08Z
[ "php", "python", "plone" ]
How to include output of PHP script in Python driven Plone site?
320,979
<p>I need to have the output of a PHP snippet in a Plone site. It was delivered to be a small library that has a display() function, in PHP, that outputs a line of text. But I need to put it in a Plone site. Do you have any recommendations?</p> <p>I was thinking a long the lines of having a display.php that just runs display() and from the Plone template to download that URL and output the content. Do you think it might work? What methods of hitting a URL, retrieve the content and outputting can I use from inside a Plone template?</p> <p>One important and critical constraint is that the output should be directly on the HTML and not an an iframe. This is a constraint coming from the outside, nothing technical.</p>
2
2008-11-26T14:58:46Z
321,274
<p>Well, use AJAX to call the PHP script (yes, you will need apache) and display the output. Adding a custom JS to plone is trivial and this abstract the technology issue.</p> <p>Just be sure this is not a critical feature. Some users still deactivate JS and the web page should therefor degrade itself nicely.</p>
1
2008-11-26T16:18:46Z
[ "php", "python", "plone" ]
How to include output of PHP script in Python driven Plone site?
320,979
<p>I need to have the output of a PHP snippet in a Plone site. It was delivered to be a small library that has a display() function, in PHP, that outputs a line of text. But I need to put it in a Plone site. Do you have any recommendations?</p> <p>I was thinking a long the lines of having a display.php that just runs display() and from the Plone template to download that URL and output the content. Do you think it might work? What methods of hitting a URL, retrieve the content and outputting can I use from inside a Plone template?</p> <p>One important and critical constraint is that the output should be directly on the HTML and not an an iframe. This is a constraint coming from the outside, nothing technical.</p>
2
2008-11-26T14:58:46Z
325,149
<p>Another option is to run the PHP script on the server using os.popen, then just printing the output. Quick and dirty example:</p> <pre><code>import os print os.popen('php YourScript.php').read()</code></pre>
1
2008-11-28T06:12:56Z
[ "php", "python", "plone" ]
Making functions non override-able
321,024
<p>I know python functions are virtual by default. Let's say I have this:</p> <pre><code>class Foo: def __init__(self, args): do some stuff def goo(): print "You can overload me" def roo(): print "You cannot overload me" </code></pre> <p>I don't want them to be able to do this:</p> <pre><code>class Aoo(Foo): def roo(): print "I don't want you to be able to do this" </code></pre> <p>Is there a way to prevent users from overloading roo()?</p>
5
2008-11-26T15:08:29Z
321,119
<p>Since Python has monkey patching, not only can you not make anything "private". Even if you could, someone could still monkeypatch in a new version of the method function.</p> <p>You can use this kind of name as a "don't go near" warning.</p> <pre><code>class Foo( object ): def _roo( self ): """Change this at your own risk.""" </code></pre> <p>That's the usual approach. Everyone can read your source. They were warned. If they boldly go where they were warned not to go, they get what they deserve. It doesn't work and you can't help them.</p> <p>You can try to make this intentionally obcure with inner classes and "hidden" implementation modules that are called by the "private" methods. But... everyone has your source. You can't <em>prevent</em> anything. You can only advise people of the consequences of their actions.</p>
9
2008-11-26T15:34:24Z
[ "python" ]
Making functions non override-able
321,024
<p>I know python functions are virtual by default. Let's say I have this:</p> <pre><code>class Foo: def __init__(self, args): do some stuff def goo(): print "You can overload me" def roo(): print "You cannot overload me" </code></pre> <p>I don't want them to be able to do this:</p> <pre><code>class Aoo(Foo): def roo(): print "I don't want you to be able to do this" </code></pre> <p>Is there a way to prevent users from overloading roo()?</p>
5
2008-11-26T15:08:29Z
321,240
<p>You can use a metaclass:</p> <pre><code>class NonOverridable(type): def __new__(self, name, bases, dct): if bases and "roo" in dct: raise SyntaxError, "Overriding roo is not allowed" return type.__new__(self, name, bases, dct) class foo: __metaclass__=NonOverridable ... </code></pre> <p>The metatype's <strong>new</strong> is called whenever a subclass is created; this will cause an error in the case you present. It will accept a definition of roo only if there are no base classes.</p> <p>You can make the approach more fancy by using annotations to declare which methods are final; you then need to inspect all bases and compute all final methods, to see whether any of them is overridden.</p> <p>This still doesn't prevent somebody monkey-patching a method into a class after it is defined; you can try to catch these by using a custom dictionary as the classes' dictionary (which might not work in all Python versions, as classes might require the class dictionary to be of the exact dict type).</p>
26
2008-11-26T16:07:04Z
[ "python" ]
Making functions non override-able
321,024
<p>I know python functions are virtual by default. Let's say I have this:</p> <pre><code>class Foo: def __init__(self, args): do some stuff def goo(): print "You can overload me" def roo(): print "You cannot overload me" </code></pre> <p>I don't want them to be able to do this:</p> <pre><code>class Aoo(Foo): def roo(): print "I don't want you to be able to do this" </code></pre> <p>Is there a way to prevent users from overloading roo()?</p>
5
2008-11-26T15:08:29Z
321,334
<pre><code>def non_overridable(f): f.non_overridable = True return f class ToughMeta(type): def __new__(cls, name, bases, dct): non_overridables = get_non_overridables(bases) for name in dct: if name in non_overridables: raise Exception ("You can not override %s, it is non-overridable" % name) return type.__new__(cls, name, bases, dct) def get_non_overridables(bases): ret = [] for source in bases: for name, attr in source.__dict__.items(): if getattr(attr, "non_overridable", False): ret.append(name) ret.extend(get_non_overridables(source.__bases__)) return ret class ToughObject(object): __metaclass__ = ToughMeta @non_overridable def test1(): pass # Tests --------------- class Derived(ToughObject): @non_overridable def test2(self): print "hello" class Derived2(Derived): def test1(self): print "derived2" # -------------------- </code></pre>
5
2008-11-26T16:32:08Z
[ "python" ]
python logging into a forum
321,304
<p>I've written this to try and log onto a forum (phpBB3).</p> <pre><code>import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) output = page.read() </code></pre> <p>However when I run it it comes up with;</p> <pre><code>Traceback (most recent call last): File "C:/Users/Mike/Documents/python/test urllib2", line 4, in &lt;module&gt; page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) TypeError: string indices must be integers </code></pre> <p>any ideas as to how to solve this?</p> <p><em>edit</em></p> <p>adding a comma between the string and the data gives this error instead</p> <pre><code>Traceback (most recent call last): File "C:/Users/Mike/Documents/python/test urllib2", line 4, in &lt;module&gt; page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login",[logindata]) File "C:\Python25\lib\urllib.py", line 84, in urlopen return opener.open(url, data) File "C:\Python25\lib\urllib.py", line 192, in open return getattr(self, name)(url, data) File "C:\Python25\lib\urllib.py", line 327, in open_http h.send(data) File "C:\Python25\lib\httplib.py", line 711, in send self.sock.sendall(str) File "&lt;string&gt;", line 1, in sendall TypeError: sendall() argument 1 must be string or read-only buffer, not list </code></pre> <p><em>edit2</em></p> <p>I've changed the code from what it was to;</p> <pre><code>import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib2.urlopen("http://www.woarl.com/board/ucp.php?mode=login", logindata) output = page.read() </code></pre> <p>This doesn't throw any error messages, it just gives 3 blank lines. Is this because I'm trying to read from the log in page which disappears after logging in. If so how do I get it to display the index which is what should appear after hitting log in.</p>
3
2008-11-26T16:24:13Z
321,316
<p>Your URL string shouldn't be </p> <pre><code>"http://www.woarl.com/board/ucp.php?mode=login"[logindata] </code></pre> <p>But</p> <pre><code> "http://www.woarl.com/board/ucp.php?mode=login", logindata </code></pre> <p>I think, because [] is for array and it require an integer. I might be wrong cause I haven't done a lot of Python.</p>
1
2008-11-26T16:27:31Z
[ "python", "login", "phpbb3", "typeerror" ]
python logging into a forum
321,304
<p>I've written this to try and log onto a forum (phpBB3).</p> <pre><code>import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) output = page.read() </code></pre> <p>However when I run it it comes up with;</p> <pre><code>Traceback (most recent call last): File "C:/Users/Mike/Documents/python/test urllib2", line 4, in &lt;module&gt; page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) TypeError: string indices must be integers </code></pre> <p>any ideas as to how to solve this?</p> <p><em>edit</em></p> <p>adding a comma between the string and the data gives this error instead</p> <pre><code>Traceback (most recent call last): File "C:/Users/Mike/Documents/python/test urllib2", line 4, in &lt;module&gt; page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login",[logindata]) File "C:\Python25\lib\urllib.py", line 84, in urlopen return opener.open(url, data) File "C:\Python25\lib\urllib.py", line 192, in open return getattr(self, name)(url, data) File "C:\Python25\lib\urllib.py", line 327, in open_http h.send(data) File "C:\Python25\lib\httplib.py", line 711, in send self.sock.sendall(str) File "&lt;string&gt;", line 1, in sendall TypeError: sendall() argument 1 must be string or read-only buffer, not list </code></pre> <p><em>edit2</em></p> <p>I've changed the code from what it was to;</p> <pre><code>import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib2.urlopen("http://www.woarl.com/board/ucp.php?mode=login", logindata) output = page.read() </code></pre> <p>This doesn't throw any error messages, it just gives 3 blank lines. Is this because I'm trying to read from the log in page which disappears after logging in. If so how do I get it to display the index which is what should appear after hitting log in.</p>
3
2008-11-26T16:24:13Z
321,317
<p>How about using a comma between the string,<code>"http:..."</code> and the urlencoded data, <code>[logindata]</code>?</p>
1
2008-11-26T16:27:39Z
[ "python", "login", "phpbb3", "typeerror" ]
python logging into a forum
321,304
<p>I've written this to try and log onto a forum (phpBB3).</p> <pre><code>import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) output = page.read() </code></pre> <p>However when I run it it comes up with;</p> <pre><code>Traceback (most recent call last): File "C:/Users/Mike/Documents/python/test urllib2", line 4, in &lt;module&gt; page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) TypeError: string indices must be integers </code></pre> <p>any ideas as to how to solve this?</p> <p><em>edit</em></p> <p>adding a comma between the string and the data gives this error instead</p> <pre><code>Traceback (most recent call last): File "C:/Users/Mike/Documents/python/test urllib2", line 4, in &lt;module&gt; page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login",[logindata]) File "C:\Python25\lib\urllib.py", line 84, in urlopen return opener.open(url, data) File "C:\Python25\lib\urllib.py", line 192, in open return getattr(self, name)(url, data) File "C:\Python25\lib\urllib.py", line 327, in open_http h.send(data) File "C:\Python25\lib\httplib.py", line 711, in send self.sock.sendall(str) File "&lt;string&gt;", line 1, in sendall TypeError: sendall() argument 1 must be string or read-only buffer, not list </code></pre> <p><em>edit2</em></p> <p>I've changed the code from what it was to;</p> <pre><code>import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib2.urlopen("http://www.woarl.com/board/ucp.php?mode=login", logindata) output = page.read() </code></pre> <p>This doesn't throw any error messages, it just gives 3 blank lines. Is this because I'm trying to read from the log in page which disappears after logging in. If so how do I get it to display the index which is what should appear after hitting log in.</p>
3
2008-11-26T16:24:13Z
321,322
<p>Your line</p> <pre><code>page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) </code></pre> <p>is semantically invalid Python. Presumably you meant</p> <pre><code>page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login", [logindata]) </code></pre> <p>which has a comma separating the arguments. However, what you ACTUALLY want is simply</p> <pre><code>page = urllib2.urlopen("http://www.woarl.com/board/ucp.php?mode=login", logindata) </code></pre> <p>without trying to enclose logindata into a list and using the more up-to-date version of urlopen is the urllib2 library.</p>
5
2008-11-26T16:29:19Z
[ "python", "login", "phpbb3", "typeerror" ]
python logging into a forum
321,304
<p>I've written this to try and log onto a forum (phpBB3).</p> <pre><code>import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) output = page.read() </code></pre> <p>However when I run it it comes up with;</p> <pre><code>Traceback (most recent call last): File "C:/Users/Mike/Documents/python/test urllib2", line 4, in &lt;module&gt; page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) TypeError: string indices must be integers </code></pre> <p>any ideas as to how to solve this?</p> <p><em>edit</em></p> <p>adding a comma between the string and the data gives this error instead</p> <pre><code>Traceback (most recent call last): File "C:/Users/Mike/Documents/python/test urllib2", line 4, in &lt;module&gt; page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login",[logindata]) File "C:\Python25\lib\urllib.py", line 84, in urlopen return opener.open(url, data) File "C:\Python25\lib\urllib.py", line 192, in open return getattr(self, name)(url, data) File "C:\Python25\lib\urllib.py", line 327, in open_http h.send(data) File "C:\Python25\lib\httplib.py", line 711, in send self.sock.sendall(str) File "&lt;string&gt;", line 1, in sendall TypeError: sendall() argument 1 must be string or read-only buffer, not list </code></pre> <p><em>edit2</em></p> <p>I've changed the code from what it was to;</p> <pre><code>import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib2.urlopen("http://www.woarl.com/board/ucp.php?mode=login", logindata) output = page.read() </code></pre> <p>This doesn't throw any error messages, it just gives 3 blank lines. Is this because I'm trying to read from the log in page which disappears after logging in. If so how do I get it to display the index which is what should appear after hitting log in.</p>
3
2008-11-26T16:24:13Z
321,339
<p>If you do a type on logindata, you can see that it is a string:</p> <pre><code>&gt;&gt;&gt; import urllib &gt;&gt;&gt; logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) &gt;&gt;&gt; type(logindata) &lt;type 'str'&gt; </code></pre> <p>Putting it in brackets ([]) puts it in a list context, which isn't what you want.</p>
1
2008-11-26T16:33:59Z
[ "python", "login", "phpbb3", "typeerror" ]
python logging into a forum
321,304
<p>I've written this to try and log onto a forum (phpBB3).</p> <pre><code>import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) output = page.read() </code></pre> <p>However when I run it it comes up with;</p> <pre><code>Traceback (most recent call last): File "C:/Users/Mike/Documents/python/test urllib2", line 4, in &lt;module&gt; page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login"[logindata]) TypeError: string indices must be integers </code></pre> <p>any ideas as to how to solve this?</p> <p><em>edit</em></p> <p>adding a comma between the string and the data gives this error instead</p> <pre><code>Traceback (most recent call last): File "C:/Users/Mike/Documents/python/test urllib2", line 4, in &lt;module&gt; page = urllib.urlopen("http://www.woarl.com/board/ucp.php?mode=login",[logindata]) File "C:\Python25\lib\urllib.py", line 84, in urlopen return opener.open(url, data) File "C:\Python25\lib\urllib.py", line 192, in open return getattr(self, name)(url, data) File "C:\Python25\lib\urllib.py", line 327, in open_http h.send(data) File "C:\Python25\lib\httplib.py", line 711, in send self.sock.sendall(str) File "&lt;string&gt;", line 1, in sendall TypeError: sendall() argument 1 must be string or read-only buffer, not list </code></pre> <p><em>edit2</em></p> <p>I've changed the code from what it was to;</p> <pre><code>import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib2.urlopen("http://www.woarl.com/board/ucp.php?mode=login", logindata) output = page.read() </code></pre> <p>This doesn't throw any error messages, it just gives 3 blank lines. Is this because I'm trying to read from the log in page which disappears after logging in. If so how do I get it to display the index which is what should appear after hitting log in.</p>
3
2008-11-26T16:24:13Z
322,726
<p>This would be easier with the high-level "mechanize" module.</p>
-1
2008-11-27T01:41:36Z
[ "python", "login", "phpbb3", "typeerror" ]
urllib2 data sending
321,582
<p>I've recently written this with help from SO. Now could someone please tell me how to make it actually log onto the board. It brings up everything just in a non logged in format.</p> <pre><code>import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib2.urlopen("http://www.woarl.com/board/index.php", logindata) pagesource = page.read() print pagesource </code></pre>
2
2008-11-26T17:56:09Z
321,601
<p>You probably want to look into preserving cookies from the server.</p> <p><a href="http://pycurl.sourceforge.net/" rel="nofollow">Pycurl</a> or <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">Mechanize</a> will make this much easier for you</p>
3
2008-11-26T18:02:14Z
[ "python", "urllib2" ]
urllib2 data sending
321,582
<p>I've recently written this with help from SO. Now could someone please tell me how to make it actually log onto the board. It brings up everything just in a non logged in format.</p> <pre><code>import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib2.urlopen("http://www.woarl.com/board/index.php", logindata) pagesource = page.read() print pagesource </code></pre>
2
2008-11-26T17:56:09Z
321,613
<p>Someone recently asked <a href="http://stackoverflow.com/questions/301924/python-urlliburllib2httplib-confusion">the same question you're asking</a>. If you read through the answers to that question you'll see code examples showing you how to stay logged in while browsing a site in a Python script using only stuff in the standard library.</p> <p>The accepted answer might not be as useful to you as <a href="http://stackoverflow.com/questions/301924/python-urlliburllib2httplib-confusion#302184">this other answer</a>, since the accepted answer deals with a specific problem involving redirection. However, I recommend reading through all of the answers regardless.</p>
4
2008-11-26T18:06:45Z
[ "python", "urllib2" ]
urllib2 data sending
321,582
<p>I've recently written this with help from SO. Now could someone please tell me how to make it actually log onto the board. It brings up everything just in a non logged in format.</p> <pre><code>import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib2.urlopen("http://www.woarl.com/board/index.php", logindata) pagesource = page.read() print pagesource </code></pre>
2
2008-11-26T17:56:09Z
321,616
<p>If actually look at the page, you see that the login link takes you to <a href="http://www.woarl.com/board/ucp.php?mode=login" rel="nofollow">http://www.woarl.com/board/ucp.php?mode=login</a></p> <p>That page has the login form and submits to <a href="http://www.woarl.com/board/ucp.php?mode=login" rel="nofollow">http://www.woarl.com/board/ucp.php?mode=login</a> again with POST.</p> <p>You'll then have to extract the cookies that are probably set, and put those in a CookieJar or similar.</p>
1
2008-11-26T18:08:05Z
[ "python", "urllib2" ]
urllib2 data sending
321,582
<p>I've recently written this with help from SO. Now could someone please tell me how to make it actually log onto the board. It brings up everything just in a non logged in format.</p> <pre><code>import urllib2, re import urllib, re logindata = urllib.urlencode({'username': 'x', 'password': 'y'}) page = urllib2.urlopen("http://www.woarl.com/board/index.php", logindata) pagesource = page.read() print pagesource </code></pre>
2
2008-11-26T17:56:09Z
322,892
<p>You probably want to create an opener with these handlers and apply it to urllib2. With these applied your cookies are handled and you'll be redirected, if server decides it wants you somewhere else.</p> <pre><code># Create handlers cookieHandler = urllib2.HTTPCookieProcessor() # Needed for cookie handling redirectionHandler = urllib2.HTTPRedirectHandler() # needed for redirection (not needed for javascript redirect?) # Create opener opener = urllib2.build_opener(cookieHandler,redirectionHandler) # Install the opener urllib2.install_opener(opener) </code></pre>
0
2008-11-27T03:46:52Z
[ "python", "urllib2" ]
Application configuration incorrect with Python Imaging Library
321,668
<p>I'm trying to install the Python Imaging Library 1.1.6 for Python 2.6. After downloading the installation executable (Win XP), I receive the following error message:</p> <p>"Application failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem"</p> <p>Any thoughts on what I have done / not done? The application has not been installed, and I can't import the module through the IDLE session. Thoughts?</p>
4
2008-11-26T18:21:07Z
321,702
<p>I am shooting in the dark: could it be <a href="http://effbot.org/zone/python-register.htm" rel="nofollow">this</a>?</p>
-1
2008-11-26T18:34:08Z
[ "python", "image-processing" ]
Application configuration incorrect with Python Imaging Library
321,668
<p>I'm trying to install the Python Imaging Library 1.1.6 for Python 2.6. After downloading the installation executable (Win XP), I receive the following error message:</p> <p>"Application failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem"</p> <p>Any thoughts on what I have done / not done? The application has not been installed, and I can't import the module through the IDLE session. Thoughts?</p>
4
2008-11-26T18:21:07Z
323,097
<p>Install Python "for all users", not "just for me".</p>
1
2008-11-27T07:06:26Z
[ "python", "image-processing" ]
Application configuration incorrect with Python Imaging Library
321,668
<p>I'm trying to install the Python Imaging Library 1.1.6 for Python 2.6. After downloading the installation executable (Win XP), I receive the following error message:</p> <p>"Application failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem"</p> <p>Any thoughts on what I have done / not done? The application has not been installed, and I can't import the module through the IDLE session. Thoughts?</p>
4
2008-11-26T18:21:07Z
325,270
<p>It looks like an SxS ("side-by-side") issue. Probably the runtime libraries PIL is linked against are missing. Try installing a redistributable package of a compiler which was used to build PIL.</p> <p><a href="http://www.microsoft.com/downloads/details.aspx?familyid=200B2FD9-AE1A-4A14-984D-389C36F85647&amp;displaylang=en" rel="nofollow">MSVC 2005 redist</a></p> <p><a href="http://www.microsoft.com/downloads/details.aspx?familyid=D5692CE4-ADAD-4000-ABFE-64628A267EF0&amp;displaylang=en" rel="nofollow">MSVC 2008 redist</a></p>
3
2008-11-28T08:22:03Z
[ "python", "image-processing" ]
Application configuration incorrect with Python Imaging Library
321,668
<p>I'm trying to install the Python Imaging Library 1.1.6 for Python 2.6. After downloading the installation executable (Win XP), I receive the following error message:</p> <p>"Application failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem"</p> <p>Any thoughts on what I have done / not done? The application has not been installed, and I can't import the module through the IDLE session. Thoughts?</p>
4
2008-11-26T18:21:07Z
368,543
<p>I got that same message recently to do with the wxPython library. It was because wxPython had been built using a later version of Visual C++ than I had on my PC. As atzz suggests, one solution is to install the appropriate redistributable package. Try a Google search for 'Microsoft Visual C++ 2008 Redistributable Package' and do the download. If that doesn't work, repeat for the 2005 version.</p>
0
2008-12-15T14:34:10Z
[ "python", "image-processing" ]
Comparing XML in a unit test in Python
321,795
<p>I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in Python, and I'm using ElementTree (not that that really matters here since I'm just dealing with XML in strings at this level).</p>
30
2008-11-26T19:09:08Z
321,845
<p>Use <a href="http://www.logilab.org/859">xmldiff</a>, a python tool that figures out the differences between two similar XML files, the same way that diff does it.</p>
5
2008-11-26T19:19:11Z
[ "python", "xml", "elementtree" ]
Comparing XML in a unit test in Python
321,795
<p>I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in Python, and I'm using ElementTree (not that that really matters here since I'm just dealing with XML in strings at this level).</p>
30
2008-11-26T19:09:08Z
321,893
<p>First normalize 2 XML, then you can compare them. I've used the following using lxml</p> <pre><code> obj1 = objectify.fromstring(expect) expect = etree.tostring(obj1) obj2 = objectify.fromstring(xml) result = etree.tostring(obj2) self.assertEquals(expect, result) </code></pre>
13
2008-11-26T19:35:15Z
[ "python", "xml", "elementtree" ]
Comparing XML in a unit test in Python
321,795
<p>I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in Python, and I'm using ElementTree (not that that really matters here since I'm just dealing with XML in strings at this level).</p>
30
2008-11-26T19:09:08Z
321,941
<p>If the problem is really just the whitespace and attribute order, and you have no other constructs than text and elements to worry about, you can parse the strings using a standard XML parser and compare the nodes manually. Here's an example using minidom, but you could write the same in etree pretty simply:</p> <pre><code>def isEqualXML(a, b): da, db= minidom.parseString(a), minidom.parseString(b) return isEqualElement(da.documentElement, db.documentElement) def isEqualElement(a, b): if a.tagName!=b.tagName: return False if sorted(a.attributes.items())!=sorted(b.attributes.items()): return False if len(a.childNodes)!=len(b.childNodes): return False for ac, bc in zip(a.childNodes, b.childNodes): if ac.nodeType!=bc.nodeType: return False if ac.nodeType==ac.TEXT_NODE and ac.data!=bc.data: return False if ac.nodeType==ac.ELEMENT_NODE and not isEqualElement(ac, bc): return False return True </code></pre> <p>If you need a more thorough equivalence comparison, covering the possibilities of other types of nodes including CDATA, PIs, entity references, comments, doctypes, namespaces and so on, you could use the DOM Level 3 Core method isEqualNode. Neither minidom nor etree have that, but pxdom is one implementation that supports it:</p> <pre><code>def isEqualXML(a, b): da, db= pxdom.parseString(a), pxdom.parseString(a) return da.isEqualNode(db) </code></pre> <p>(You may want to change some of the DOMConfiguration options on the parse if you need to specify whether entity references and CDATA sections match their replaced equivalents.)</p> <p>A slightly more roundabout way of doing it would be to parse, then re-serialise to canonical form and do a string comparison. Again pxdom supports the DOM Level 3 LS option ‘canonical-form’ which you could use to do this; an alternative way using the stdlib's minidom implementation is to use c14n. However you must have the PyXML extensions install for this so you still can't quite do it within the stdlib:</p> <pre><code>from xml.dom.ext import c14n def isEqualXML(a, b): da, bd= minidom.parseString(a), minidom.parseString(b) a, b= c14n.Canonicalize(da), c14n.Canonicalize(db) return a==b </code></pre>
7
2008-11-26T19:56:19Z
[ "python", "xml", "elementtree" ]
Comparing XML in a unit test in Python
321,795
<p>I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in Python, and I'm using ElementTree (not that that really matters here since I'm just dealing with XML in strings at this level).</p>
30
2008-11-26T19:09:08Z
322,088
<p>Why are you examining the XML data at all?</p> <p>The way to test object serialization is to create an instance of the object, serialize it, deserialize it into a new object, and compare the two objects. When you make a change that breaks serialization or deserialization, this test will fail.</p> <p>The only thing checking the XML data is going to find for you is if your serializer is emitting a superset of what the deserializer requires, and the deserializer silently ignores stuff it doesn't expect.</p> <p>Of course, if something else is going to be consuming the serialized data, that's another matter. But in that case, you ought to be thinking about establishing a schema for the XML and validating it.</p>
2
2008-11-26T20:46:45Z
[ "python", "xml", "elementtree" ]
Comparing XML in a unit test in Python
321,795
<p>I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in Python, and I'm using ElementTree (not that that really matters here since I'm just dealing with XML in strings at this level).</p>
30
2008-11-26T19:09:08Z
322,600
<p>The Java component <code>dbUnit</code> does a lot of XML comparisons, so you might find it useful to look at their approach (especially to find any gotchas that they may have already addressed).</p>
0
2008-11-27T00:20:52Z
[ "python", "xml", "elementtree" ]
Comparing XML in a unit test in Python
321,795
<p>I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in Python, and I'm using ElementTree (not that that really matters here since I'm just dealing with XML in strings at this level).</p>
30
2008-11-26T19:09:08Z
7,060,342
<p>This is an old question, but the accepted Kozyarchuk's answer doesn't work for me because of attributes order, and the minidom solution doesn't work as-is either (no idea why, I haven't debugged it). </p> <p>This is what I finally came up with:</p> <pre><code>from doctest import Example from lxml.doctestcompare import LXMLOutputChecker class XmlTest(TestCase): def assertXmlEqual(self, got, want): checker = LXMLOutputChecker() if not checker.check_output(want, got, 0): message = checker.output_difference(Example("", want), got, 0) raise AssertionError(message) </code></pre> <p>This also produces a diff that can be helpful in case of large xml files.</p>
15
2011-08-14T23:05:34Z
[ "python", "xml", "elementtree" ]
Comparing XML in a unit test in Python
321,795
<p>I have an object that can build itself from an XML string, and write itself out to an XML string. I'd like to write a unit test to test round tripping through XML, but I'm having trouble comparing the two XML versions. Whitespace and attribute order seem to be the issues. Any suggestions for how to do this? This is in Python, and I'm using ElementTree (not that that really matters here since I'm just dealing with XML in strings at this level).</p>
30
2008-11-26T19:09:08Z
8,178,899
<p>I also had this problem and did some digging around it today. The <a href="http://stackoverflow.com/questions/321795/comparing-xml-in-a-unit-test-in-python/7060342#7060342"><code>doctestcompare</code> approach</a> may suffice, but I found via <a href="http://blog.ianbicking.org/2007/09/24/lxmlhtml/" rel="nofollow">Ian Bicking</a> that it is based on <code>formencode.doctest_xml_compare</code>. Which appears to now be <a href="https://bitbucket.org/formencode/official-formencode/src/3be5078c6030/formencode/doctest_xml_compare.py#cl-70" rel="nofollow">here</a>. As you can see that is a pretty simple function, unlike <a href="https://github.com/lxml/lxml/blob/master/src/lxml/doctestcompare.py" rel="nofollow"><code>doctestcompare</code></a> (although I guess <code>doctestcompare</code> is collecting all the failures and maybe more sophisticated checking). Anyway copying/importing <code>xml_compare</code> out of <code>formencode</code> may be a good solution.</p>
1
2011-11-18T07:05:26Z
[ "python", "xml", "elementtree" ]
Does c# have anything comparable to Python's list comprehensions
323,032
<p>I want to generate a list in C#. I am missing python's list comprehensions. Is there a c# way to create collections on the fly like list comprehensions or generator statements do in python?</p>
12
2008-11-27T05:55:24Z
323,039
<p>If you are using C# 3.0 (VS2008) then LINQ to Objects can do very similar things:</p> <pre><code>List&lt;Foo&gt; fooList = new List&lt;Foo&gt;(); IEnumerable&lt;Foo&gt; extract = from foo in fooList where foo.Bar &gt; 10 select Foo.Name.ToUpper(); </code></pre>
16
2008-11-27T05:59:36Z
[ "c#", "python", "list" ]
Does c# have anything comparable to Python's list comprehensions
323,032
<p>I want to generate a list in C#. I am missing python's list comprehensions. Is there a c# way to create collections on the fly like list comprehensions or generator statements do in python?</p>
12
2008-11-27T05:55:24Z
323,058
<p>Matt has mentioned query expressions. These are available for LINQ in general, by the way - not just LINQ to Objects. (For example, the same query applied to a LINQ to SQL datacontext would execute the filter and projection on the database.)</p> <p>The query expressions in C# 3 are simply syntactic sugar over writing normal C# code - although query expressions usually end up calling <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx" rel="nofollow">extension methods</a>. (They don't have to, and the compiler doesn't care, but they usually do.) There are various things you can do with collections which aren't available in C# query expressions, but which are supported by method calls, so it's worth being aware of both kinds of syntax. For instance, Matt's query expression of:</p> <pre><code>List&lt;Foo&gt; fooList = new List&lt;Foo&gt;(); IEnumerable&lt;string&gt; extract = from foo in fooList where foo.Bar &gt; 10 select foo.Name.ToUpper(); </code></pre> <p>is "pre-processed" into:</p> <pre><code>List&lt;Foo&gt; fooList = new List&lt;Foo&gt;(); IEnumerable&lt;string&gt; extract = fooList.Where(foo =&gt; foo.Bar &gt; 10) .Select(foo =&gt; foo.Name.ToUpper()); </code></pre> <p>If you want to (say) filter based on the index of the value in the original collection, you can use an <a href="http://msdn.microsoft.com/en-us/library/bb549418.aspx" rel="nofollow">appropriate overload of Where</a> which is unavailable via query expressions:</p> <pre><code>List&lt;Foo&gt; fooList = new List&lt;Foo&gt;(); IEnumerable&lt;string&gt; extract = fooList.Where((foo, index) =&gt; foo.Bar &gt; 10 + index) .Select(foo =&gt; foo.Name.ToUpper()); </code></pre> <p>Or you could find the length of the longest name matching the criteria:</p> <pre><code>List&lt;Foo&gt; fooList = new List&lt;Foo&gt;(); int longestName = fooList.Where((foo, index) =&gt; foo.Bar &gt; 10 + index) .Select(foo =&gt; foo.Name) .Max(); </code></pre> <p>(You don't <em>have</em> to do the projection and max in separate methods - there's a <code>Max</code> overload which takes a projection as well.)</p> <p>My point is that using extension methods you can very easily build up sophisticated queries.</p> <p>You mention Python generators as well - C# has this in the form of <a href="http://stackoverflow.com/questions/317462/some-help-understanding-yield">iterator blocks</a>. Indeed, these are incredibly useful when implementing LINQ-like operators. (Because most of LINQ to Objects is based on extension methods, you can add your own operators which look "native" to LINQ - although you can't change the query expression syntax yourself.)</p>
13
2008-11-27T06:24:33Z
[ "c#", "python", "list" ]
Does c# have anything comparable to Python's list comprehensions
323,032
<p>I want to generate a list in C#. I am missing python's list comprehensions. Is there a c# way to create collections on the fly like list comprehensions or generator statements do in python?</p>
12
2008-11-27T05:55:24Z
2,739,426
<p><a href="http://msdn.microsoft.com/en-us/library/73fe8cwf.aspx" rel="nofollow"><code>List&lt;T&gt;.ConvertAll</code></a> behaves just like list comprehensions by performing the same operation on every item on an existing list and then returning a new collection. This is an alternative to using Linq especially if you are still using .NET 2.0.</p> <p>In Python, a simple list comprehension example:</p> <pre><code>&gt;&gt;&gt; foo = [1, 2, 3] &gt;&gt;&gt; bar = [x * 2 for x in foo] &gt;&gt;&gt; bar [2, 4, 6] </code></pre> <p>For C# 3.0, you can pass a lambda function specifying what type of mapping function is needed.</p> <pre><code>public static void Main() { var foo = new List&lt;int&gt;{ 1, 2, 3}; var bar = foo.ConvertAll(x =&gt; x * 2); // list comprehension foreach (var x in bar) { Console.WriteLine(x); // should print 2 4 6 } } </code></pre> <p>For C# 2.0, you can use an anonymous method with the <code>Converter</code> delegate to perform the equivalent.</p> <pre><code>public static void Main() { List&lt;int&gt; foo = new List&lt;int&gt;(new int[]{ 1, 2, 3}); List&lt;int&gt; bar = foo.ConvertAll(new Converter&lt;int, int&gt;(delegate(int x){ return x * 2; })); // list comprehension foreach (int x in bar) { Console.WriteLine(x); // should print 2 4 6 } } </code></pre> <p>(Note: the same can be done with Arrays using <a href="http://msdn.microsoft.com/en-us/library/exc45z53.aspx" rel="nofollow"><code>Array.ConvertAll</code></a></p>
4
2010-04-29T17:25:59Z
[ "c#", "python", "list" ]
Does c# have anything comparable to Python's list comprehensions
323,032
<p>I want to generate a list in C#. I am missing python's list comprehensions. Is there a c# way to create collections on the fly like list comprehensions or generator statements do in python?</p>
12
2008-11-27T05:55:24Z
31,141,556
<p>There's this:</p> <pre class="lang-cs prettyprint-override"><code>new List&lt;FooBar&gt;{new Foo(), new Bar()} </code></pre> <p>which is only a little longer than its python equivalent:</p> <pre class="lang-py prettyprint-override"><code>[Foo(), Bar()] </code></pre> <p>And then there is this:</p> <pre class="lang-cs prettyprint-override"><code>public IEnumerable&lt;FooBar&gt; myFooBarGenerator() { yield return new Foo(); yield return new Bar(); } </code></pre> <p>which is the python equivalent of:</p> <pre class="lang-py prettyprint-override"><code>def myFooBarGenerator(): yield Foo() yield Bar() </code></pre>
0
2015-06-30T14:48:38Z
[ "c#", "python", "list" ]
py2exe fails to generate an executable
323,424
<p>I am using python 2.6 on XP. I have just installed py2exe, and I can successfully create a simple hello.exe from a hello.py. However, when I try using py2exe on my real program, py2exe produces a few information messages but fails to generate anything in the dist folder. </p> <p>My setup.py looks like this:</p> <pre><code>from distutils.core import setup import py2exe setup(console=['ServerManager.py']) </code></pre> <p>and the py2exe output looks like this:</p> <pre class="lang-none prettyprint-override"><code>python setup.py py2exe running py2exe creating C:\DevSource\Scripts\ServerManager\build creating C:\DevSource\Scripts\ServerManager\build\bdist.win32 ... ... creating C:\DevSource\Scripts\ServerManager\dist *** searching for required modules *** *** parsing results *** creating python loader for extension 'wx._misc_' (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_misc_.pyd -&gt; wx._misc_.pyd) creating python loader for extension 'lxml.etree' (C:\Python26\lib\site-packages\lxml\etree.pyd -&gt; lxml.etree.pyd) ... ... creating python loader for extension 'bz2' (C:\Python26\DLLs\bz2.pyd -&gt; bz2.pyd) *** finding dlls needed *** </code></pre> <p>py2exe seems to have found all my imports (though I was a bit surprised to see win32 mentioned, as I am not explicitly importing it). Also, my program starts up quite happily with this command:</p> <pre class="lang-none prettyprint-override"><code>python ServerManager.py </code></pre> <p>Clearly I am doing something fundamentally wrong, but in the absence of any error messages from py2exe I have no idea what.</p>
48
2008-11-27T10:31:51Z
325,135
<p>The output says you're using WX. Try running py2exe with your script specified as a GUI app instead of console. If I'm not mistaken, that tends to cause problems with py2exe.</p>
0
2008-11-28T06:05:46Z
[ "python", "wxpython", "py2exe" ]
py2exe fails to generate an executable
323,424
<p>I am using python 2.6 on XP. I have just installed py2exe, and I can successfully create a simple hello.exe from a hello.py. However, when I try using py2exe on my real program, py2exe produces a few information messages but fails to generate anything in the dist folder. </p> <p>My setup.py looks like this:</p> <pre><code>from distutils.core import setup import py2exe setup(console=['ServerManager.py']) </code></pre> <p>and the py2exe output looks like this:</p> <pre class="lang-none prettyprint-override"><code>python setup.py py2exe running py2exe creating C:\DevSource\Scripts\ServerManager\build creating C:\DevSource\Scripts\ServerManager\build\bdist.win32 ... ... creating C:\DevSource\Scripts\ServerManager\dist *** searching for required modules *** *** parsing results *** creating python loader for extension 'wx._misc_' (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_misc_.pyd -&gt; wx._misc_.pyd) creating python loader for extension 'lxml.etree' (C:\Python26\lib\site-packages\lxml\etree.pyd -&gt; lxml.etree.pyd) ... ... creating python loader for extension 'bz2' (C:\Python26\DLLs\bz2.pyd -&gt; bz2.pyd) *** finding dlls needed *** </code></pre> <p>py2exe seems to have found all my imports (though I was a bit surprised to see win32 mentioned, as I am not explicitly importing it). Also, my program starts up quite happily with this command:</p> <pre class="lang-none prettyprint-override"><code>python ServerManager.py </code></pre> <p>Clearly I am doing something fundamentally wrong, but in the absence of any error messages from py2exe I have no idea what.</p>
48
2008-11-27T10:31:51Z
325,456
<p>I've discovered that py2exe works just fine if I comment out the part of my program that uses wxPython. Also, when I use py2exe on the 'simple' sample that comes with its download (i.e. in Python26\Lib\site-packages\py2exe\samples\simple), I get this error message:</p> <pre><code>*** finding dlls needed *** error: MSVCP90.dll: No such file or directory </code></pre> <p>So something about wxPython makes py2exe think I need a Visual Studio 2008 DLL. I don't have VS2008, and yet my program works perfectly well as a directory of Python modules. I found a copy of MSVCP90.DLL on the web, installed it in Python26/DLLs, and py2exe now works fine. </p> <p>I still don't understand where this dependency has come from, since I can run my code perfectly okay without py2exe. It's also annoying that py2exe didn't give me an error message like it did with the test_wx.py sample.</p> <p>Further update: When I tried to run the output from py2exe on another PC, I discovered that it needed to have MSVCR90.DLL installed; so if your target PC hasn't got Visual C++ 2008 already installed, I recommend you download and install the <a href="http://www.microsoft.com/download/en/details.aspx?displaylang=en&amp;id=29">Microsoft Visual C++ 2008 Redistributable Package</a>.</p>
35
2008-11-28T10:36:56Z
[ "python", "wxpython", "py2exe" ]
py2exe fails to generate an executable
323,424
<p>I am using python 2.6 on XP. I have just installed py2exe, and I can successfully create a simple hello.exe from a hello.py. However, when I try using py2exe on my real program, py2exe produces a few information messages but fails to generate anything in the dist folder. </p> <p>My setup.py looks like this:</p> <pre><code>from distutils.core import setup import py2exe setup(console=['ServerManager.py']) </code></pre> <p>and the py2exe output looks like this:</p> <pre class="lang-none prettyprint-override"><code>python setup.py py2exe running py2exe creating C:\DevSource\Scripts\ServerManager\build creating C:\DevSource\Scripts\ServerManager\build\bdist.win32 ... ... creating C:\DevSource\Scripts\ServerManager\dist *** searching for required modules *** *** parsing results *** creating python loader for extension 'wx._misc_' (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_misc_.pyd -&gt; wx._misc_.pyd) creating python loader for extension 'lxml.etree' (C:\Python26\lib\site-packages\lxml\etree.pyd -&gt; lxml.etree.pyd) ... ... creating python loader for extension 'bz2' (C:\Python26\DLLs\bz2.pyd -&gt; bz2.pyd) *** finding dlls needed *** </code></pre> <p>py2exe seems to have found all my imports (though I was a bit surprised to see win32 mentioned, as I am not explicitly importing it). Also, my program starts up quite happily with this command:</p> <pre class="lang-none prettyprint-override"><code>python ServerManager.py </code></pre> <p>Clearly I am doing something fundamentally wrong, but in the absence of any error messages from py2exe I have no idea what.</p>
48
2008-11-27T10:31:51Z
774,715
<p>I put this in all my setup.py scripts:</p> <pre><code>distutils.core.setup( options = { "py2exe": { "dll_excludes": ["MSVCP90.dll"] } }, ... ) </code></pre> <p>This keeps py2exe quiet, but you still need to make sure that dll is on the user's machine.</p>
37
2009-04-21T21:29:58Z
[ "python", "wxpython", "py2exe" ]
py2exe fails to generate an executable
323,424
<p>I am using python 2.6 on XP. I have just installed py2exe, and I can successfully create a simple hello.exe from a hello.py. However, when I try using py2exe on my real program, py2exe produces a few information messages but fails to generate anything in the dist folder. </p> <p>My setup.py looks like this:</p> <pre><code>from distutils.core import setup import py2exe setup(console=['ServerManager.py']) </code></pre> <p>and the py2exe output looks like this:</p> <pre class="lang-none prettyprint-override"><code>python setup.py py2exe running py2exe creating C:\DevSource\Scripts\ServerManager\build creating C:\DevSource\Scripts\ServerManager\build\bdist.win32 ... ... creating C:\DevSource\Scripts\ServerManager\dist *** searching for required modules *** *** parsing results *** creating python loader for extension 'wx._misc_' (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_misc_.pyd -&gt; wx._misc_.pyd) creating python loader for extension 'lxml.etree' (C:\Python26\lib\site-packages\lxml\etree.pyd -&gt; lxml.etree.pyd) ... ... creating python loader for extension 'bz2' (C:\Python26\DLLs\bz2.pyd -&gt; bz2.pyd) *** finding dlls needed *** </code></pre> <p>py2exe seems to have found all my imports (though I was a bit surprised to see win32 mentioned, as I am not explicitly importing it). Also, my program starts up quite happily with this command:</p> <pre class="lang-none prettyprint-override"><code>python ServerManager.py </code></pre> <p>Clearly I am doing something fundamentally wrong, but in the absence of any error messages from py2exe I have no idea what.</p>
48
2008-11-27T10:31:51Z
819,083
<p>我的wxpython app也遇到了這樣的問題,采用Bill的方式解決了該問題。thanks bill</p> <p>setup.py文件內容如下:</p> <pre><code>#coding=utf-8 from distutils.core import setup import py2exe setup(windows=['main.py'], options = { "py2exe":{"dll_excludes":["MSVCP90.dll"]}}) </code></pre>
0
2009-05-04T07:11:33Z
[ "python", "wxpython", "py2exe" ]
py2exe fails to generate an executable
323,424
<p>I am using python 2.6 on XP. I have just installed py2exe, and I can successfully create a simple hello.exe from a hello.py. However, when I try using py2exe on my real program, py2exe produces a few information messages but fails to generate anything in the dist folder. </p> <p>My setup.py looks like this:</p> <pre><code>from distutils.core import setup import py2exe setup(console=['ServerManager.py']) </code></pre> <p>and the py2exe output looks like this:</p> <pre class="lang-none prettyprint-override"><code>python setup.py py2exe running py2exe creating C:\DevSource\Scripts\ServerManager\build creating C:\DevSource\Scripts\ServerManager\build\bdist.win32 ... ... creating C:\DevSource\Scripts\ServerManager\dist *** searching for required modules *** *** parsing results *** creating python loader for extension 'wx._misc_' (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_misc_.pyd -&gt; wx._misc_.pyd) creating python loader for extension 'lxml.etree' (C:\Python26\lib\site-packages\lxml\etree.pyd -&gt; lxml.etree.pyd) ... ... creating python loader for extension 'bz2' (C:\Python26\DLLs\bz2.pyd -&gt; bz2.pyd) *** finding dlls needed *** </code></pre> <p>py2exe seems to have found all my imports (though I was a bit surprised to see win32 mentioned, as I am not explicitly importing it). Also, my program starts up quite happily with this command:</p> <pre class="lang-none prettyprint-override"><code>python ServerManager.py </code></pre> <p>Clearly I am doing something fundamentally wrong, but in the absence of any error messages from py2exe I have no idea what.</p>
48
2008-11-27T10:31:51Z
1,433,894
<pre><code>import sys sys.path.append('c:/Program Files/Microsoft Visual Studio 9.0/VC/redist/x86/Microsoft.VC90.CRT') </code></pre>
-2
2009-09-16T15:58:53Z
[ "python", "wxpython", "py2exe" ]
py2exe fails to generate an executable
323,424
<p>I am using python 2.6 on XP. I have just installed py2exe, and I can successfully create a simple hello.exe from a hello.py. However, when I try using py2exe on my real program, py2exe produces a few information messages but fails to generate anything in the dist folder. </p> <p>My setup.py looks like this:</p> <pre><code>from distutils.core import setup import py2exe setup(console=['ServerManager.py']) </code></pre> <p>and the py2exe output looks like this:</p> <pre class="lang-none prettyprint-override"><code>python setup.py py2exe running py2exe creating C:\DevSource\Scripts\ServerManager\build creating C:\DevSource\Scripts\ServerManager\build\bdist.win32 ... ... creating C:\DevSource\Scripts\ServerManager\dist *** searching for required modules *** *** parsing results *** creating python loader for extension 'wx._misc_' (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_misc_.pyd -&gt; wx._misc_.pyd) creating python loader for extension 'lxml.etree' (C:\Python26\lib\site-packages\lxml\etree.pyd -&gt; lxml.etree.pyd) ... ... creating python loader for extension 'bz2' (C:\Python26\DLLs\bz2.pyd -&gt; bz2.pyd) *** finding dlls needed *** </code></pre> <p>py2exe seems to have found all my imports (though I was a bit surprised to see win32 mentioned, as I am not explicitly importing it). Also, my program starts up quite happily with this command:</p> <pre class="lang-none prettyprint-override"><code>python ServerManager.py </code></pre> <p>Clearly I am doing something fundamentally wrong, but in the absence of any error messages from py2exe I have no idea what.</p>
48
2008-11-27T10:31:51Z
1,570,163
<p>It looks like this is only a dependency for Python 2.6. I wasn't getting this error under 2.5, but after the upgrade I am.</p> <p>This email thread has some background for why the problem exists and how to fix it:<br> <a href="http://www.nabble.com/py2exe,-Py26,-wxPython-and-dll-td20556399.html" rel="nofollow">http://www.nabble.com/py2exe,-Py26,-wxPython-and-dll-td20556399.html</a></p> <p>I didn't want to have to install the vcredist. My application currently requires no installation and can be run by non-administrators, which is behavior I don't want to lose. So I followed the suggestions in the links and got the necessary Microsoft.VC90.CRT.manifest and msvcr90.dll by installing Python "for this user only". I also needed msvcp90.dll that I found in the WinSxS folder of an "all users" Python 2.6 install. Since I already had two of the three, I included msvcm90.dll to prevent future errors though I didn't get any immediate errors when I left it out. I put the manifest and the three DLLs in the libs folder used by my frozen application.</p> <p>The trick I had to perform was including an additional copy of the manifest and msvcr90.dll in the root of my application folder next to by py2exe generated executable. This copy of the DLL is used to bootstrap the application, but then it appears to only look in the libs folder.</p> <p>Hopefully that discovery helps someone else out.</p> <p>Also, I had the same problem with having py2exe log a real error message. Then I realized that stderr wasn't getting redirected into my log file. Add "> build.log 2>&amp;1" on the command line where you invoke py2exe.</p>
6
2009-10-15T03:37:08Z
[ "python", "wxpython", "py2exe" ]
py2exe fails to generate an executable
323,424
<p>I am using python 2.6 on XP. I have just installed py2exe, and I can successfully create a simple hello.exe from a hello.py. However, when I try using py2exe on my real program, py2exe produces a few information messages but fails to generate anything in the dist folder. </p> <p>My setup.py looks like this:</p> <pre><code>from distutils.core import setup import py2exe setup(console=['ServerManager.py']) </code></pre> <p>and the py2exe output looks like this:</p> <pre class="lang-none prettyprint-override"><code>python setup.py py2exe running py2exe creating C:\DevSource\Scripts\ServerManager\build creating C:\DevSource\Scripts\ServerManager\build\bdist.win32 ... ... creating C:\DevSource\Scripts\ServerManager\dist *** searching for required modules *** *** parsing results *** creating python loader for extension 'wx._misc_' (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_misc_.pyd -&gt; wx._misc_.pyd) creating python loader for extension 'lxml.etree' (C:\Python26\lib\site-packages\lxml\etree.pyd -&gt; lxml.etree.pyd) ... ... creating python loader for extension 'bz2' (C:\Python26\DLLs\bz2.pyd -&gt; bz2.pyd) *** finding dlls needed *** </code></pre> <p>py2exe seems to have found all my imports (though I was a bit surprised to see win32 mentioned, as I am not explicitly importing it). Also, my program starts up quite happily with this command:</p> <pre class="lang-none prettyprint-override"><code>python ServerManager.py </code></pre> <p>Clearly I am doing something fundamentally wrong, but in the absence of any error messages from py2exe I have no idea what.</p>
48
2008-11-27T10:31:51Z
2,630,448
<p>Just for your info, for me it worked to copy the files </p> <p>Microsoft.VC90.CRT.manifest msvcr90.dll</p> <p>into the directory with the .exe on the user's machine (who has no python or VC redistributable installed).</p> <p>Thanks for all the hints here!</p>
2
2010-04-13T14:43:32Z
[ "python", "wxpython", "py2exe" ]
py2exe fails to generate an executable
323,424
<p>I am using python 2.6 on XP. I have just installed py2exe, and I can successfully create a simple hello.exe from a hello.py. However, when I try using py2exe on my real program, py2exe produces a few information messages but fails to generate anything in the dist folder. </p> <p>My setup.py looks like this:</p> <pre><code>from distutils.core import setup import py2exe setup(console=['ServerManager.py']) </code></pre> <p>and the py2exe output looks like this:</p> <pre class="lang-none prettyprint-override"><code>python setup.py py2exe running py2exe creating C:\DevSource\Scripts\ServerManager\build creating C:\DevSource\Scripts\ServerManager\build\bdist.win32 ... ... creating C:\DevSource\Scripts\ServerManager\dist *** searching for required modules *** *** parsing results *** creating python loader for extension 'wx._misc_' (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_misc_.pyd -&gt; wx._misc_.pyd) creating python loader for extension 'lxml.etree' (C:\Python26\lib\site-packages\lxml\etree.pyd -&gt; lxml.etree.pyd) ... ... creating python loader for extension 'bz2' (C:\Python26\DLLs\bz2.pyd -&gt; bz2.pyd) *** finding dlls needed *** </code></pre> <p>py2exe seems to have found all my imports (though I was a bit surprised to see win32 mentioned, as I am not explicitly importing it). Also, my program starts up quite happily with this command:</p> <pre class="lang-none prettyprint-override"><code>python ServerManager.py </code></pre> <p>Clearly I am doing something fundamentally wrong, but in the absence of any error messages from py2exe I have no idea what.</p>
48
2008-11-27T10:31:51Z
4,216,212
<p>wxPython has nothing to do with it. Before Python 2.6, Python used Visual Studio 2003 as their Windows compiler. Beginning with 2.6, they switched to Visual Studio 2008, which requires a manifest file in some situations. This has been well documented. See the following links:</p> <p><a href="http://wiki.wxpython.org/py2exe">http://wiki.wxpython.org/py2exe</a></p> <p><a href="http://py2exe.org/index.cgi/Tutorial#Step52">http://py2exe.org/index.cgi/Tutorial#Step52</a></p> <p>Also, if you're creating a wxPython application with py2exe, then you want to set the windows parameter, NOT the console one. Maybe my tutorial will help you:</p> <p><a href="http://www.blog.pythonlibrary.org/2010/07/31/a-py2exe-tutorial-build-a-binary-series/">http://www.blog.pythonlibrary.org/2010/07/31/a-py2exe-tutorial-build-a-binary-series/</a></p>
10
2010-11-18T15:07:21Z
[ "python", "wxpython", "py2exe" ]
py2exe fails to generate an executable
323,424
<p>I am using python 2.6 on XP. I have just installed py2exe, and I can successfully create a simple hello.exe from a hello.py. However, when I try using py2exe on my real program, py2exe produces a few information messages but fails to generate anything in the dist folder. </p> <p>My setup.py looks like this:</p> <pre><code>from distutils.core import setup import py2exe setup(console=['ServerManager.py']) </code></pre> <p>and the py2exe output looks like this:</p> <pre class="lang-none prettyprint-override"><code>python setup.py py2exe running py2exe creating C:\DevSource\Scripts\ServerManager\build creating C:\DevSource\Scripts\ServerManager\build\bdist.win32 ... ... creating C:\DevSource\Scripts\ServerManager\dist *** searching for required modules *** *** parsing results *** creating python loader for extension 'wx._misc_' (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_misc_.pyd -&gt; wx._misc_.pyd) creating python loader for extension 'lxml.etree' (C:\Python26\lib\site-packages\lxml\etree.pyd -&gt; lxml.etree.pyd) ... ... creating python loader for extension 'bz2' (C:\Python26\DLLs\bz2.pyd -&gt; bz2.pyd) *** finding dlls needed *** </code></pre> <p>py2exe seems to have found all my imports (though I was a bit surprised to see win32 mentioned, as I am not explicitly importing it). Also, my program starts up quite happily with this command:</p> <pre class="lang-none prettyprint-override"><code>python ServerManager.py </code></pre> <p>Clearly I am doing something fundamentally wrong, but in the absence of any error messages from py2exe I have no idea what.</p>
48
2008-11-27T10:31:51Z
11,906,634
<p>Try this: <a href="http://www.py2exe.org/index.cgi/Tutorial#Step52" rel="nofollow">http://www.py2exe.org/index.cgi/Tutorial#Step52</a></p> <p>It worked for me</p>
1
2012-08-10T17:38:41Z
[ "python", "wxpython", "py2exe" ]
py2exe fails to generate an executable
323,424
<p>I am using python 2.6 on XP. I have just installed py2exe, and I can successfully create a simple hello.exe from a hello.py. However, when I try using py2exe on my real program, py2exe produces a few information messages but fails to generate anything in the dist folder. </p> <p>My setup.py looks like this:</p> <pre><code>from distutils.core import setup import py2exe setup(console=['ServerManager.py']) </code></pre> <p>and the py2exe output looks like this:</p> <pre class="lang-none prettyprint-override"><code>python setup.py py2exe running py2exe creating C:\DevSource\Scripts\ServerManager\build creating C:\DevSource\Scripts\ServerManager\build\bdist.win32 ... ... creating C:\DevSource\Scripts\ServerManager\dist *** searching for required modules *** *** parsing results *** creating python loader for extension 'wx._misc_' (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_misc_.pyd -&gt; wx._misc_.pyd) creating python loader for extension 'lxml.etree' (C:\Python26\lib\site-packages\lxml\etree.pyd -&gt; lxml.etree.pyd) ... ... creating python loader for extension 'bz2' (C:\Python26\DLLs\bz2.pyd -&gt; bz2.pyd) *** finding dlls needed *** </code></pre> <p>py2exe seems to have found all my imports (though I was a bit surprised to see win32 mentioned, as I am not explicitly importing it). Also, my program starts up quite happily with this command:</p> <pre class="lang-none prettyprint-override"><code>python ServerManager.py </code></pre> <p>Clearly I am doing something fundamentally wrong, but in the absence of any error messages from py2exe I have no idea what.</p>
48
2008-11-27T10:31:51Z
12,577,412
<pre><code>import sys sys.path.append('C:\\WINDOWS\\WinSxS\\x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.4148_none_5090ab56bcba71c2') </code></pre> <p>On each Windows, you can find the file <code>MSVCP90.dll</code> in some subdirectory in <code>C:\\WINDOWS\\WinSxS\\</code> </p> <p>In my case, the directory was: <code>x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.4148_none_5090ab56bcba71c2</code>. </p> <p>Go to <code>C:\\WINDOWS\\WinSxS\\</code> and use windows file search to find <code>MSVCP90.dll</code>.</p>
5
2012-09-25T06:37:18Z
[ "python", "wxpython", "py2exe" ]
py2exe fails to generate an executable
323,424
<p>I am using python 2.6 on XP. I have just installed py2exe, and I can successfully create a simple hello.exe from a hello.py. However, when I try using py2exe on my real program, py2exe produces a few information messages but fails to generate anything in the dist folder. </p> <p>My setup.py looks like this:</p> <pre><code>from distutils.core import setup import py2exe setup(console=['ServerManager.py']) </code></pre> <p>and the py2exe output looks like this:</p> <pre class="lang-none prettyprint-override"><code>python setup.py py2exe running py2exe creating C:\DevSource\Scripts\ServerManager\build creating C:\DevSource\Scripts\ServerManager\build\bdist.win32 ... ... creating C:\DevSource\Scripts\ServerManager\dist *** searching for required modules *** *** parsing results *** creating python loader for extension 'wx._misc_' (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_misc_.pyd -&gt; wx._misc_.pyd) creating python loader for extension 'lxml.etree' (C:\Python26\lib\site-packages\lxml\etree.pyd -&gt; lxml.etree.pyd) ... ... creating python loader for extension 'bz2' (C:\Python26\DLLs\bz2.pyd -&gt; bz2.pyd) *** finding dlls needed *** </code></pre> <p>py2exe seems to have found all my imports (though I was a bit surprised to see win32 mentioned, as I am not explicitly importing it). Also, my program starts up quite happily with this command:</p> <pre class="lang-none prettyprint-override"><code>python ServerManager.py </code></pre> <p>Clearly I am doing something fundamentally wrong, but in the absence of any error messages from py2exe I have no idea what.</p>
48
2008-11-27T10:31:51Z
28,473,909
<p>There is some info on the wxPython wiki.</p> <p><a href="http://wiki.wxpython.org/Deployment" rel="nofollow">Deploy a Python app</a></p> <p><a href="http://wiki.wxpython.org/py2exe-python26" rel="nofollow">py2exe with wxPython and Python 2.6</a></p>
-1
2015-02-12T09:35:53Z
[ "python", "wxpython", "py2exe" ]
py2exe fails to generate an executable
323,424
<p>I am using python 2.6 on XP. I have just installed py2exe, and I can successfully create a simple hello.exe from a hello.py. However, when I try using py2exe on my real program, py2exe produces a few information messages but fails to generate anything in the dist folder. </p> <p>My setup.py looks like this:</p> <pre><code>from distutils.core import setup import py2exe setup(console=['ServerManager.py']) </code></pre> <p>and the py2exe output looks like this:</p> <pre class="lang-none prettyprint-override"><code>python setup.py py2exe running py2exe creating C:\DevSource\Scripts\ServerManager\build creating C:\DevSource\Scripts\ServerManager\build\bdist.win32 ... ... creating C:\DevSource\Scripts\ServerManager\dist *** searching for required modules *** *** parsing results *** creating python loader for extension 'wx._misc_' (C:\Python26\lib\site-packages\wx-2.8-msw-unicode\wx\_misc_.pyd -&gt; wx._misc_.pyd) creating python loader for extension 'lxml.etree' (C:\Python26\lib\site-packages\lxml\etree.pyd -&gt; lxml.etree.pyd) ... ... creating python loader for extension 'bz2' (C:\Python26\DLLs\bz2.pyd -&gt; bz2.pyd) *** finding dlls needed *** </code></pre> <p>py2exe seems to have found all my imports (though I was a bit surprised to see win32 mentioned, as I am not explicitly importing it). Also, my program starts up quite happily with this command:</p> <pre class="lang-none prettyprint-override"><code>python ServerManager.py </code></pre> <p>Clearly I am doing something fundamentally wrong, but in the absence of any error messages from py2exe I have no idea what.</p>
48
2008-11-27T10:31:51Z
28,651,480
<p>On my win8.1, I do not find the path</p> <blockquote> <p>c:/Program Files/Microsoft Visual Studio 9.0/VC/redist/x86/Microsoft.VC90.CRT</p> </blockquote> <p>On the contrary , the dll is found in </p> <blockquote> <p>C:/WINDOWS/WinSxS/x86_Microsoft.VC90.CRT_XXXXXXX</p> </blockquote> <p>The XXX may vary according to your PC</p> <p>You may search in the path , then add the path in you setup.py</p> <pre><code>import sys sys.path.append('C:/WINDOWS/WinSxS/x86_Microsoft.VC90.CRT_XXXXXXX') </code></pre>
-1
2015-02-21T21:20:54Z
[ "python", "wxpython", "py2exe" ]
How to get the name of an open file?
323,515
<p>I'm trying to store in a variable the name of the current file that I've opened from a folder...</p> <p>How can I do that? I've tried cwd = os.getcwd() but this only gives me the path of the folder, and I need to store the name of the opened file...</p> <p>Can you please help me?</p> <p>Thanks.</p>
13
2008-11-27T11:28:25Z
323,522
<pre><code>Python 2.5.1 (r251:54863, Jul 31 2008, 22:53:39) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; f = open('generic.png','r') &gt;&gt;&gt; f.name 'generic.png' </code></pre>
33
2008-11-27T11:30:31Z
[ "python", "file" ]
How to get the name of an open file?
323,515
<p>I'm trying to store in a variable the name of the current file that I've opened from a folder...</p> <p>How can I do that? I've tried cwd = os.getcwd() but this only gives me the path of the folder, and I need to store the name of the opened file...</p> <p>Can you please help me?</p> <p>Thanks.</p>
13
2008-11-27T11:28:25Z
324,326
<p>Maybe this script is what you want?</p> <pre><code>import sys, os print sys.argv[0] print os.path.basename(sys.argv[0]) </code></pre> <p>When I run the above script I get;</p> <pre><code>D:\UserData\workspace\temp\Script1.py Script1.py </code></pre>
1
2008-11-27T17:36:44Z
[ "python", "file" ]
How to get the name of an open file?
323,515
<p>I'm trying to store in a variable the name of the current file that I've opened from a folder...</p> <p>How can I do that? I've tried cwd = os.getcwd() but this only gives me the path of the folder, and I need to store the name of the opened file...</p> <p>Can you please help me?</p> <p>Thanks.</p>
13
2008-11-27T11:28:25Z
24,144,992
<p>One more useful trick to add. I agree with original correct answer, however if you're like me came to this page wanting the filename only without the rest of the path, this works well.</p> <pre><code>&gt;&gt;&gt; f = open('/tmp/generic.png','r') &gt;&gt;&gt; f.name '/tmp/generic.png' &gt;&gt;&gt; import os &gt;&gt;&gt; os.path.basename(f.name) 'generic.png' </code></pre>
13
2014-06-10T15:30:11Z
[ "python", "file" ]
Eclipse (pydev): Is it possible to assign a shortcut to send selection to the python console?
323,581
<p>Question so easy that fitted in the title :) Eclipse (pydev): Is it possible to assign a shortcut to send selection to the python console?</p>
4
2008-11-27T12:10:53Z
323,789
<p>You can only assign shortcuts to "actions". Actions bound to buttons (for example, the toolbar) and menus. If you have a menu for this, you can bind a key to it. If not, then you will have to open an enhancement request in the pydev project.</p>
1
2008-11-27T13:36:39Z
[ "python", "ide" ]
Eclipse (pydev): Is it possible to assign a shortcut to send selection to the python console?
323,581
<p>Question so easy that fitted in the title :) Eclipse (pydev): Is it possible to assign a shortcut to send selection to the python console?</p>
4
2008-11-27T12:10:53Z
1,399,786
<p>If you mean to the interactive console, use ctrl+alt+enter in the pydev editor (version 1.5).</p> <p>That action does a number of things:</p> <ol> <li>opens an interactive console view if it's not opened already</li> <li>sends the selected text to the console</li> <li>makes an execfile of the current editor (if no text is selected)</li> </ol>
1
2009-09-09T13:48:15Z
[ "python", "ide" ]
Python list slice syntax used for no obvious reason
323,689
<p>I occasionally see the list slice syntax used in Python code like this:</p> <pre><code>newList = oldList[:] </code></pre> <p>Surely this is just the same as:</p> <pre><code>newList = oldList </code></pre> <p>Or am I missing something?</p>
31
2008-11-27T12:57:05Z
323,698
<p><code>[:]</code> <a href="http://en.wikipedia.org/wiki/Deep_copy#Shallow_copy">Shallow copies</a> the list, making a copy of the list structure containing references to the original list members. This means that operations on the copy do not affect the structure of the original. However, if you do something to the list members, both lists still refer to them, so the updates will show up if the members are accessed through the original. </p> <p>A <a href="http://en.wikipedia.org/wiki/Deep_copy#Deep_copy">Deep Copy</a> would make copies of all the list members as well.</p> <p>The code snippet below shows a shallow copy in action.</p> <pre><code># ================================================================ # === ShallowCopy.py ============================================= # ================================================================ # class Foo: def __init__(self, data): self._data = data aa = Foo ('aaa') bb = Foo ('bbb') # The initial list has two elements containing 'aaa' and 'bbb' OldList = [aa,bb] print OldList[0]._data # The shallow copy makes a new list pointing to the old elements NewList = OldList[:] print NewList[0]._data # Updating one of the elements through the new list sees the # change reflected when you access that element through the # old list. NewList[0]._data = 'xxx' print OldList[0]._data # Updating the new list to point to something new is not reflected # in the old list. NewList[0] = Foo ('ccc') print NewList[0]._data print OldList[0]._data </code></pre> <p>Running it in a python shell gives the following transcript. We can see the list being made with copies of the old objects. One of the objects can have its state updated by reference through the old list, and the updates can be seen when the object is accessed through the old list. Finally, changing a reference in the new list can be seen to not reflect in the old list, as the new list is now referring to a different object.</p> <pre><code>&gt;&gt;&gt; # ================================================================ ... # === ShallowCopy.py ============================================= ... # ================================================================ ... # ... class Foo: ... def __init__(self, data): ... self._data = data ... &gt;&gt;&gt; aa = Foo ('aaa') &gt;&gt;&gt; bb = Foo ('bbb') &gt;&gt;&gt; &gt;&gt;&gt; # The initial list has two elements containing 'aaa' and 'bbb' ... OldList = [aa,bb] &gt;&gt;&gt; print OldList[0]._data aaa &gt;&gt;&gt; &gt;&gt;&gt; # The shallow copy makes a new list pointing to the old elements ... NewList = OldList[:] &gt;&gt;&gt; print NewList[0]._data aaa &gt;&gt;&gt; &gt;&gt;&gt; # Updating one of the elements through the new list sees the ... # change reflected when you access that element through the ... # old list. ... NewList[0]._data = 'xxx' &gt;&gt;&gt; print OldList[0]._data xxx &gt;&gt;&gt; &gt;&gt;&gt; # Updating the new list to point to something new is not reflected ... # in the old list. ... NewList[0] = Foo ('ccc') &gt;&gt;&gt; print NewList[0]._data ccc &gt;&gt;&gt; print OldList[0]._data xxx </code></pre>
48
2008-11-27T13:00:31Z
[ "python", "list", "shallow-copy" ]
Python list slice syntax used for no obvious reason
323,689
<p>I occasionally see the list slice syntax used in Python code like this:</p> <pre><code>newList = oldList[:] </code></pre> <p>Surely this is just the same as:</p> <pre><code>newList = oldList </code></pre> <p>Or am I missing something?</p>
31
2008-11-27T12:57:05Z
323,733
<p>Like NXC said, Python variable names actually point to an object, and not a specific spot in memory.</p> <p><code>newList = oldList</code> would create two different variables that point to the same object, therefore, changing <code>oldList</code> would also change <code>newList</code>.</p> <p>However, when you do <code>newList = oldList[:]</code>, it "slices" the list, and creates a new list. The default values for <code>[:]</code> are 0 and the end of the list, so it copies everything. Therefore, it creates a new list with all the data contained in the first one, but both can be altered without changing the other.</p>
44
2008-11-27T13:13:58Z
[ "python", "list", "shallow-copy" ]
Python list slice syntax used for no obvious reason
323,689
<p>I occasionally see the list slice syntax used in Python code like this:</p> <pre><code>newList = oldList[:] </code></pre> <p>Surely this is just the same as:</p> <pre><code>newList = oldList </code></pre> <p>Or am I missing something?</p>
31
2008-11-27T12:57:05Z
323,800
<p>As it has already been answered, I'll simply add a simple demonstration:</p> <pre><code>&gt;&gt;&gt; a = [1, 2, 3, 4] &gt;&gt;&gt; b = a &gt;&gt;&gt; c = a[:] &gt;&gt;&gt; b[2] = 10 &gt;&gt;&gt; c[3] = 20 &gt;&gt;&gt; a [1, 2, 10, 4] &gt;&gt;&gt; b [1, 2, 10, 4] &gt;&gt;&gt; c [1, 2, 3, 20] </code></pre>
10
2008-11-27T13:40:50Z
[ "python", "list", "shallow-copy" ]
Python list slice syntax used for no obvious reason
323,689
<p>I occasionally see the list slice syntax used in Python code like this:</p> <pre><code>newList = oldList[:] </code></pre> <p>Surely this is just the same as:</p> <pre><code>newList = oldList </code></pre> <p>Or am I missing something?</p>
31
2008-11-27T12:57:05Z
323,810
<p>Never think that 'a = b' in Python means 'copy b to a'. If there are variables on both sides, you can't really know that. Instead, think of it as 'give b the additional name a'.</p> <p>If b is an immutable object (like a number, tuple or a string), then yes, the effect is that you get a copy. But that's because when you deal with immutables (which maybe should have been called <em>read only</em>, <em>unchangeable</em> or <em>WORM</em>) you <em>always</em> get a copy, by definition. </p> <p>If b is a mutable, you <em>always have to do something extra to be sure you have a true copy</em>. <em>Always</em>. With lists, it's as simple as a slice: a = b[:]. </p> <p>Mutability is also the reason that this:</p> <pre><code>def myfunction(mylist=[]): pass </code></pre> <p>... doesn't quite do what you think it does.</p> <p>If you're from a C-background: what's left of the '=' is a pointer, always. All variables are pointers, always. If you put variables in a list: a = [b, c], you've put pointers to the values pointed to by b and c in a list pointed to by a. If you then set a[0] = d, the pointer in position 0 is now pointing to whatever d points to. </p> <p>See also the copy-module: <a href="http://docs.python.org/library/copy.html" rel="nofollow">http://docs.python.org/library/copy.html</a></p>
4
2008-11-27T13:45:58Z
[ "python", "list", "shallow-copy" ]
Python list slice syntax used for no obvious reason
323,689
<p>I occasionally see the list slice syntax used in Python code like this:</p> <pre><code>newList = oldList[:] </code></pre> <p>Surely this is just the same as:</p> <pre><code>newList = oldList </code></pre> <p>Or am I missing something?</p>
31
2008-11-27T12:57:05Z
2,220,902
<p><strong>Shallow Copy:</strong> (copies chunks of memory from one location to another)</p> <pre><code>a = ['one','two','three'] b = a[:] b[1] = 2 print id(a), a #Output: 1077248300 ['one', 'two', 'three'] print id(b), b #Output: 1077248908 ['one', 2, 'three'] </code></pre> <p><strong>Deep Copy:</strong> (Copies object reference)</p> <pre><code>a = ['one','two','three'] b = a b[1] = 2 print id(a), a #Output: 1077248300 ['one', 2, 'three'] print id(b), b #Output: 1077248300 ['one', 2, 'three'] </code></pre>
-2
2010-02-08T10:30:39Z
[ "python", "list", "shallow-copy" ]
How to access previous/next element while for looping?
323,750
<p>Is there a way to access a list(or tuple, or other iterable)'s next, or previous element while looping through with for loop?</p> <pre><code>l=[1,2,3] for item in l: if item==2: get_previous(l,item) </code></pre>
31
2008-11-27T13:22:19Z
323,798
<p>Iterators only have the next() method so you cannot look forwards or backwards, you can only get the next item.</p> <p>enumerate(iterable) can be useful if you are iterating a list or tuple.</p>
0
2008-11-27T13:39:28Z
[ "python" ]
How to access previous/next element while for looping?
323,750
<p>Is there a way to access a list(or tuple, or other iterable)'s next, or previous element while looping through with for loop?</p> <pre><code>l=[1,2,3] for item in l: if item==2: get_previous(l,item) </code></pre>
31
2008-11-27T13:22:19Z
323,802
<p>The most simple way is to search the list for the item:</p> <pre><code>def get_previous(l, item): idx = l.find(item) return None if idx == 0 else l[idx-1] </code></pre> <p>Of course, this only works if the list only contains unique items. The other solution is:</p> <pre><code>for idx in range(len(l)): item = l[idx] if item == 2: l[idx-1] </code></pre>
-6
2008-11-27T13:41:17Z
[ "python" ]
How to access previous/next element while for looping?
323,750
<p>Is there a way to access a list(or tuple, or other iterable)'s next, or previous element while looping through with for loop?</p> <pre><code>l=[1,2,3] for item in l: if item==2: get_previous(l,item) </code></pre>
31
2008-11-27T13:22:19Z
323,827
<p>I don't think there is a straightforward way, especially that an iterable can be a generator (no going back). There's a decent workaround, relying on explicitly passing the index into the loop body:</p> <pre><code>for itemIndex, item in enumerate(l): if itemIndex&gt;0: previousItem = l[itemIndex-1] else: previousItem = None </code></pre> <p>The <code>enumerate()</code> function is a builtin.</p>
1
2008-11-27T13:55:31Z
[ "python" ]