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 |
---|---|---|---|---|---|---|---|---|---|
Python, unit-testing and mocking imports | 178,458 | <p>I am in a project where we are starting refactoring some massive code base. One problem that immediately sprang up is that each file imports a lot of other files. How do I in an elegant way mock this in my unit test without having to alter the actual code so I can start to write unit-tests?</p>
<p>As an example: The file with the functions I want to test, imports ten other files which is part of our software and not python core libs.</p>
<p>I want to be able to run the unit tests as separately as possible and for now I am only going to test functions that does not depend on things from the files that are being imported.</p>
<p>Thanks for all the answers. </p>
<p>I didn't really know what I wanted to do from the start but now I think I know. </p>
<p>Problem was that some imports was only possible when the whole application was running because of some third-party auto-magic. So I had to make some stubs for these modules in a directory which I pointed out with sys.path</p>
<p>Now I can import the file which contains the functions I want to write tests for in my unit-test file without complaints about missing modules.</p>
| 10 | 2008-10-07T13:34:42Z | 178,603 | <p>If you really want to muck around with the python import mechanism, take a look at the <a href="http://pydoc.org/2.4.1/ihooks.html" rel="nofollow"><code>ihooks</code></a> module. It provides tools for changing the behavior of the <code>__import__</code> built-in. But it's not clear from your question why you need to do this.</p>
| 1 | 2008-10-07T14:05:11Z | [
"python",
"unit-testing",
"refactoring",
"python-import"
] |
Python, unit-testing and mocking imports | 178,458 | <p>I am in a project where we are starting refactoring some massive code base. One problem that immediately sprang up is that each file imports a lot of other files. How do I in an elegant way mock this in my unit test without having to alter the actual code so I can start to write unit-tests?</p>
<p>As an example: The file with the functions I want to test, imports ten other files which is part of our software and not python core libs.</p>
<p>I want to be able to run the unit tests as separately as possible and for now I am only going to test functions that does not depend on things from the files that are being imported.</p>
<p>Thanks for all the answers. </p>
<p>I didn't really know what I wanted to do from the start but now I think I know. </p>
<p>Problem was that some imports was only possible when the whole application was running because of some third-party auto-magic. So I had to make some stubs for these modules in a directory which I pointed out with sys.path</p>
<p>Now I can import the file which contains the functions I want to write tests for in my unit-test file without complaints about missing modules.</p>
| 10 | 2008-10-07T13:34:42Z | 178,829 | <p>No difficult manipulation is necessary if you want a quick-and-dirty fix before your unit-tests.</p>
<p>If the unit tests are in the same file as the code you wish to test, simply delete unwanted module from the <code>globals()</code> dictionary.</p>
<p>Here is a rather lengthy example: suppose you have a module <code>impp.py</code> with contents:</p>
<pre><code>value = 5
</code></pre>
<p>Now, in your test file you can write:</p>
<pre><code>>>> import impp
>>> print globals().keys()
>>> def printVal():
>>> print impp.value
['printVal', '__builtins__', '__file__', 'impp', '__name__', '__doc__']
</code></pre>
<p>Note that <code>impp</code> is among the globals, because it was imported. Calling the function <code>printVal</code> that uses <code>impp</code> module still works:</p>
<pre><code>>>> printVal()
5
</code></pre>
<p>But now, if you remove <code>impp</code> key from <code>globals()</code>...</p>
<pre><code>>>> del globals()['impp']
>>> print globals().keys()
['printVal', '__builtins__', '__file__', '__name__', '__doc__']
</code></pre>
<p>...and try to call <code>printVal()</code>, you'll get:</p>
<pre><code>>>> printVal()
Traceback (most recent call last):
File "test_imp.py", line 13, in <module>
printVal()
File "test_imp.py", line 5, in printVal
print impp.value
NameError: global name 'impp' is not defined
</code></pre>
<p>...which is probably exactly what you're trying to achieve.</p>
<p>To use it in your unit-tests, you can delete the globals just before running the test suite, e.g. in <code>__main__</code>:</p>
<pre><code>if __name__ == '__main__':
del globals()['impp']
unittest.main()
</code></pre>
| 0 | 2008-10-07T14:53:38Z | [
"python",
"unit-testing",
"refactoring",
"python-import"
] |
Python, unit-testing and mocking imports | 178,458 | <p>I am in a project where we are starting refactoring some massive code base. One problem that immediately sprang up is that each file imports a lot of other files. How do I in an elegant way mock this in my unit test without having to alter the actual code so I can start to write unit-tests?</p>
<p>As an example: The file with the functions I want to test, imports ten other files which is part of our software and not python core libs.</p>
<p>I want to be able to run the unit tests as separately as possible and for now I am only going to test functions that does not depend on things from the files that are being imported.</p>
<p>Thanks for all the answers. </p>
<p>I didn't really know what I wanted to do from the start but now I think I know. </p>
<p>Problem was that some imports was only possible when the whole application was running because of some third-party auto-magic. So I had to make some stubs for these modules in a directory which I pointed out with sys.path</p>
<p>Now I can import the file which contains the functions I want to write tests for in my unit-test file without complaints about missing modules.</p>
| 10 | 2008-10-07T13:34:42Z | 179,057 | <p>In your comment <a href="http://stackoverflow.com/questions/178458/python-unit-testing-and-mocking-imports#178829">above</a>, you say you want to convince python that certain modules have already been imported. This still seems like a strange goal, but if that's really what you want to do, in principle you can sneak around behind the import mechanism's back, and change <code>sys.modules</code>. Not sure how this'd work for package imports, but should be fine for absolute imports.</p>
| 0 | 2008-10-07T15:30:34Z | [
"python",
"unit-testing",
"refactoring",
"python-import"
] |
Python, unit-testing and mocking imports | 178,458 | <p>I am in a project where we are starting refactoring some massive code base. One problem that immediately sprang up is that each file imports a lot of other files. How do I in an elegant way mock this in my unit test without having to alter the actual code so I can start to write unit-tests?</p>
<p>As an example: The file with the functions I want to test, imports ten other files which is part of our software and not python core libs.</p>
<p>I want to be able to run the unit tests as separately as possible and for now I am only going to test functions that does not depend on things from the files that are being imported.</p>
<p>Thanks for all the answers. </p>
<p>I didn't really know what I wanted to do from the start but now I think I know. </p>
<p>Problem was that some imports was only possible when the whole application was running because of some third-party auto-magic. So I had to make some stubs for these modules in a directory which I pointed out with sys.path</p>
<p>Now I can import the file which contains the functions I want to write tests for in my unit-test file without complaints about missing modules.</p>
| 10 | 2008-10-07T13:34:42Z | 179,531 | <p>If you want to import a module while at the same time ensuring that it doesn't import anything, you can replace the <code>__import__</code> builtin function.</p>
<p>For example, use this class:</p>
<pre><code>class ImportWrapper(object):
def __init__(self, real_import):
self.real_import = real_import
def wrapper(self, wantedModules):
def inner(moduleName, *args, **kwargs):
if moduleName in wantedModules:
print "IMPORTING MODULE", moduleName
self.real_import(*args, **kwargs)
else:
print "NOT IMPORTING MODULE", moduleName
return inner
def mock_import(self, moduleName, wantedModules):
__builtins__.__import__ = self.wrapper(wantedModules)
try:
__import__(moduleName, globals(), locals(), [], -1)
finally:
__builtins__.__import__ = self.real_import
</code></pre>
<p>And in your test code, instead of writing <code>import myModule</code>, write:</p>
<pre><code>wrapper = ImportWrapper(__import__)
wrapper.mock_import('myModule', [])
</code></pre>
<p>The second argument to <code>mock_import</code> is a list of module names you <em>do</em> want to import in inner module.</p>
<p>This example can be modified further to e.g. import other module than desired instead of just not importing it, or even mocking the module object with some custom object of your own.</p>
| 7 | 2008-10-07T17:30:27Z | [
"python",
"unit-testing",
"refactoring",
"python-import"
] |
How do I perform an IMAP search in Python (using Gmail and imaplib)? | 179,026 | <p>In Gmail, I have a bunch of labeled messages.</p>
<p>I'd like to use an IMAP client to get those messages, but I'm not sure what the search incantation is.</p>
<pre><code>c = imaplib.IMAP4_SSL('imap.gmail.com')
c.list()
('OK', [..., '(\\HasNoChildren) "/" "GM"', ...])
c.search(???)
</code></pre>
<p>I'm not finding many examples for this sort of thing.</p>
| 9 | 2008-10-07T15:24:59Z | 179,356 | <p><a href="http://mail.google.com/support/bin/answer.py?ctx=gmail&hl=en&answer=75725">Labels are accessed exactly like IMAP folders</a>, according to Google.</p>
| 5 | 2008-10-07T16:42:21Z | [
"python",
"gmail",
"imap"
] |
How do I perform an IMAP search in Python (using Gmail and imaplib)? | 179,026 | <p>In Gmail, I have a bunch of labeled messages.</p>
<p>I'd like to use an IMAP client to get those messages, but I'm not sure what the search incantation is.</p>
<pre><code>c = imaplib.IMAP4_SSL('imap.gmail.com')
c.list()
('OK', [..., '(\\HasNoChildren) "/" "GM"', ...])
c.search(???)
</code></pre>
<p>I'm not finding many examples for this sort of thing.</p>
| 9 | 2008-10-07T15:24:59Z | 185,499 | <p>I've been pretty surprised that imaplib doesn't do a lot of the response parsing. And it seems that responses were crafted to be hard to parse.</p>
<p>FWIW, to answer my own question:
c.search(None, 'GM')</p>
<p>(I have no idea what the '(\HasNoChildren) "/"' part is about.)</p>
| 0 | 2008-10-09T00:38:53Z | [
"python",
"gmail",
"imap"
] |
How do I perform an IMAP search in Python (using Gmail and imaplib)? | 179,026 | <p>In Gmail, I have a bunch of labeled messages.</p>
<p>I'd like to use an IMAP client to get those messages, but I'm not sure what the search incantation is.</p>
<pre><code>c = imaplib.IMAP4_SSL('imap.gmail.com')
c.list()
('OK', [..., '(\\HasNoChildren) "/" "GM"', ...])
c.search(???)
</code></pre>
<p>I'm not finding many examples for this sort of thing.</p>
| 9 | 2008-10-07T15:24:59Z | 421,752 | <p><code>imaplib</code> is intentionally a thin wrapper around the IMAP protocol, I assume to allow for a greater degree of user flexibility and a greater ability to adapt to changes in the IMAP specification. As a result, it doesn't really offer any structure for your search queries and requires you to be familiar with the <a href="http://www.faqs.org/rfcs/rfc3501.html">IMAP specification</a>.</p>
<p>As you'll see in section "6.4.4. SEARCH Command", there are many things you can specify for search criterion. Note that you have to <code>SELECT</code> a mailbox (IMAP's name for a folder) before you can search for anything. (Searching multiple folders simultaneously requires multiple IMAP connections, as I understand it.) <code>IMAP4.list</code> will help you figure out what the mailbox identifiers are.</p>
<p>Also useful in formulating the strings you pass to <code>imaplib</code> is "9. Formal Syntax" from the RFC linked to above.</p>
<p>The <code>r'(\HasNoChildren) "/"'</code> is a mailbox flag on the root mailbox, <code>/</code>. See "7.2.6. FLAGS Response".</p>
<p>Good luck!</p>
| 6 | 2009-01-07T19:37:42Z | [
"python",
"gmail",
"imap"
] |
How do I perform an IMAP search in Python (using Gmail and imaplib)? | 179,026 | <p>In Gmail, I have a bunch of labeled messages.</p>
<p>I'd like to use an IMAP client to get those messages, but I'm not sure what the search incantation is.</p>
<pre><code>c = imaplib.IMAP4_SSL('imap.gmail.com')
c.list()
('OK', [..., '(\\HasNoChildren) "/" "GM"', ...])
c.search(???)
</code></pre>
<p>I'm not finding many examples for this sort of thing.</p>
| 9 | 2008-10-07T15:24:59Z | 3,101,260 | <pre><code>import imaplib
obj = imaplib.IMAP4_SSL('imap.gmail.com', 993)
obj.login('username', 'password')
obj.select('**label name**') # <-- the label in which u want to search message
obj.search(None, 'FROM', '"LDJ"')
</code></pre>
| 6 | 2010-06-23T11:45:49Z | [
"python",
"gmail",
"imap"
] |
How do I perform an IMAP search in Python (using Gmail and imaplib)? | 179,026 | <p>In Gmail, I have a bunch of labeled messages.</p>
<p>I'd like to use an IMAP client to get those messages, but I'm not sure what the search incantation is.</p>
<pre><code>c = imaplib.IMAP4_SSL('imap.gmail.com')
c.list()
('OK', [..., '(\\HasNoChildren) "/" "GM"', ...])
c.search(???)
</code></pre>
<p>I'm not finding many examples for this sort of thing.</p>
| 9 | 2008-10-07T15:24:59Z | 36,875,058 | <p>The easiest way to use imaplib with Gmail is to use the <code>X-GM-RAW</code> attribute as described in the <a href="https://developers.google.com/gmail/imap_extensions#special-use_extension_of_the_list_command" rel="nofollow">Gmail Imap Extensions page</a>.</p>
<p>The process would be like this:</p>
<p>First connect to the account with the appropriate email and password:</p>
<pre><code>c = imaplib.IMAP4_SSL('imap.gmail.com', 993)
email = 'eggs@spam'
password = 'spamspamspam'
c.login(email, password)
</code></pre>
<p>Then connect to one of the folders/labels:</p>
<pre><code>c.select("INBOX")
</code></pre>
<p>If necessary, you can list all the available folders/labels with <code>c.list()</code>.</p>
<p>Finally, use the search method:</p>
<pre><code>gmail_search = "has:attachment eggs OR spam"
status, data = c.search(None, 'X-GM-RAW', gmail_search)
</code></pre>
<p>In the <code>gmail_search</code> you can use the same search syntax used in <a href="https://support.google.com/mail/answer/7190?hl=en" rel="nofollow">gmail advanced search</a>.</p>
<p>The search command will return the status of the command and the ids of all the messages that match your gmail_search.</p>
<p>After this you can fetch each messages by id with:</p>
<pre><code>for id in data[0].split():
status, data = gmail.fetch(id, '(BODY[TEXT])')
</code></pre>
| 0 | 2016-04-26T20:25:52Z | [
"python",
"gmail",
"imap"
] |
What is the best way to change text contained in an XML file using Python? | 179,287 | <p>Let's say I have an existing trivial XML file named 'MyData.xml' that contains the following:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<myElement>foo</myElement>
</code></pre>
<p>I want to change the text value of 'foo' to 'bar' resulting in the following:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<myElement>bar</myElement>
</code></pre>
<p>Once I am done, I want to save the changes. </p>
<p>What is the easiest and simplest way to accomplish all this?</p>
| 4 | 2008-10-07T16:23:52Z | 179,305 | <p>For quick, non-critical XML manipulations, i really like <a href="http://ponderer.org/p4x" rel="nofollow">P4X</a>. It let's you write like this:</p>
<pre class="lang-python prettyprint-override"><code>import p4x
doc = p4x.P4X (open(file).read)
doc.myElement = 'bar'
</code></pre>
| 3 | 2008-10-07T16:29:04Z | [
"python",
"xml",
"text"
] |
What is the best way to change text contained in an XML file using Python? | 179,287 | <p>Let's say I have an existing trivial XML file named 'MyData.xml' that contains the following:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<myElement>foo</myElement>
</code></pre>
<p>I want to change the text value of 'foo' to 'bar' resulting in the following:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<myElement>bar</myElement>
</code></pre>
<p>Once I am done, I want to save the changes. </p>
<p>What is the easiest and simplest way to accomplish all this?</p>
| 4 | 2008-10-07T16:23:52Z | 179,306 | <p>Use Python's <a href="http://docs.python.org/library/xml.dom.minidom.html" rel="nofollow">minidom</a></p>
<p>Basically you will take the following steps:</p>
<ol>
<li>Read XML data into DOM object</li>
<li>Use DOM methods to modify the document</li>
<li>Save new DOM object to new XML document</li>
</ol>
<p>The python spec should hold your hand rather nicely though this process. </p>
| 4 | 2008-10-07T16:29:06Z | [
"python",
"xml",
"text"
] |
What is the best way to change text contained in an XML file using Python? | 179,287 | <p>Let's say I have an existing trivial XML file named 'MyData.xml' that contains the following:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<myElement>foo</myElement>
</code></pre>
<p>I want to change the text value of 'foo' to 'bar' resulting in the following:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<myElement>bar</myElement>
</code></pre>
<p>Once I am done, I want to save the changes. </p>
<p>What is the easiest and simplest way to accomplish all this?</p>
| 4 | 2008-10-07T16:23:52Z | 180,433 | <p>This is what I wrote based on <a href="http://stackoverflow.com/questions/179287/what-is-the-best-way-to-change-text-contained-in-an-xml-file-using-python#179306">@Ryan's answer</a>:</p>
<pre class="lang-python prettyprint-override"><code>from xml.dom.minidom import parse
import os
# create a backup of original file
new_file_name = 'MyData.xml'
old_file_name = new_file_name + "~"
os.rename(new_file_name, old_file_name)
# change text value of element
doc = parse(old_file_name)
node = doc.getElementsByTagName('myElement')
node[0].firstChild.nodeValue = 'bar'
# persist changes to new file
xml_file = open(new_file_name, "w")
doc.writexml(xml_file, encoding="utf-8")
xml_file.close()
</code></pre>
<p>Not sure if this was the easiest and simplest approach but it does work. (<a href="http://stackoverflow.com/questions/179287/what-is-the-best-way-to-change-text-contained-in-an-xml-file-using-python#179305">@Javier's answer</a> has less lines of code but requires non-standard library)</p>
| 3 | 2008-10-07T21:07:57Z | [
"python",
"xml",
"text"
] |
What is the best way to change text contained in an XML file using Python? | 179,287 | <p>Let's say I have an existing trivial XML file named 'MyData.xml' that contains the following:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<myElement>foo</myElement>
</code></pre>
<p>I want to change the text value of 'foo' to 'bar' resulting in the following:</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<myElement>bar</myElement>
</code></pre>
<p>Once I am done, I want to save the changes. </p>
<p>What is the easiest and simplest way to accomplish all this?</p>
| 4 | 2008-10-07T16:23:52Z | 180,564 | <p>You also might want to check out Uche Ogbuji's excellent XML Data Binding Library, Amara:
<a href="http://uche.ogbuji.net/tech/4suite/amara" rel="nofollow">http://uche.ogbuji.net/tech/4suite/amara</a></p>
<p>(Documentation here:
<a href="http://platea.pntic.mec.es/~jmorilla/amara/manual/" rel="nofollow">http://platea.pntic.mec.es/~jmorilla/amara/manual/</a>)</p>
<p>The cool thing about Amara is that it turns an XML document in to a Python object, so you can just do stuff like:</p>
<pre class="lang-python prettyprint-override"><code>record = doc.xml_create_element(u'Record')
nameElem = doc.xml_create_element(u'Name', content=unicode(name))
record.xml_append(nameElem)
valueElem = doc.xml_create_element(u'Value', content=unicode(value))
record.xml_append(valueElem
</code></pre>
<p>(which creates a Record element that contains Name and Value elements (which in turn contain the values of the name and value variables)).</p>
| 1 | 2008-10-07T21:42:17Z | [
"python",
"xml",
"text"
] |
Average difference between dates in Python | 179,716 | <p>I have a series of datetime objects and would like to calculate the average delta between them.</p>
<p>For example, if the input was <code>(2008-10-01 12:15:00, 2008-10-01 12:25:00, 2008-10-01 12:35:00)</code>, then the average delta would be exactly 00:10:00, or 10 minutes.</p>
<p>Any suggestions on how to calculate this using Python?</p>
| 2 | 2008-10-07T18:18:48Z | 179,738 | <p>As far as algorithms go, that's an easy one. Just find the max and min datetimes, take the difference, and divide by the number of datetimes you looked at.</p>
<p>If you have an array a of datetimes, you can do:</p>
<pre><code>mx = max(a)
mn = min(a)
avg = (mx-mn)/(len(a)-1)
</code></pre>
<p>to get back the average difference.</p>
<p>EDIT: fixed the off-by-one error</p>
| 12 | 2008-10-07T18:26:46Z | [
"python",
"algorithm",
"datetime"
] |
Average difference between dates in Python | 179,716 | <p>I have a series of datetime objects and would like to calculate the average delta between them.</p>
<p>For example, if the input was <code>(2008-10-01 12:15:00, 2008-10-01 12:25:00, 2008-10-01 12:35:00)</code>, then the average delta would be exactly 00:10:00, or 10 minutes.</p>
<p>Any suggestions on how to calculate this using Python?</p>
| 2 | 2008-10-07T18:18:48Z | 179,760 | <p>Since you seem to be throwing out the 20 minute delta between times 1 and 3 in your example, I'd say you should just sort the list of datetimes, add up the deltas between adjacent times, then divide by n-1.</p>
<p>Do you have any code you can share with us, so we can help you debug it?</p>
| 2 | 2008-10-07T18:32:46Z | [
"python",
"algorithm",
"datetime"
] |
Average difference between dates in Python | 179,716 | <p>I have a series of datetime objects and would like to calculate the average delta between them.</p>
<p>For example, if the input was <code>(2008-10-01 12:15:00, 2008-10-01 12:25:00, 2008-10-01 12:35:00)</code>, then the average delta would be exactly 00:10:00, or 10 minutes.</p>
<p>Any suggestions on how to calculate this using Python?</p>
| 2 | 2008-10-07T18:18:48Z | 179,761 | <p>You can subtract each successive date from the one prior (resulting in a timedelta object which represents the difference in days, seconds). You can then average the timedelta objects to find your answer.</p>
| 1 | 2008-10-07T18:32:56Z | [
"python",
"algorithm",
"datetime"
] |
Average difference between dates in Python | 179,716 | <p>I have a series of datetime objects and would like to calculate the average delta between them.</p>
<p>For example, if the input was <code>(2008-10-01 12:15:00, 2008-10-01 12:25:00, 2008-10-01 12:35:00)</code>, then the average delta would be exactly 00:10:00, or 10 minutes.</p>
<p>Any suggestions on how to calculate this using Python?</p>
| 2 | 2008-10-07T18:18:48Z | 181,239 | <p>Say <code>a</code> is your list</p>
<pre><code>sumdeltas = timedelta(seconds=0)
i = 1
while i < len(a):
sumdeltas += a[i-1] - a[i]
i = i + 1
avg_delta = sumdeltas / (len(a) - 1)
</code></pre>
<p>This will indeed average your deltas together.</p>
| 2 | 2008-10-08T03:33:47Z | [
"python",
"algorithm",
"datetime"
] |
Average difference between dates in Python | 179,716 | <p>I have a series of datetime objects and would like to calculate the average delta between them.</p>
<p>For example, if the input was <code>(2008-10-01 12:15:00, 2008-10-01 12:25:00, 2008-10-01 12:35:00)</code>, then the average delta would be exactly 00:10:00, or 10 minutes.</p>
<p>Any suggestions on how to calculate this using Python?</p>
| 2 | 2008-10-07T18:18:48Z | 1,571,406 | <p>small clarification</p>
<pre><code>from datetime import timedelta
def avg(a):
numdeltas = len(a) - 1
sumdeltas = timedelta(seconds=0)
i = 1
while i < len(a):
delta = abs(a[i] - a[i-1])
try:
sumdeltas += delta
except:
raise
i += 1
avg = sumdeltas / numdeltas
return avg
</code></pre>
| 0 | 2009-10-15T10:04:17Z | [
"python",
"algorithm",
"datetime"
] |
Python class factory ... or? | 179,985 | <p>We have a database library in C# that we can use like this:</p>
<pre><code>DatabaseConnection conn = DatabaseConnection.FromConnectionString("...");
</code></pre>
<p>This library hides many of the differences between different database engines, like SQL function names, parameter names and specifications, etc.</p>
<p>Internally, the <code>DatabaseConnection</code> class is an abstract class implementing some of the basic methods, but the <code>FromConnectionString</code> method runs through a list of registered specialized types that handles the actual differences, and constructs an object of the right class. In other words, I don't get a DatabaseConnection object back, I get a MSSQLDatabaseConnection or OracleDatabaseConnection object back instead, which of course inherit from DatabaseConnection.</p>
<p>The connection string contains information about what kind of database engine and version this connection is for.</p>
<p>I'd like to create a similar library in Python. Is the right approach to make something that can be constructed like this?</p>
<pre><code>conn = DatabaseConnection("...")
</code></pre>
<p>or using a class method?</p>
<pre><code>conn = DatabaseConnection.FromConnectionString("...")
</code></pre>
<p>is the first even possible, that is... constructing an object like this and getting back something else, a specialized object, depending on data in the passed string?</p>
<p>Ok, let me ask a different question... What is the <em>pythonic</em> way of doing this?</p>
<p>I basically want to have the DatabaseConnection base class in Python as well, implementing the common methods, and specialize in derived classes, and have a method or function somewhere that based on the connection string constructs and returns the right type of object.</p>
| 1 | 2008-10-07T19:34:13Z | 180,009 | <p>This is possible in Python, but is probably not the best way to do it. The class factory pattern is essentially a workaround for languages that don't have first class classes. Since Python does have first class classes, you can store a class in a variable, and use that class directly to create instances. To change what class is created, store a different class in the variable.</p>
<p>For example:</p>
<pre><code>class class1:
def greet(self):
print "hi"
class class2:
def greet(self):
print "hello"
maker = class1
obj1 = maker()
maker = class2
obj2 = maker()
obj1.greet() # prints "hi"
obj2.greet() # prints "hello"
</code></pre>
| 5 | 2008-10-07T19:39:32Z | [
"c#",
"python"
] |
Python class factory ... or? | 179,985 | <p>We have a database library in C# that we can use like this:</p>
<pre><code>DatabaseConnection conn = DatabaseConnection.FromConnectionString("...");
</code></pre>
<p>This library hides many of the differences between different database engines, like SQL function names, parameter names and specifications, etc.</p>
<p>Internally, the <code>DatabaseConnection</code> class is an abstract class implementing some of the basic methods, but the <code>FromConnectionString</code> method runs through a list of registered specialized types that handles the actual differences, and constructs an object of the right class. In other words, I don't get a DatabaseConnection object back, I get a MSSQLDatabaseConnection or OracleDatabaseConnection object back instead, which of course inherit from DatabaseConnection.</p>
<p>The connection string contains information about what kind of database engine and version this connection is for.</p>
<p>I'd like to create a similar library in Python. Is the right approach to make something that can be constructed like this?</p>
<pre><code>conn = DatabaseConnection("...")
</code></pre>
<p>or using a class method?</p>
<pre><code>conn = DatabaseConnection.FromConnectionString("...")
</code></pre>
<p>is the first even possible, that is... constructing an object like this and getting back something else, a specialized object, depending on data in the passed string?</p>
<p>Ok, let me ask a different question... What is the <em>pythonic</em> way of doing this?</p>
<p>I basically want to have the DatabaseConnection base class in Python as well, implementing the common methods, and specialize in derived classes, and have a method or function somewhere that based on the connection string constructs and returns the right type of object.</p>
| 1 | 2008-10-07T19:34:13Z | 180,028 | <p>The first one is absolutely possible, and preferable in my opinion. In python, there's really not a whole lot of magic behind constructors. For all intents and purposes, they're just like any other function. I've used this design pattern a few times to indicate that a class shouldn't be instantiated directly, for example:</p>
<pre><code>def DatabaseConnectionFromString(connection_string)
return _DatabaseConnection(connection_string)
def DatabaseConnectionFromSomethingElse(something_else)
connection_string = convert_something_else_into_string(something_else)
return _DatabaseConnection(connection_string)
class _DatabaseConnection(object):
def __init__(self, connection_string):
self.connection_string = connection_string
</code></pre>
<p>Of course, that's a contrived example, but that should give you a general idea.</p>
<p><strong>EDIT:</strong> This is also one of the areas where inheritance isn't quite as frowned upon in python as well. You can also do this:</p>
<pre><code>DatabaseConnection(object):
def __init__(self, connection_string):
self.connection_string = connection_string
DatabaseConnectionFromSomethingElse(object)
def __init__(self, something_else):
self.connection_string = convert_something_else_into_string(something_else)
</code></pre>
<p>Sorry that's so verbose, but I wanted to make it clear.</p>
| 1 | 2008-10-07T19:42:54Z | [
"c#",
"python"
] |
Python class factory ... or? | 179,985 | <p>We have a database library in C# that we can use like this:</p>
<pre><code>DatabaseConnection conn = DatabaseConnection.FromConnectionString("...");
</code></pre>
<p>This library hides many of the differences between different database engines, like SQL function names, parameter names and specifications, etc.</p>
<p>Internally, the <code>DatabaseConnection</code> class is an abstract class implementing some of the basic methods, but the <code>FromConnectionString</code> method runs through a list of registered specialized types that handles the actual differences, and constructs an object of the right class. In other words, I don't get a DatabaseConnection object back, I get a MSSQLDatabaseConnection or OracleDatabaseConnection object back instead, which of course inherit from DatabaseConnection.</p>
<p>The connection string contains information about what kind of database engine and version this connection is for.</p>
<p>I'd like to create a similar library in Python. Is the right approach to make something that can be constructed like this?</p>
<pre><code>conn = DatabaseConnection("...")
</code></pre>
<p>or using a class method?</p>
<pre><code>conn = DatabaseConnection.FromConnectionString("...")
</code></pre>
<p>is the first even possible, that is... constructing an object like this and getting back something else, a specialized object, depending on data in the passed string?</p>
<p>Ok, let me ask a different question... What is the <em>pythonic</em> way of doing this?</p>
<p>I basically want to have the DatabaseConnection base class in Python as well, implementing the common methods, and specialize in derived classes, and have a method or function somewhere that based on the connection string constructs and returns the right type of object.</p>
| 1 | 2008-10-07T19:34:13Z | 180,142 | <p>Python doesn't care why type you return.</p>
<pre><code>def DatabaseConnection( str ):
if ( IsOracle( str ) ):
return OracleConnection( str )
else:
return SomeOtherConnection( str )
</code></pre>
| 3 | 2008-10-07T20:04:00Z | [
"c#",
"python"
] |
How to handle a broken pipe (SIGPIPE) in python? | 180,095 | <p>I've written a simple multi-threaded game server in python that creates a new thread for each client connection. I'm finding that every now and then, the server will crash because of a broken-pipe/SIGPIPE error. I'm pretty sure it is happening when the program tries to send a response back to a client that is no longer present.</p>
<p>What is a good way to deal with this? My preferred resolution would simply close the server-side connection to the client and move on, rather than exit the entire program.</p>
<p>PS: <a href="http://stackoverflow.com/questions/108183/how-to-prevent-sigpipes-or-handle-them-properly">This</a> question/answer deals with the problem in a generic way; how specifically should I solve it?</p>
| 40 | 2008-10-07T19:53:53Z | 180,152 | <p>Read up on the try: statement.</p>
<pre><code>try:
# do something
except socket.error, e:
# A socket error
except IOError, e:
if e.errno == errno.EPIPE:
# EPIPE error
else:
# Other error
</code></pre>
| 30 | 2008-10-07T20:07:27Z | [
"python",
"broken-pipe"
] |
How to handle a broken pipe (SIGPIPE) in python? | 180,095 | <p>I've written a simple multi-threaded game server in python that creates a new thread for each client connection. I'm finding that every now and then, the server will crash because of a broken-pipe/SIGPIPE error. I'm pretty sure it is happening when the program tries to send a response back to a client that is no longer present.</p>
<p>What is a good way to deal with this? My preferred resolution would simply close the server-side connection to the client and move on, rather than exit the entire program.</p>
<p>PS: <a href="http://stackoverflow.com/questions/108183/how-to-prevent-sigpipes-or-handle-them-properly">This</a> question/answer deals with the problem in a generic way; how specifically should I solve it?</p>
| 40 | 2008-10-07T19:53:53Z | 180,378 | <p><code>SIGPIPE</code> (although I think maybe you mean <code>EPIPE</code>?) occurs on sockets when you shut down a socket and then send data to it. The simple solution is not to shut the socket down before trying to send it data. This can also happen on pipes, but it doesn't sound like that's what you're experiencing, since it's a network server.</p>
<p>You can also just apply the band-aid of catching the exception in some top-level handler in each thread.</p>
<p>Of course, if you used <a href="http://twistedmatrix.com/" rel="nofollow">Twisted</a> rather than spawning a new thread for each client connection, you probably wouldn't have this problem. It's really hard (maybe impossible, depending on your application) to get the ordering of close and write operations correct if multiple threads are dealing with the same I/O channel.</p>
| 3 | 2008-10-07T20:55:36Z | [
"python",
"broken-pipe"
] |
How to handle a broken pipe (SIGPIPE) in python? | 180,095 | <p>I've written a simple multi-threaded game server in python that creates a new thread for each client connection. I'm finding that every now and then, the server will crash because of a broken-pipe/SIGPIPE error. I'm pretty sure it is happening when the program tries to send a response back to a client that is no longer present.</p>
<p>What is a good way to deal with this? My preferred resolution would simply close the server-side connection to the client and move on, rather than exit the entire program.</p>
<p>PS: <a href="http://stackoverflow.com/questions/108183/how-to-prevent-sigpipes-or-handle-them-properly">This</a> question/answer deals with the problem in a generic way; how specifically should I solve it?</p>
| 40 | 2008-10-07T19:53:53Z | 180,421 | <p>My answer is very close to S.Lott's, except I'd be even more particular:</p>
<pre><code>try:
# do something
except IOError, e:
# ooops, check the attributes of e to see precisely what happened.
if e.errno != 23:
# I don't know how to handle this
raise
</code></pre>
<p>where "23" is the error number you get from EPIPE. This way you won't attempt to handle a permissions error or anything else you're not equipped for.</p>
| -1 | 2008-10-07T21:05:54Z | [
"python",
"broken-pipe"
] |
How to handle a broken pipe (SIGPIPE) in python? | 180,095 | <p>I've written a simple multi-threaded game server in python that creates a new thread for each client connection. I'm finding that every now and then, the server will crash because of a broken-pipe/SIGPIPE error. I'm pretty sure it is happening when the program tries to send a response back to a client that is no longer present.</p>
<p>What is a good way to deal with this? My preferred resolution would simply close the server-side connection to the client and move on, rather than exit the entire program.</p>
<p>PS: <a href="http://stackoverflow.com/questions/108183/how-to-prevent-sigpipes-or-handle-them-properly">This</a> question/answer deals with the problem in a generic way; how specifically should I solve it?</p>
| 40 | 2008-10-07T19:53:53Z | 180,922 | <p>Assuming that you are using the standard socket module, you should be catching the <code>socket.error: (32, 'Broken pipe')</code> exception (not IOError as others have suggested). This will be raised in the case that you've described, i.e. sending/writing to a socket for which the remote side has disconnected.</p>
<pre><code>import socket, errno, time
# setup socket to listen for incoming connections
s = socket.socket()
s.bind(('localhost', 1234))
s.listen(1)
remote, address = s.accept()
print "Got connection from: ", address
while 1:
try:
remote.send("message to peer\n")
time.sleep(1)
except socket.error, e:
if isinstance(e.args, tuple):
print "errno is %d" % e[0]
if e[0] == errno.EPIPE:
# remote peer disconnected
print "Detected remote disconnect"
else:
# determine and handle different error
pass
else:
print "socket error ", e
remote.close()
break
except IOError, e:
# Hmmm, Can IOError actually be raised by the socket module?
print "Got IOError: ", e
break
</code></pre>
<p>Note that this exception will not always be raised on the first write to a closed socket - more usually the second write (unless the number of bytes written in the first write is larger than the socket's buffer size). You need to keep this in mind in case your application thinks that the remote end received the data from the first write when it may have already disconnected.</p>
<p>You can reduce the incidence (but not entirely eliminate) of this by using <code>select.select()</code> (or <code>poll</code>). Check for data ready to read from the peer before attempting a write. If <code>select</code> reports that there is data available to read from the peer socket, read it using <code>socket.recv()</code>. If this returns an empty string, the remote peer has closed the connection. Because there is still a race condition here, you'll still need to catch and handle the exception.</p>
<p>Twisted is great for this sort of thing, however, it sounds like you've already written a fair bit of code.</p>
| 44 | 2008-10-08T00:14:18Z | [
"python",
"broken-pipe"
] |
How do I convert a list of ascii values to a string in python? | 180,606 | <p>I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?</p>
| 31 | 2008-10-07T21:51:01Z | 180,615 | <p>You are probably looking for 'chr()':</p>
<pre><code>>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(chr(i) for i in L)
'hello, world'
</code></pre>
| 56 | 2008-10-07T21:54:33Z | [
"python",
"string",
"ascii"
] |
How do I convert a list of ascii values to a string in python? | 180,606 | <p>I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?</p>
| 31 | 2008-10-07T21:51:01Z | 180,617 | <pre><code>l = [83, 84, 65, 67, 75]
s = "".join([chr(c) for c in l])
print s
</code></pre>
| 4 | 2008-10-07T21:55:06Z | [
"python",
"string",
"ascii"
] |
How do I convert a list of ascii values to a string in python? | 180,606 | <p>I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?</p>
| 31 | 2008-10-07T21:51:01Z | 181,057 | <p>Same basic solution as others, but I personally prefer to use map instead of the list comprehension:</p>
<pre><code>
>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(map(chr,L))
'hello, world'
</code></pre>
| 12 | 2008-10-08T01:22:05Z | [
"python",
"string",
"ascii"
] |
How do I convert a list of ascii values to a string in python? | 180,606 | <p>I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?</p>
| 31 | 2008-10-07T21:51:01Z | 184,708 | <pre><code>import array
def f7(list):
return array.array('B', list).tostring()
</code></pre>
<p>from <a href="http://www.python.org/doc/essays/list2str.html">Python Patterns - An Optimization Anecdote</a></p>
| 8 | 2008-10-08T20:22:31Z | [
"python",
"string",
"ascii"
] |
How do I convert a list of ascii values to a string in python? | 180,606 | <p>I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?</p>
| 31 | 2008-10-07T21:51:01Z | 31,800,289 | <p>def working_ascii():
"""
G r e e t i n g s !
71, 114, 101, 101, 116, 105, 110, 103, 115, 33
"""</p>
<pre><code>hello = [71, 114, 101, 101, 116, 105, 110, 103, 115, 33]
pmsg = ''.join(chr(i) for i in hello)
print(pmsg)
for i in range(33, 256):
print(" ascii: {0} char: {1}".format(i, chr(i)))
</code></pre>
<p>working_ascii()</p>
| 0 | 2015-08-04T03:42:20Z | [
"python",
"string",
"ascii"
] |
How do I convert a list of ascii values to a string in python? | 180,606 | <p>I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?</p>
| 31 | 2008-10-07T21:51:01Z | 34,246,694 | <p>Perhaps not as Pyhtonic a solution, but easier to read for noobs like me:</p>
<pre><code>charlist = [34, 38, 49, 67, 89, 45, 103, 105, 119, 125]
mystring = ""
for char in charlist:
mystring = mystring + chr(char)
print mystring
</code></pre>
| 1 | 2015-12-13T00:35:37Z | [
"python",
"string",
"ascii"
] |
In the Django admin interface, is there a way to duplicate an item? | 180,809 | <p>Just wondering if there is an easy way to add the functionality to duplicate an existing listing in the admin interface?</p>
<p>In data entry we have run into a situation where a lot of items share generic data with another item, and to save time it would be very nice to quickly duplicate an existing listing and only alter the changed data. Using a better model structure would be one way of reducing the duplication of the data, but there may be situation where the duplicated data needs to be changed on an individual basis in the future.</p>
| 40 | 2008-10-07T23:23:11Z | 180,816 | <p>You can <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_as">save as</a> by just enabling adding this to your ModelAdmin:</p>
<pre><code>save_as = True
</code></pre>
<p>This replaces the "Save and add another" button with a "Save as" button. "Save as" means the object will be saved as a new object (with a new ID), rather than the old object.</p>
| 71 | 2008-10-07T23:26:15Z | [
"python",
"django",
"django-models",
"django-admin"
] |
What is the difference between Python's re.search and re.match? | 180,986 | <p>What is the difference between the <code>search()</code> and <code>match()</code> functions in the <a href="http://docs.python.org/2/library/re.html">Python <code>re</code> module</a>?</p>
<p>I've read the <a href="http://www.python.org/doc/2.5.2/lib/matching-searching.html">documentation</a> (<a href="http://docs.python.org/2/library/re.html?highlight=matching%20searching#search-vs-match">current documentation</a>), but I never seem to remember it. I keep having to look it up and re-learn it. I'm hoping that someone will answer it clearly with examples so that (perhaps) it will stick in my head. Or at least I'll have a better place to return with my question and it will take less time to re-learn it.</p>
| 189 | 2008-10-08T00:51:36Z | 180,993 | <p><code>re.match</code> is anchored at the beginning of the string. That has nothing to do with newlines, so it is not the same as using <code>^</code> in the pattern.</p>
<p>As <a href="http://docs.python.org/2/library/re.html#re.match">re.match documentation</a> says:</p>
<blockquote>
<p>If zero or more characters at the
<strong>beginning of string</strong> match the regular expression pattern, return a
corresponding <code>MatchObject</code> instance.
Return <code>None</code> if the string does not
match the pattern; note that this is
different from a zero-length match.</p>
<p>Note: If you want to locate a match
anywhere in string, use <code>search()</code>
instead.</p>
</blockquote>
<p><code>re.search</code> searches the entire string, as <a href="http://docs.python.org/2/library/re.html#re.search">the documentation says</a>:</p>
<blockquote>
<p><strong>Scan through string</strong> looking for a
location where the regular expression
pattern produces a match, and return a
corresponding <code>MatchObject</code> instance.
Return <code>None</code> if no position in the
string matches the pattern; note that
this is different from finding a
zero-length match at some point in the
string.</p>
</blockquote>
<p>So if you need to match at the beginning of the string, or to match the entire string use <code>match</code>. It is faster. Otherwise use <code>search</code>.</p>
<p>The documentation has a <a href="http://docs.python.org/2/library/re.html#search-vs-match">specific section for <code>match</code> vs. <code>search</code></a> that also covers multiline strings:</p>
<blockquote>
<p>Python offers two different primitive
operations based on regular
expressions: <code>match</code> checks for a match
<strong>only at the beginning</strong> of the string,
while <code>search</code> checks for a match
<strong>anywhere</strong> in the string (this is what
Perl does by default).</p>
<p>Note that <code>match</code> may differ from <code>search</code>
even when using a regular expression
beginning with <code>'^'</code>: <code>'^'</code> matches only
at the start of the string, or in
<code>MULTILINE</code> mode also immediately
following a newline. The â<code>match</code>â
operation succeeds <em>only if the pattern
matches at the <strong>start</strong> of the string</em>
regardless of mode, or at the starting
position given by the optional <code>pos</code>
argument regardless of whether a
newline precedes it.</p>
</blockquote>
<p>Now, enough talk. Time to some example code:</p>
<pre><code># example code:
string_with_newlines = """something
someotherthing"""
import re
print re.match('some', string_with_newlines) # matches
print re.match('someother',
string_with_newlines) # won't match
print re.match('^someother', string_with_newlines,
re.MULTILINE) # also won't match
print re.search('someother',
string_with_newlines) # finds something
print re.search('^someother', string_with_newlines,
re.MULTILINE) # also finds something
m = re.compile('thing$', re.MULTILINE)
print m.match(string_with_newlines) # no match
print m.match(string_with_newlines, pos=4) # matches
print m.search(string_with_newlines,
re.MULTILINE) # also matches
</code></pre>
| 209 | 2008-10-08T00:53:12Z | [
"python",
"regex",
"search",
"match"
] |
What is the difference between Python's re.search and re.match? | 180,986 | <p>What is the difference between the <code>search()</code> and <code>match()</code> functions in the <a href="http://docs.python.org/2/library/re.html">Python <code>re</code> module</a>?</p>
<p>I've read the <a href="http://www.python.org/doc/2.5.2/lib/matching-searching.html">documentation</a> (<a href="http://docs.python.org/2/library/re.html?highlight=matching%20searching#search-vs-match">current documentation</a>), but I never seem to remember it. I keep having to look it up and re-learn it. I'm hoping that someone will answer it clearly with examples so that (perhaps) it will stick in my head. Or at least I'll have a better place to return with my question and it will take less time to re-learn it.</p>
| 189 | 2008-10-08T00:51:36Z | 181,000 | <p>re.match attempts to match a pattern <strong>at the beginning of the string</strong>. re.search attempts to match the pattern <strong>throughout the string</strong> until it finds a match.</p>
| 9 | 2008-10-08T00:54:57Z | [
"python",
"regex",
"search",
"match"
] |
What is the difference between Python's re.search and re.match? | 180,986 | <p>What is the difference between the <code>search()</code> and <code>match()</code> functions in the <a href="http://docs.python.org/2/library/re.html">Python <code>re</code> module</a>?</p>
<p>I've read the <a href="http://www.python.org/doc/2.5.2/lib/matching-searching.html">documentation</a> (<a href="http://docs.python.org/2/library/re.html?highlight=matching%20searching#search-vs-match">current documentation</a>), but I never seem to remember it. I keep having to look it up and re-learn it. I'm hoping that someone will answer it clearly with examples so that (perhaps) it will stick in my head. Or at least I'll have a better place to return with my question and it will take less time to re-learn it.</p>
| 189 | 2008-10-08T00:51:36Z | 181,001 | <p>Have you had a look at the <a href="http://docs.python.org/library/re.html#matching-vs-searching" rel="nofollow">documentation</a>?</p>
<blockquote>
<p>Python offers two different primitive operations based on regular expressions: match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string (this is what Perl does by default).</p>
</blockquote>
| 4 | 2008-10-08T00:55:28Z | [
"python",
"regex",
"search",
"match"
] |
What is the difference between Python's re.search and re.match? | 180,986 | <p>What is the difference between the <code>search()</code> and <code>match()</code> functions in the <a href="http://docs.python.org/2/library/re.html">Python <code>re</code> module</a>?</p>
<p>I've read the <a href="http://www.python.org/doc/2.5.2/lib/matching-searching.html">documentation</a> (<a href="http://docs.python.org/2/library/re.html?highlight=matching%20searching#search-vs-match">current documentation</a>), but I never seem to remember it. I keep having to look it up and re-learn it. I'm hoping that someone will answer it clearly with examples so that (perhaps) it will stick in my head. Or at least I'll have a better place to return with my question and it will take less time to re-learn it.</p>
| 189 | 2008-10-08T00:51:36Z | 181,028 | <p><code>re.search</code> <strong>search</strong>es for the pattern <strong>throughout the string</strong>, whereas <code>re.match</code> does <em>not search</em> the pattern; if it does not, it has no other choice than to <strong>match</strong> it at start of the string.</p>
| 37 | 2008-10-08T01:07:26Z | [
"python",
"regex",
"search",
"match"
] |
What is the difference between Python's re.search and re.match? | 180,986 | <p>What is the difference between the <code>search()</code> and <code>match()</code> functions in the <a href="http://docs.python.org/2/library/re.html">Python <code>re</code> module</a>?</p>
<p>I've read the <a href="http://www.python.org/doc/2.5.2/lib/matching-searching.html">documentation</a> (<a href="http://docs.python.org/2/library/re.html?highlight=matching%20searching#search-vs-match">current documentation</a>), but I never seem to remember it. I keep having to look it up and re-learn it. I'm hoping that someone will answer it clearly with examples so that (perhaps) it will stick in my head. Or at least I'll have a better place to return with my question and it will take less time to re-learn it.</p>
| 189 | 2008-10-08T00:51:36Z | 8,687,988 | <p><code>search</code> ⇒ find something anywhere in the string and return a match object.</p>
<p><code>match</code> ⇒ find something at the <em>beginning</em> of the string and return a match object.</p>
| 32 | 2011-12-31T12:05:43Z | [
"python",
"regex",
"search",
"match"
] |
What is the difference between Python's re.search and re.match? | 180,986 | <p>What is the difference between the <code>search()</code> and <code>match()</code> functions in the <a href="http://docs.python.org/2/library/re.html">Python <code>re</code> module</a>?</p>
<p>I've read the <a href="http://www.python.org/doc/2.5.2/lib/matching-searching.html">documentation</a> (<a href="http://docs.python.org/2/library/re.html?highlight=matching%20searching#search-vs-match">current documentation</a>), but I never seem to remember it. I keep having to look it up and re-learn it. I'm hoping that someone will answer it clearly with examples so that (perhaps) it will stick in my head. Or at least I'll have a better place to return with my question and it will take less time to re-learn it.</p>
| 189 | 2008-10-08T00:51:36Z | 31,715,754 | <p>you can refer the below example to understand the working of re.match and re.search</p>
<pre><code>a = "123abc"
t = re.match("[a-z]+",a)
t = re.search("[a-z]+",a)
</code></pre>
<p>re.match will return none, but re.search will return abc.</p>
| 6 | 2015-07-30T05:27:27Z | [
"python",
"regex",
"search",
"match"
] |
What is the difference between Python's re.search and re.match? | 180,986 | <p>What is the difference between the <code>search()</code> and <code>match()</code> functions in the <a href="http://docs.python.org/2/library/re.html">Python <code>re</code> module</a>?</p>
<p>I've read the <a href="http://www.python.org/doc/2.5.2/lib/matching-searching.html">documentation</a> (<a href="http://docs.python.org/2/library/re.html?highlight=matching%20searching#search-vs-match">current documentation</a>), but I never seem to remember it. I keep having to look it up and re-learn it. I'm hoping that someone will answer it clearly with examples so that (perhaps) it will stick in my head. Or at least I'll have a better place to return with my question and it will take less time to re-learn it.</p>
| 189 | 2008-10-08T00:51:36Z | 37,363,575 | <p>The difference is, <strong><code>re.match()</code> misleads anyone accustomed to <em>Perl</em>, <em>grep</em>, or <em>sed</em> regular expression matching, and <code>re.search()</code> does not.</strong> :-)</p>
<p>More soberly, <a href="http://www.johndcook.com/blog/python_regex/" rel="nofollow">As John D. Cook remarks</a>, <code>re.match()</code> "behaves as if every pattern has ^ prepended." In other words, <code>re.match('pattern')</code> equals <code>re.search('^pattern')</code>. So it anchors a pattern's left side. But it also <em>doesn't anchor a pattern's right side:</em> that still requires a terminating <code>$</code>.</p>
<p>Frankly given the above, I think <code>re.match()</code> should be deprecated. I would be interested to know reasons it should be retained.</p>
| 4 | 2016-05-21T13:28:47Z | [
"python",
"regex",
"search",
"match"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 181,553 | <p>This doesn't improve so much but...</p>
<pre><code>allCondsAreOK = (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4')
if allCondsAreOK:
do_something
</code></pre>
| 11 | 2008-10-08T06:31:54Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 181,557 | <p>You don't need to use 4 spaces on your second conditional line. Maybe use:</p>
<pre><code>if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Also, don't forget the whitespace is more flexible than you might think:</p>
<pre><code>if (
cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'
):
do_something
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Both of those are fairly ugly though.</p>
<p>Maybe lose the brackets (the <a href="https://www.python.org/dev/peps/pep-0008/#multiline-if-statements">Style Guide</a> discourages this though)?</p>
<pre><code>if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and cond4 == 'val4':
do_something
</code></pre>
<p>This at least gives you some differentiation.</p>
<p>Or even:</p>
<pre><code>if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_something
</code></pre>
<p>I think I prefer:</p>
<pre><code>if cond1 == 'val1' and \
cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_something
</code></pre>
<p>Here's the <a href="https://www.python.org/dev/peps/pep-0008/#multiline-if-statements">Style Guide</a>, which (since 2010) recommends using brackets.</p>
| 296 | 2008-10-08T06:34:25Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 181,641 | <p>I suggest moving the <code>and</code> keyword to the second line and indenting all lines containing conditions with two spaces instead of four:</p>
<pre><code>if (cond1 == 'val1' and cond2 == 'val2'
and cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>This is exactly how I solve this problem in my code. Having a keyword as the first word in the line makes the condition a lot more readable, and reducing the number of spaces further distinguishes condition from action.</p>
| 13 | 2008-10-08T07:19:09Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 181,848 | <p>I prefer this style when I have a terribly large if-condition:</p>
<pre><code>if (
expr1
and (expr2 or expr3)
and hasattr(thingy1, '__eq__')
or status=="HappyTimes"
):
do_stuff()
else:
do_other_stuff()
</code></pre>
| 11 | 2008-10-08T08:39:58Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 182,050 | <p>I've resorted to the following in the degenerate case where it's simply AND's or OR's.</p>
<pre><code>if all( [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4'] ):
if any( [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4'] ):
</code></pre>
<p>It shaves a few characters and makes it clear that there's no subtlety to the condition.</p>
| 61 | 2008-10-08T10:26:48Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 182,067 | <p>"all" and "any" are nice for the many conditions of same type case. BUT they always evaluates all conditions. As shown in this example:</p>
<pre><code>def c1():
print " Executed c1"
return False
def c2():
print " Executed c2"
return False
print "simple and (aborts early!)"
if c1() and c2():
pass
print
print "all (executes all :( )"
if all((c1(),c2())):
pass
print
</code></pre>
| 2 | 2008-10-08T10:38:37Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 183,206 | <p><em>Someone</em> has to champion use of vertical whitespace here! :)</p>
<pre><code>if ( cond1 == val1
and cond2 == val2
and cond3 == val3
):
do_stuff()
</code></pre>
<p>This makes each condition clearly visible. It also allows cleaner expression of more complex conditions:</p>
<pre><code>if ( cond1 == val1
or
( cond2_1 == val2_1
and cond2_2 >= val2_2
and cond2_3 != bad2_3
)
):
do_more_stuff()
</code></pre>
<p>Yes, we're trading off a bit of vertical real estate for clarity. Well worth it IMO.</p>
| 27 | 2008-10-08T14:55:02Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 183,889 | <p>Just a few other random ideas for completeness's sake. If they work for you, use them. Otherwise, you're probably better off trying something else.</p>
<p>You could also do this with a dictionary:</p>
<pre><code>>>> x = {'cond1' : 'val1', 'cond2' : 'val2'}
>>> y = {'cond1' : 'val1', 'cond2' : 'val2'}
>>> x == y
True
</code></pre>
<p>This option is more complicated, but you may also find it useful:</p>
<pre><code>class Klass(object):
def __init__(self, some_vars):
#initialize conditions here
def __nonzero__(self):
return (self.cond1 == 'val1' and self.cond2 == 'val2' and
self.cond3 == 'val3' and self.cond4 == 'val4')
foo = Klass()
if foo:
print "foo is true!"
else:
print "foo is false!"
</code></pre>
<p>Dunno if that works for you, but it's another option to consider. Here's one more way:</p>
<pre><code>class Klass(object):
def __init__(self):
#initialize conditions here
def __eq__(self):
return (self.cond1 == 'val1' and self.cond2 == 'val2' and
self.cond3 == 'val3' and self.cond4 == 'val4')
x = Klass(some_values)
y = Klass(some_other_values)
if x == y:
print 'x == y'
else:
print 'x!=y'
</code></pre>
<p>The last two I haven't tested, but the concepts should be enough to get you going if that's what you want to go with.</p>
<p>(And for the record, if this is just a one time thing, you're probably just better off using the method you presented at first. If you're doing the comparison in lots of places, these methods may enhance readability enough to make you not feel so bad about the fact that they are kind of hacky.)</p>
| 1 | 2008-10-08T17:26:00Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 185,748 | <p>What if we only insert an additional blank line between the condition and the body and do the rest in the canonical way?</p>
<pre><code>if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>p.s. I always use tabs, not spaces; I cannot fine-tune...</p>
| 2 | 2008-10-09T02:45:40Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 3,004,525 | <p>Pack your conditions into a list, then do smth. like:</p>
<pre><code>if False not in Conditions:
do_something
</code></pre>
| 0 | 2010-06-09T09:23:43Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 4,689,224 | <p>(I've lightly modified the identifiers as fixed-width names aren't representative of real code â at least not real code that I encounter â and will belie an example's readability.)</p>
<pre><code>if (cond1 == "val1" and cond22 == "val2"
and cond333 == "val3" and cond4444 == "val4"):
do_something
</code></pre>
<p>This works well for "and" and "or" (it's important that they're first on the second line), but much less so for other long conditions. Fortunately, the former seem to be the more common case while the latter are often easily rewritten with a temporary variable. (It's usually not hard, but it can be difficult or much less obvious/readable to preserve the short-circuiting of "and"/"or" when rewriting.)</p>
<p>Since I found this question from <a href="http://eli.thegreenplace.net/2011/01/14/how-python-affected-my-cc-brace-style/" rel="nofollow">your blog post about C++</a>, I'll include that my C++ style is identical:</p>
<pre><code>if (cond1 == "val1" and cond22 == "val2"
and cond333 == "val3" and cond4444 == "val4") {
do_something
}
</code></pre>
| 1 | 2011-01-14T08:33:47Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 4,690,241 | <p>Here's my very personal take: long conditions are (in my view) a code smell that suggests refactoring into a boolean-returning function/method. For example:</p>
<pre><code>def is_action__required(...):
return (cond1 == 'val1' and cond2 == 'val2'
and cond3 == 'val3' and cond4 == 'val4')
</code></pre>
<p>Now, if I found a way to make multi-line conditions look good, I would probably find myself content with having them and skip the refactoring.</p>
<p>On the other hand, having them perturb my aesthetic sense acts as an incentive for refactoring.</p>
<p>My conclusion, therefore, is that multiple line conditions should look ugly and this is an incentive to avoid them.</p>
| 12 | 2011-01-14T10:50:32Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 4,692,294 | <p>I'm surprised not to see my preferred solution,</p>
<pre><code>if (cond1 == 'val1' and cond2 == 'val2'
and cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Since <code>and</code> is a keyword, it gets highlighted by my editor, and looks sufficiently different from the do_something below it.</p>
| 4 | 2011-01-14T14:50:50Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 4,740,630 | <p>Adding to what @krawyoti said... Long conditions smell because they are difficult to read and difficult to understand. Using a function or a variable makes the code clearer. In Python, I prefer to use vertical space, enclose parenthesis, and place the logical operators at the beginning of each line so the expressions don't look like "floating".</p>
<pre><code>conditions_met = (
cond1 == 'val1'
and cond2 == 'val2'
and cond3 == 'val3'
and cond4 == 'val4'
)
if conditions_met:
do_something
</code></pre>
<p>If the conditions need to be evaluated more than once, as in a <code>while</code> loop, then using a local function is best.</p>
| 2 | 2011-01-19T20:53:39Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 7,511,872 | <p>I find that when I have long conditions, I often have a short code body. In that case, I just double-indent the body, thus:</p>
<pre><code>if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
| 0 | 2011-09-22T08:31:27Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 9,682,878 | <pre><code> if cond1 == 'val1' and \
cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_something
</code></pre>
<p>or if this is clearer:</p>
<pre><code> if cond1 == 'val1'\
and cond2 == 'val2'\
and cond3 == 'val3'\
and cond4 == 'val4':
do_something
</code></pre>
<p>There is no reason indent should be a multiple of 4 in this case, e.g. see "Aligned with opening delimiter":</p>
<p><a href="http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Indentation#Indentation" rel="nofollow">http://google-styleguide.googlecode.com/svn/trunk/pyguide.html?showone=Indentation#Indentation</a></p>
| 0 | 2012-03-13T11:13:19Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 15,264,532 | <p>Personally, I like to add meaning to long if-statements. I would have to search through code to find an appropriate example, but here's the first example that comes to mind: let's say I happen to run into some quirky logic where I want to display a certain page depending on many variables.</p>
<p>English: "If the logged-in user is NOT an administrator teacher, but is just a regular teacher, and is not a student themselves..."</p>
<pre><code>if not user.isAdmin() and user.isTeacher() and not user.isStudent():
doSomething()
</code></pre>
<p>Sure this might look fine, but reading those if statements is a lot of work. How about we assign the logic to label that makes sense. The "label" is actually the variable name:</p>
<pre><code>displayTeacherPanel = not user.isAdmin() and user.isTeacher() and not user.isStudent()
if displayTeacherPanel:
showTeacherPanel()
</code></pre>
<p>This may seem silly, but you might have yet another condition where you ONLY want to display another item if, and only if, you're displaying the teacher panel OR if the user has access to that other specific panel by default:</p>
<pre><code>if displayTeacherPanel or user.canSeeSpecialPanel():
showSpecialPanel()
</code></pre>
<p>Try writing the above condition without using variables to store and label your logic, and not only do you end up with a very messy, hard-to-read logical statement, but you also just repeated yourself. While there are reasonable exceptions, remember: Don't Repeat Yourself (DRY).</p>
| 2 | 2013-03-07T06:24:12Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 25,085,957 | <p>What I usually do is:</p>
<pre><code>if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'
):
do_something
</code></pre>
<p>this way the closing brace and colon visually mark the end of our condition.</p>
| 1 | 2014-08-01T17:53:44Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 26,414,728 | <p>Here's another approach:</p>
<pre><code>cond_list = ['cond1 == "val1"','cond2=="val2"','cond3=="val3"','cond4=="val4"']
if all([eval(i) for i in cond_list]):
do something
</code></pre>
<p>This also makes it easy to add another condition easily without changing the if statement by simply appending another condition to the list:</p>
<pre><code>cond_list.append('cond5=="val5"')
</code></pre>
| 0 | 2014-10-16T22:08:03Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 27,008,512 | <p>Here's what I do, remember that "all" and "any" accepts an iterable, so I just put a long condition in a list and let "all" do the work.</p>
<pre><code>condition = [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4']
if all(condition):
do_something
</code></pre>
| 4 | 2014-11-19T03:34:33Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 27,100,017 | <p>Plain and simple, also passes pep8 checks:</p>
<pre><code>if (
cond1 and
cond2
):
print("Hello World!")
</code></pre>
<hr>
<p>In recent times I have been preferring the <code>all</code> and <code>any</code> functions, since I rarely mix And and Or comparisons this works well, and has the additional advantage of Failing Early with generators comprehension:</p>
<pre><code>if all([
cond1,
cond2,
]):
print("Hello World!")
</code></pre>
<p>Just remember to pass in a single iterable! Passing in N-arguments is not correct.</p>
<p>Note: <code>any</code> is like many <code>or</code> comparisons, <code>all</code> is like many <code>and</code> comparisons.</p>
<hr>
<p>This combines nicely with generator comprehensions, for example:</p>
<pre><code># Check if every string in a list contains a substring:
my_list = [
'a substring is like a string',
'another substring'
]
if all('substring' in item for item in my_list):
print("Hello World!")
# or
if all(
'substring' in item
for item in my_list
):
print("Hello World!")
</code></pre>
<p>More on: <a href="http://stackoverflow.com/q/364802/1695680">generator comprehension</a></p>
| 1 | 2014-11-24T07:44:29Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 27,279,883 | <p>I've been struggling to find a decent way to do this as well, so I just came up with an idea (not a silver bullet, since this is mainly a matter of taste).</p>
<pre><code>if bool(condition1 and
condition2 and
...
conditionN):
foo()
bar()
</code></pre>
<p>I find a few merits in this solution compared to others I've seen, namely, you get exactly an extra 4 spaces of indentation (bool), allowing all conditions to line up vertically, and the body of the if statement can be indented in a clear(ish) way. This also keeps the benefits of short-circuit evaluation of boolean operators, but of course adds the overhead of a function call that basically does nothing. You could argue (validly) that any function returning its argument could be used here instead of bool, but like I said, it's just an idea and it's ultimately a matter of taste.</p>
<p>Funny enough, as I was writing this and thinking about the "problem", I came up with <em>yet another</em> idea, which removes the overhead of a function call. Why not indicate that we're about to enter a complex condition by using extra pairs of parentheses? Say, 2 more, to give a nice 2 space indent of the sub-conditions relative to the body of the if statement. Example:</p>
<pre><code>if (((foo and
bar and
frob and
ninja_bear))):
do_stuff()
</code></pre>
<p>I kind of like this because when you look at it, a bell immediatelly rings in your head saying <em>"hey, there's a complex thing going on here!"</em>. Yes, I know that parentheses don't help readability, but these conditions should appear rarely enough, and when they do show up, you are going to have to stop and read them carefuly anyway (because they're <strong>complex</strong>).</p>
<p>Anyway, just two more proposals that I haven't seen here. Hope this helps someone :)</p>
| 1 | 2014-12-03T19:19:18Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 28,867,664 | <p>I usually use: </p>
<pre class="lang-py prettyprint-override"><code>if ((cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4')):
do_something()
</code></pre>
| 0 | 2015-03-05T00:12:32Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 31,231,248 | <p>It seems worth quoting <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP 0008</a> (Python's official style guide), since it comments upon this issue at modest length:</p>
<blockquote>
<p>When the conditional part of an <code>if</code> -statement is long enough to require that it be written across multiple lines, it's worth noting that the combination of a two character keyword (i.e. <code>if</code> ), plus a single space, plus an opening parenthesis creates a natural 4-space indent for the subsequent lines of the multiline conditional. This can produce a visual conflict with the indented suite of code nested inside the <code>if</code> -statement, which would also naturally be indented to 4 spaces. This PEP takes no explicit position on how (or whether) to further visually distinguish such conditional lines from the nested suite inside the <code>if</code> -statement. Acceptable options in this situation include, but are not limited to:</p>
<pre><code># No extra indentation.
if (this_is_one_thing and
that_is_another_thing):
do_something()
# Add a comment, which will provide some distinction in editors
# supporting syntax highlighting.
if (this_is_one_thing and
that_is_another_thing):
# Since both conditions are true, we can frobnicate.
do_something()
# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
and that_is_another_thing):
do_something()
</code></pre>
</blockquote>
<p>Note the "not limited to" in the quote above; besides the approaches suggested in the style guide, some of the ones suggested in other answers to this question are acceptable too.</p>
| 3 | 2015-07-05T14:15:27Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 34,117,413 | <p>if our if & an else condition has to execute multiple statement inside of it than we can write like below.
Every when we have if else example with one statement inside of it .</p>
<p>Thanks it work for me.</p>
<pre><code>#!/usr/bin/python
import sys
numberOfArgument =len(sys.argv)
weblogic_username =''
weblogic_password = ''
weblogic_admin_server_host =''
weblogic_admin_server_port =''
if numberOfArgument == 5:
weblogic_username = sys.argv[1]
weblogic_password = sys.argv[2]
weblogic_admin_server_host =sys.argv[3]
weblogic_admin_server_port=sys.argv[4]
elif numberOfArgument <5:
print " weblogic UserName, weblogic Password and weblogic host details are Mandatory like, defalutUser, passwordForDefaultUser, t3s://server.domainname:7001 ."
weblogic_username = raw_input("Enter Weblogic user Name")
weblogic_password = raw_input('Enter Weblogic user Password')
weblogic_admin_server_host = raw_input('Enter Weblogic admin host ')
weblogic_admin_server_port = raw_input('Enter Weblogic admin port')
#enfelif
#endIf
</code></pre>
| 0 | 2015-12-06T12:27:55Z | [
"python",
"coding-style",
"if-statement"
] |
Python style: multiple-line conditions in IFs | 181,530 | <p>Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is:</p>
<pre><code> if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.</p>
<p>For the moment I'm using:</p>
<pre><code> if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
</code></pre>
<p>But this isn't very pretty. :-)</p>
<p>Can you recommend an alternative way ?</p>
| 270 | 2008-10-08T06:19:07Z | 38,775,892 | <p>You could split it into two lines</p>
<pre><code>total = cond1 == 'val' and cond2 == 'val2' and cond3 == 'val3' and cond4 == val4
if total:
do_something()
</code></pre>
<p>Or even add on one condition at a time. That way, at least it separates the clutter from the <code>if</code>.</p>
| 0 | 2016-08-04T19:30:45Z | [
"python",
"coding-style",
"if-statement"
] |
What is the problem with reduce()? | 181,543 | <p>There seems to be a lot of heated discussion on the net about the changes to the reduce() function in python 3.0 and how it should be removed. I am having a little difficulty understanding why this is the case; I find it quite reasonable to use it in a variety of cases. If the contempt was simply subjective, I cannot imagine that such a large number of people would care about it. </p>
<p>What am I missing? What is the problem with reduce()?</p>
| 47 | 2008-10-08T06:27:12Z | 181,593 | <p>People worry it encourages an obfuscated style of programming, doing something that can be achieved with clearer methods.</p>
<p>I'm not against reduce myself, I also find it a useful tool sometimes.</p>
| 7 | 2008-10-08T06:53:54Z | [
"python",
"python-3.x"
] |
What is the problem with reduce()? | 181,543 | <p>There seems to be a lot of heated discussion on the net about the changes to the reduce() function in python 3.0 and how it should be removed. I am having a little difficulty understanding why this is the case; I find it quite reasonable to use it in a variety of cases. If the contempt was simply subjective, I cannot imagine that such a large number of people would care about it. </p>
<p>What am I missing? What is the problem with reduce()?</p>
| 47 | 2008-10-08T06:27:12Z | 181,646 | <p><code>reduce()</code> is not being removed -- it's simply being moved into the <code>functools</code> module. Guido's reasoning is that except for trivial cases like summation, code written using <code>reduce()</code> is usually clearer when written as an accumulation loop.</p>
| 24 | 2008-10-08T07:20:43Z | [
"python",
"python-3.x"
] |
What is the problem with reduce()? | 181,543 | <p>There seems to be a lot of heated discussion on the net about the changes to the reduce() function in python 3.0 and how it should be removed. I am having a little difficulty understanding why this is the case; I find it quite reasonable to use it in a variety of cases. If the contempt was simply subjective, I cannot imagine that such a large number of people would care about it. </p>
<p>What am I missing? What is the problem with reduce()?</p>
| 47 | 2008-10-08T06:27:12Z | 181,706 | <p>As Guido says in his <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=98196">The fate of reduce() in Python 3000</a> post:</p>
<blockquote>
<p>So now reduce(). This is actually the one I've always hated most, because, apart from a few examples involving + or *, almost every time I see a reduce() call with a non-trivial function argument, I need to grab pen and paper to diagram what's actually being fed into that function before I understand what the reduce() is supposed to do. So in my mind, the applicability of reduce() is pretty much limited to associative operators, and in all other cases it's better to write out the accumulation loop explicitly. </p>
</blockquote>
<p>There is an excellent example of a confusing <code>reduce</code> in the <a href="http://www.amk.ca/python/writing/functional">Functional Programming HOWTO</a> article:</p>
<blockquote>
<p>Quick, what's the following code doing?</p>
<pre><code>total = reduce(lambda a, b: (0, a[1] + b[1]), items)[1]
</code></pre>
<p>You can figure it out, but it takes time to disentangle the expression to figure out
what's going on. Using a short nested def statements makes things a little bit better:</p>
<pre><code>def combine (a, b):
return 0, a[1] + b[1]
total = reduce(combine, items)[1]
</code></pre>
<p>But it would be best of all if I had simply used a for loop:</p>
<pre><code>total = 0
for a, b in items:
total += b
</code></pre>
<p>Or the sum() built-in and a generator expression:</p>
<pre><code>total = sum(b for a,b in items)
</code></pre>
<p>Many uses of reduce() are clearer when written as for loops.</p>
</blockquote>
| 56 | 2008-10-08T07:42:12Z | [
"python",
"python-3.x"
] |
py2exe including MSVC DLLs in the .exe | 181,556 | <p>When using py2exe to distribute Python applications with wxPython, some MSVC DLLs are usually needed to make the .exe work on freshly installed machines. In particular, the two most common DLLs are msvcp71.dll and msvcr71.dll</p>
<p>The former can be included in the .exe using <a href="http://www.py2exe.org/index.cgi/OverridingCriteraForIncludingDlls" rel="nofollow">this tip</a>. However, the latter is just placed in the <code>dist</code> dir by py2exe and not into the executable, even if I specifically ask to include it.</p>
<p>Any idea how to cause py2exe to include both inside the .exe ?</p>
| 4 | 2008-10-08T06:34:21Z | 181,583 | <p>Wouldn't it fail to launch, then? You want <code>msvcr71.dll</code> in the same directory as the exe, so that the library loader will be able to find and link it into the application's memory map. </p>
<p>It's needed for basic operation, so you can't just let <code>py2exe</code> unpack it with the rest of the DLLs.</p>
| 6 | 2008-10-08T06:46:57Z | [
"python",
"dll",
"py2exe"
] |
py2exe including MSVC DLLs in the .exe | 181,556 | <p>When using py2exe to distribute Python applications with wxPython, some MSVC DLLs are usually needed to make the .exe work on freshly installed machines. In particular, the two most common DLLs are msvcp71.dll and msvcr71.dll</p>
<p>The former can be included in the .exe using <a href="http://www.py2exe.org/index.cgi/OverridingCriteraForIncludingDlls" rel="nofollow">this tip</a>. However, the latter is just placed in the <code>dist</code> dir by py2exe and not into the executable, even if I specifically ask to include it.</p>
<p>Any idea how to cause py2exe to include both inside the .exe ?</p>
| 4 | 2008-10-08T06:34:21Z | 182,059 | <p>py2exe can't do this. You can wrap py2exe (there is <a href="http://py2exe.org/index.cgi/SingleFileExecutable" rel="nofollow">an example on the wiki</a> showing how to do that with NSIS); you could build your own wrapper if using NSIS or InnoSetup wasn't an option.</p>
<p>Alternatively, if you're positive that your users will have a compatible copy of msvcr71.dll installed (IIRC Vista or XP SP2 users), then you could get away without including it. More usefully, perhaps, if you use Python 2.3 (or older), then Python links against msvcr.dll rather than msvcr71.dll, and any Windows user will have that installed, so you can just not worry about it.</p>
| 1 | 2008-10-08T10:31:51Z | [
"python",
"dll",
"py2exe"
] |
py2exe including MSVC DLLs in the .exe | 181,556 | <p>When using py2exe to distribute Python applications with wxPython, some MSVC DLLs are usually needed to make the .exe work on freshly installed machines. In particular, the two most common DLLs are msvcp71.dll and msvcr71.dll</p>
<p>The former can be included in the .exe using <a href="http://www.py2exe.org/index.cgi/OverridingCriteraForIncludingDlls" rel="nofollow">this tip</a>. However, the latter is just placed in the <code>dist</code> dir by py2exe and not into the executable, even if I specifically ask to include it.</p>
<p>Any idea how to cause py2exe to include both inside the .exe ?</p>
| 4 | 2008-10-08T06:34:21Z | 22,450,019 | <p>Yes, py2exe can do this. <a href="http://www.py2exe.org/index.cgi/OverridingCriteraForIncludingDlls" rel="nofollow">View this link.</a>And if you are using python2.7, replace "msvcr71" to "msvcp90".</p>
| 1 | 2014-03-17T08:51:08Z | [
"python",
"dll",
"py2exe"
] |
wxPython: displaying multiple widgets in same frame | 181,573 | <p>I would like to be able to display <code>Notebook</code> and a <code>TxtCtrl</code> wx widgets in a single frame. Below is an example adapted from the wxpython wiki; is it possible to change their layout (maybe with something like <code>wx.SplitterWindow</code>) to display the text box below the <code>Notebook</code> in the same frame?</p>
<pre><code>import wx
import wx.lib.sheet as sheet
class MySheet(sheet.CSheet):
def __init__(self, parent):
sheet.CSheet.__init__(self, parent)
self.SetLabelBackgroundColour('#CCFF66')
self.SetNumberRows(50)
self.SetNumberCols(50)
class Notebook(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(600, 600))
menubar = wx.MenuBar()
file = wx.Menu()
file.Append(101, 'Quit', '' )
menubar.Append(file, "&File")
self.SetMenuBar(menubar)
wx.EVT_MENU(self, 101, self.OnQuit)
nb = wx.Notebook(self, -1, style=wx.NB_BOTTOM)
self.sheet1 = MySheet(nb)
self.sheet2 = MySheet(nb)
self.sheet3 = MySheet(nb)
nb.AddPage(self.sheet1, "Sheet1")
nb.AddPage(self.sheet2, "Sheet2")
nb.AddPage(self.sheet3, "Sheet3")
self.sheet1.SetFocus()
self.StatusBar()
def StatusBar(self):
self.statusbar = self.CreateStatusBar()
def OnQuit(self, event):
self.Close()
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(450, 400))
self.text = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE)
self.Center()
class MyApp(wx.App):
def OnInit(self):
frame = Notebook(None, -1, 'notebook.py')
frame.Show(True)
frame.Center()
frame2 = MyFrame(None, -1, '')
frame2.Show(True)
self.SetTopWindow(frame2)
return True
app = MyApp(0)
app.MainLoop()
</code></pre>
| 2 | 2008-10-08T06:41:18Z | 181,591 | <p>You can use a splitter, yes.</p>
<p>Also, it makes sense to create a Panel, place your widgets in it (with sizers), and add this panel to the Frame.</p>
| 1 | 2008-10-08T06:52:03Z | [
"python",
"user-interface",
"layout",
"wxpython",
"wxwidgets"
] |
wxPython: displaying multiple widgets in same frame | 181,573 | <p>I would like to be able to display <code>Notebook</code> and a <code>TxtCtrl</code> wx widgets in a single frame. Below is an example adapted from the wxpython wiki; is it possible to change their layout (maybe with something like <code>wx.SplitterWindow</code>) to display the text box below the <code>Notebook</code> in the same frame?</p>
<pre><code>import wx
import wx.lib.sheet as sheet
class MySheet(sheet.CSheet):
def __init__(self, parent):
sheet.CSheet.__init__(self, parent)
self.SetLabelBackgroundColour('#CCFF66')
self.SetNumberRows(50)
self.SetNumberCols(50)
class Notebook(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(600, 600))
menubar = wx.MenuBar()
file = wx.Menu()
file.Append(101, 'Quit', '' )
menubar.Append(file, "&File")
self.SetMenuBar(menubar)
wx.EVT_MENU(self, 101, self.OnQuit)
nb = wx.Notebook(self, -1, style=wx.NB_BOTTOM)
self.sheet1 = MySheet(nb)
self.sheet2 = MySheet(nb)
self.sheet3 = MySheet(nb)
nb.AddPage(self.sheet1, "Sheet1")
nb.AddPage(self.sheet2, "Sheet2")
nb.AddPage(self.sheet3, "Sheet3")
self.sheet1.SetFocus()
self.StatusBar()
def StatusBar(self):
self.statusbar = self.CreateStatusBar()
def OnQuit(self, event):
self.Close()
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(450, 400))
self.text = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE)
self.Center()
class MyApp(wx.App):
def OnInit(self):
frame = Notebook(None, -1, 'notebook.py')
frame.Show(True)
frame.Center()
frame2 = MyFrame(None, -1, '')
frame2.Show(True)
self.SetTopWindow(frame2)
return True
app = MyApp(0)
app.MainLoop()
</code></pre>
| 2 | 2008-10-08T06:41:18Z | 181,626 | <p>Making two widgets appear on the same frame is easy, actually. You should use sizers to accomplish this.</p>
<p>In your example, you can change your <code>Notebook</code> class implementation to something like this:</p>
<pre><code>class Notebook(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title, size=(600, 600))
menubar = wx.MenuBar()
file = wx.Menu()
file.Append(101, 'Quit', '' )
menubar.Append(file, "&File")
self.SetMenuBar(menubar)
wx.EVT_MENU(self, 101, self.OnQuit)
nb = wx.Notebook(self, -1, style=wx.NB_BOTTOM)
self.sheet1 = MySheet(nb)
self.sheet2 = MySheet(nb)
self.sheet3 = MySheet(nb)
nb.AddPage(self.sheet1, "Sheet1")
nb.AddPage(self.sheet2, "Sheet2")
nb.AddPage(self.sheet3, "Sheet3")
self.sheet1.SetFocus()
self.StatusBar()
# new code begins here:
# add your text ctrl:
self.text = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE)
# create a new sizer for both controls:
sizer = wx.BoxSizer(wx.VERTICAL)
# add notebook first, with size factor 2:
sizer.Add(nb, 2)
# then text, size factor 1, maximized
sizer.Add(self.text, 1, wx.EXPAND)
# assign the sizer to Frame:
self.SetSizerAndFit(sizer)
</code></pre>
<p>Only the <code>__init__</code> method is changed. Note that you can manipulate the proportions between the notebook and text control by changing the second argument of the <code>Add</code> method.</p>
<p>You can learn more about sizers from the official <a href="http://docs.wxwidgets.org/2.8/wx_sizeroverview.html">Sizer overview</a> article.</p>
| 8 | 2008-10-08T07:11:08Z | [
"python",
"user-interface",
"layout",
"wxpython",
"wxwidgets"
] |
Problem opening berkeley db in python | 181,648 | <p>I have problems opening a berkeley db in python using bdtables. As bdtables is used by the library I am using to access the database, I need it to work.</p>
<p>The problem seems to be that the db environment I am trying to open (I got a copy of the database to open), is version 4.4 while libdb is version 4.6. I get the following error using bsddb.dbtables.bsdTableDB([dbname],[folder]):</p>
<pre><code>(-30972, "DB_VERSION_MISMATCH: Database environment version mismatch -- Program version 4.6 doesn't match environment version 4.4")
</code></pre>
<p>However, bsddb.btopen([dbname]) works.</p>
<p>I have also tried installing db4.4-util, db4.5-util and db4.6-util. Trying to use db4.6_verify results in:</p>
<pre><code>db4.6_verify: Program version 4.6 doesn't match environment version 4.4
db4.6_verify: DB_ENV->open: DB_VERSION_MISMATCH: Database environment version mismatchs
</code></pre>
<p>db4.4_verify results in the computer just hanging, and nothing happening.</p>
<p>Finally, if I run db4.4_recover on the database, that works. However, afterwards I get the following error 'No such file or directory' in python.</p>
| 3 | 2008-10-08T07:21:19Z | 185,678 | <p>I think answers should go in the "answer" section rather than as an addendum to the question since that marks the question as having an answer on the various question-list pages. I'll do that for you but, if you also get around to doing it, leave a comment on my answer so I can delete it.</p>
<p>Quoting "answer in question":</p>
<p>Verifying everything in this question, I eventually solved the problem. The 'No such file or directory' are caused by some __db.XXX files missing. Using</p>
<pre><code>bsddb.dbtables.bsdTableDB([dbname],[folder], create=1)
</code></pre>
<p>after db4.4_recover, these files got created and everything is now working.</p>
<p>Still, it was a bit of an obscure problem, and initially hard to figure out. But thanks to the question <a href="http://stackoverflow.com/questions/37644/examining-berkeley-db-files-from-the-cli">Examining Berkeley DB files from the CLI</a>, I got the tools I needed. I'll just post it here if someone ends up with the same problem in the future and end up at stackoverflow.com</p>
| 3 | 2008-10-09T02:16:06Z | [
"python",
"database",
"berkeley-db"
] |
Problem opening berkeley db in python | 181,648 | <p>I have problems opening a berkeley db in python using bdtables. As bdtables is used by the library I am using to access the database, I need it to work.</p>
<p>The problem seems to be that the db environment I am trying to open (I got a copy of the database to open), is version 4.4 while libdb is version 4.6. I get the following error using bsddb.dbtables.bsdTableDB([dbname],[folder]):</p>
<pre><code>(-30972, "DB_VERSION_MISMATCH: Database environment version mismatch -- Program version 4.6 doesn't match environment version 4.4")
</code></pre>
<p>However, bsddb.btopen([dbname]) works.</p>
<p>I have also tried installing db4.4-util, db4.5-util and db4.6-util. Trying to use db4.6_verify results in:</p>
<pre><code>db4.6_verify: Program version 4.6 doesn't match environment version 4.4
db4.6_verify: DB_ENV->open: DB_VERSION_MISMATCH: Database environment version mismatchs
</code></pre>
<p>db4.4_verify results in the computer just hanging, and nothing happening.</p>
<p>Finally, if I run db4.4_recover on the database, that works. However, afterwards I get the following error 'No such file or directory' in python.</p>
| 3 | 2008-10-08T07:21:19Z | 194,022 | <p>Damn, verifying everything in this question I eventually solved the problem. The 'No such file or directory' are caused by some __db.XXX files missing. Using bsddb.dbtables.bsdTableDB([dbname],[folder], create=1) after db4.4_recover, these files got created and everything is now working.</p>
<p>Still, it was a bit of an obscure problem, and initially hard to figure out. But thanks to the question Examining Berkeley DB files from the CLI I got the tools I needed. I'll just post it here if someone ends up with the same problem in the future and end up at stackoverflow.com</p>
| 0 | 2008-10-11T12:21:41Z | [
"python",
"database",
"berkeley-db"
] |
When to use the Python debugger | 181,724 | <p>Since Python is a dynamic, interpreted language you don't have to compile your code before running it. Hence, it's very easy to simply write your code, run it, see what problems occur, and fix them. Using hotkeys or macros can make this incredibly quick.</p>
<p>So, because it's so easy to immediately see the output of your program and any errors that may occur, I haven't uses a debugger tool yet. What situations may call for using a real debugger vs. the method I currently use?</p>
<p>I'd like to know before I get into a situation and get frustrated because I don't know how to fix the problem.</p>
| 5 | 2008-10-08T07:49:01Z | 181,761 | <p>Any time you want to inspect the contents of variables that may have caused the error. The only way you can do that is to stop execution and take a look at the stack.</p>
<p>pydev in Eclipse is a pretty good IDE if you are looking for one.</p>
| 2 | 2008-10-08T08:02:14Z | [
"python",
"debugging"
] |
When to use the Python debugger | 181,724 | <p>Since Python is a dynamic, interpreted language you don't have to compile your code before running it. Hence, it's very easy to simply write your code, run it, see what problems occur, and fix them. Using hotkeys or macros can make this incredibly quick.</p>
<p>So, because it's so easy to immediately see the output of your program and any errors that may occur, I haven't uses a debugger tool yet. What situations may call for using a real debugger vs. the method I currently use?</p>
<p>I'd like to know before I get into a situation and get frustrated because I don't know how to fix the problem.</p>
| 5 | 2008-10-08T07:49:01Z | 181,767 | <p>I use pdb for basic python debugging. Some of the situations I use it are:</p>
<ul>
<li>When you have a loop iterating over 100,000 entries and want to break at a specific point, it becomes really helpful.(conditional breaks)</li>
<li>Trace the control flow of someone else's code.</li>
<li>Its always better to use a debugger than litter the code with prints.</li>
<li>Normally there can be more than one point of failures resulting in a bug, all are not obvious in the first look. So you look for obvious places, if nothing is wrong there, you move ahead and add some more prints.. debugger can save you time here, you dont need to add the print and run again.</li>
</ul>
| 7 | 2008-10-08T08:04:08Z | [
"python",
"debugging"
] |
When to use the Python debugger | 181,724 | <p>Since Python is a dynamic, interpreted language you don't have to compile your code before running it. Hence, it's very easy to simply write your code, run it, see what problems occur, and fix them. Using hotkeys or macros can make this incredibly quick.</p>
<p>So, because it's so easy to immediately see the output of your program and any errors that may occur, I haven't uses a debugger tool yet. What situations may call for using a real debugger vs. the method I currently use?</p>
<p>I'd like to know before I get into a situation and get frustrated because I don't know how to fix the problem.</p>
| 5 | 2008-10-08T07:49:01Z | 181,768 | <p>Usually when the error is buried in some function, but I don't know exactly what or where. Either I insert dozens of <code>log.debug()</code> calls and then have to take them back out, or just put in:</p>
<pre><code>import pdb
pdb.set_trace ()
</code></pre>
<p>and then run the program. The debugger will launch when it reaches that point and give me a full REPL to poke around in.</p>
| 6 | 2008-10-08T08:04:12Z | [
"python",
"debugging"
] |
When to use the Python debugger | 181,724 | <p>Since Python is a dynamic, interpreted language you don't have to compile your code before running it. Hence, it's very easy to simply write your code, run it, see what problems occur, and fix them. Using hotkeys or macros can make this incredibly quick.</p>
<p>So, because it's so easy to immediately see the output of your program and any errors that may occur, I haven't uses a debugger tool yet. What situations may call for using a real debugger vs. the method I currently use?</p>
<p>I'd like to know before I get into a situation and get frustrated because I don't know how to fix the problem.</p>
| 5 | 2008-10-08T07:49:01Z | 182,010 | <p>In 30 years of programming I've used a debugger exactly 4 times. All four times were to read the <code>core</code> file produced from a C program crashing to locate the traceback information that's buried in there.</p>
<p>I don't think debuggers help much, even in compiled languages. Many people like debuggers, there are some reasons for using them, I'm sure, or people wouldn't lavish such love and care on them.</p>
<p>Here's the point -- <strong>software is knowledge capture</strong>. </p>
<p>Yes, it does have to run. More importantly, however, software has <strong>meaning</strong>.</p>
<p>This is not an indictment of <em>your</em> use of a debugger. However, I find that the folks who rely on debugging will sometimes produce really odd-looking code and won't have a good justification for what it <strong>means</strong>. They can only say "it may be a hack, but it works." </p>
<p>My suggestion on debuggers is "don't bother".</p>
<p>"But, what if I'm totally stumped?" you ask, "should I learn the debugger then?" Totally stumped by what? The language? Python's too simple for utter befuddlement. Some library? Perhaps.</p>
<p>Here's what you do -- with or without a debugger.</p>
<ol>
<li>You have the source, read it.</li>
<li>You write small tests to exercise the library. Using the interactive shell, if possible. [All the really good libraries seem to show their features using the interactive Python mode -- I strive for this level of tight, clear simplicity.]</li>
<li>You have the source, add print functions.</li>
</ol>
| 8 | 2008-10-08T10:09:56Z | [
"python",
"debugging"
] |
When to use the Python debugger | 181,724 | <p>Since Python is a dynamic, interpreted language you don't have to compile your code before running it. Hence, it's very easy to simply write your code, run it, see what problems occur, and fix them. Using hotkeys or macros can make this incredibly quick.</p>
<p>So, because it's so easy to immediately see the output of your program and any errors that may occur, I haven't uses a debugger tool yet. What situations may call for using a real debugger vs. the method I currently use?</p>
<p>I'd like to know before I get into a situation and get frustrated because I don't know how to fix the problem.</p>
| 5 | 2008-10-08T07:49:01Z | 183,563 | <p>I find it very useful to drop into a debugger in a failing test case.</p>
<p>I add <code>import pdb; pdb.set_trace()</code> just before the failure point of the test. The test runs, building up a potentially quite large context (e.g. importing a database fixture or constructing an HTTP request). When the test reaches the <code>pdb.set_trace()</code> line, it drops into the interactive debugger and I can inspect the context in which the failure occurs with the usual pdb commands looking for clues as to the cause.</p>
| 1 | 2008-10-08T16:07:57Z | [
"python",
"debugging"
] |
When to use the Python debugger | 181,724 | <p>Since Python is a dynamic, interpreted language you don't have to compile your code before running it. Hence, it's very easy to simply write your code, run it, see what problems occur, and fix them. Using hotkeys or macros can make this incredibly quick.</p>
<p>So, because it's so easy to immediately see the output of your program and any errors that may occur, I haven't uses a debugger tool yet. What situations may call for using a real debugger vs. the method I currently use?</p>
<p>I'd like to know before I get into a situation and get frustrated because I don't know how to fix the problem.</p>
| 5 | 2008-10-08T07:49:01Z | 14,683,302 | <p>You might want to take a look at this other SO post:</p>
<p><a href="http://stackoverflow.com/questions/426569/why-is-debugging-better-in-an-ide">Why is debugging better in an IDE?</a></p>
<p>It's directly relevant to what you're asking about.</p>
| 0 | 2013-02-04T08:57:00Z | [
"python",
"debugging"
] |
How do I turn an RSS feed back into RSS? | 181,818 | <p>According to the <a href="http://feedparser.org/docs/introduction.html" rel="nofollow">feedparser documentation</a>, I can turn an RSS feed into a parsed object like this:</p>
<pre><code>import feedparser
d = feedparser.parse('http://feedparser.org/docs/examples/atom10.xml')
</code></pre>
<p>but I can't find anything showing how to go the other way; I'd like to be able do manipulate 'd' and then output the result as XML:</p>
<pre><code>print d.toXML()
</code></pre>
<p>but there doesn't seem to be anything in feedparser for going in that direction. Am I going to have to loop through d's various elements, or is there a quicker way?</p>
| 3 | 2008-10-08T08:26:14Z | 181,832 | <pre><code>from xml.dom import minidom
doc= minidom.parse('./your/file.xml')
print doc.toxml()
</code></pre>
<p>The only problem is that it do not download feeds from the internet.</p>
| 0 | 2008-10-08T08:32:52Z | [
"python",
"rss"
] |
How do I turn an RSS feed back into RSS? | 181,818 | <p>According to the <a href="http://feedparser.org/docs/introduction.html" rel="nofollow">feedparser documentation</a>, I can turn an RSS feed into a parsed object like this:</p>
<pre><code>import feedparser
d = feedparser.parse('http://feedparser.org/docs/examples/atom10.xml')
</code></pre>
<p>but I can't find anything showing how to go the other way; I'd like to be able do manipulate 'd' and then output the result as XML:</p>
<pre><code>print d.toXML()
</code></pre>
<p>but there doesn't seem to be anything in feedparser for going in that direction. Am I going to have to loop through d's various elements, or is there a quicker way?</p>
| 3 | 2008-10-08T08:26:14Z | 181,903 | <p>As a method of making a feed, how about <a href="http://www.dalkescientific.com/Python/PyRSS2Gen.html" rel="nofollow">PyRSS2Gen</a>? :)</p>
<p>I've not played with FeedParser, but have you tried just doing str(yourFeedParserObject)? I've often been suprised by various modules that have <strong>str</strong> methods to just output the object as text.</p>
<p><strong>[Edit]</strong> Just tried the str() method and it doesn't work on this one. Worth a shot though ;-)</p>
| 0 | 2008-10-08T09:09:29Z | [
"python",
"rss"
] |
How do I turn an RSS feed back into RSS? | 181,818 | <p>According to the <a href="http://feedparser.org/docs/introduction.html" rel="nofollow">feedparser documentation</a>, I can turn an RSS feed into a parsed object like this:</p>
<pre><code>import feedparser
d = feedparser.parse('http://feedparser.org/docs/examples/atom10.xml')
</code></pre>
<p>but I can't find anything showing how to go the other way; I'd like to be able do manipulate 'd' and then output the result as XML:</p>
<pre><code>print d.toXML()
</code></pre>
<p>but there doesn't seem to be anything in feedparser for going in that direction. Am I going to have to loop through d's various elements, or is there a quicker way?</p>
| 3 | 2008-10-08T08:26:14Z | 181,931 | <p>If you're looking to read in an XML feed, modify it and then output it again, there's <a href="http://wiki.python.org/moin/RssLibraries" rel="nofollow">a page on the main python wiki indicating that the RSS.py library might support what you're after</a> (it reads most RSS and is able to output RSS 1.0). I've not looked at it in much detail though..</p>
| 1 | 2008-10-08T09:25:41Z | [
"python",
"rss"
] |
How do I turn an RSS feed back into RSS? | 181,818 | <p>According to the <a href="http://feedparser.org/docs/introduction.html" rel="nofollow">feedparser documentation</a>, I can turn an RSS feed into a parsed object like this:</p>
<pre><code>import feedparser
d = feedparser.parse('http://feedparser.org/docs/examples/atom10.xml')
</code></pre>
<p>but I can't find anything showing how to go the other way; I'd like to be able do manipulate 'd' and then output the result as XML:</p>
<pre><code>print d.toXML()
</code></pre>
<p>but there doesn't seem to be anything in feedparser for going in that direction. Am I going to have to loop through d's various elements, or is there a quicker way?</p>
| 3 | 2008-10-08T08:26:14Z | 191,899 | <p>Appended is a not hugely-elegant, but working solution - it uses feedparser to parse the feed, you can then modify the entries, and it passes the data to PyRSS2Gen. It preserves <em>most</em> of the feed info (the important bits anyway, there are somethings that will need extra conversion, the parsed_feed['feed']['image'] element for example).</p>
<p>I put this together as part of a <a href="http://github.com/dbr/py-feedproc/tree/master/" rel="nofollow">little feed-processing framework</a> I'm fiddling about with.. It may be of some use (it's pretty short - should be less than 100 lines of code in total when done..)</p>
<pre><code>#!/usr/bin/env python
import datetime
# http://www.feedparser.org/
import feedparser
# http://www.dalkescientific.com/Python/PyRSS2Gen.html
import PyRSS2Gen
# Get the data
parsed_feed = feedparser.parse('http://reddit.com/.rss')
# Modify the parsed_feed data here
items = [
PyRSS2Gen.RSSItem(
title = x.title,
link = x.link,
description = x.summary,
guid = x.link,
pubDate = datetime.datetime(
x.modified_parsed[0],
x.modified_parsed[1],
x.modified_parsed[2],
x.modified_parsed[3],
x.modified_parsed[4],
x.modified_parsed[5])
)
for x in parsed_feed.entries
]
# make the RSS2 object
# Try to grab the title, link, language etc from the orig feed
rss = PyRSS2Gen.RSS2(
title = parsed_feed['feed'].get("title"),
link = parsed_feed['feed'].get("link"),
description = parsed_feed['feed'].get("description"),
language = parsed_feed['feed'].get("language"),
copyright = parsed_feed['feed'].get("copyright"),
managingEditor = parsed_feed['feed'].get("managingEditor"),
webMaster = parsed_feed['feed'].get("webMaster"),
pubDate = parsed_feed['feed'].get("pubDate"),
lastBuildDate = parsed_feed['feed'].get("lastBuildDate"),
categories = parsed_feed['feed'].get("categories"),
generator = parsed_feed['feed'].get("generator"),
docs = parsed_feed['feed'].get("docs"),
items = items
)
print rss.to_xml()
</code></pre>
| 4 | 2008-10-10T15:33:14Z | [
"python",
"rss"
] |
Code to verify updates from the Google Safe Browsing API | 181,994 | <p>In order to verify the data coming from the <a href="http://code.google.com/apis/safebrowsing/developers_guide.html" rel="nofollow">Google Safe Browsing API</a>, you can calculate a Message Authentication Code (MAC) for each update. The instructions to do this (from Google) are:</p>
<blockquote>
<p>The MAC is computed from an MD5 Digest
over the following information:
client_key|separator|table
data|separator|client_key. The
separator is the string:coolgoog: -
that is a colon followed by "coolgoog"
followed by a colon. The resulting
128-bit MD5 digest is websafe base-64
encoded.</p>
</blockquote>
<p>There's also example data to check against:</p>
<pre><code>client key: "8eirwN1kTwCzgWA2HxTaRQ=="
</code></pre>
<p>response:</p>
<pre><code>[goog-black-hash 1.180 update][mac=dRalfTU+bXwUhlk0NCGJtQ==]
+8070465bdf3b9c6ad6a89c32e8162ef1
+86fa593a025714f89d6bc8c9c5a191ac
+bbbd7247731cbb7ec1b3a5814ed4bc9d
*Note that there are tabs at the end of each line.
</code></pre>
<p>I'm unable to get a match. Please either point out where I'm going wrong, or just write the couple of lines of Python code necessary to do this!</p>
<p>FWIW, I expected to be able to do something like this:</p>
<pre><code>>>> s = "+8070465bdf3b9c6ad6a89c32e8162ef1\t\n+86fa593a025714f89d6bc8c9c5a191ac\t\n+bbbd7247731cbb7ec1b3a5814ed4bc9d\t"
>>> c = "8eirwN1kTwCzgWA2HxTaRQ=="
>>> hashlib.md5("%s%s%s%s%s" % (c, ":coolgoog:", s, ":coolgoog:", c)).digest().encode("base64")
'qfb50mxpHrS82yTofPkcEg==\n'
</code></pre>
<p>But as you can see, 'qfb50mxpHrS82yTofPkcEg==\n' != 'dRalfTU+bXwUhlk0NCGJtQ=='.</p>
| 1 | 2008-10-08T09:59:55Z | 182,099 | <pre><code>c="8eirwN1kTwCzgWA2HxTaRQ==".decode('base64')
</code></pre>
| 1 | 2008-10-08T10:47:51Z | [
"python",
"api",
"verification",
"safe-browsing"
] |
Code to verify updates from the Google Safe Browsing API | 181,994 | <p>In order to verify the data coming from the <a href="http://code.google.com/apis/safebrowsing/developers_guide.html" rel="nofollow">Google Safe Browsing API</a>, you can calculate a Message Authentication Code (MAC) for each update. The instructions to do this (from Google) are:</p>
<blockquote>
<p>The MAC is computed from an MD5 Digest
over the following information:
client_key|separator|table
data|separator|client_key. The
separator is the string:coolgoog: -
that is a colon followed by "coolgoog"
followed by a colon. The resulting
128-bit MD5 digest is websafe base-64
encoded.</p>
</blockquote>
<p>There's also example data to check against:</p>
<pre><code>client key: "8eirwN1kTwCzgWA2HxTaRQ=="
</code></pre>
<p>response:</p>
<pre><code>[goog-black-hash 1.180 update][mac=dRalfTU+bXwUhlk0NCGJtQ==]
+8070465bdf3b9c6ad6a89c32e8162ef1
+86fa593a025714f89d6bc8c9c5a191ac
+bbbd7247731cbb7ec1b3a5814ed4bc9d
*Note that there are tabs at the end of each line.
</code></pre>
<p>I'm unable to get a match. Please either point out where I'm going wrong, or just write the couple of lines of Python code necessary to do this!</p>
<p>FWIW, I expected to be able to do something like this:</p>
<pre><code>>>> s = "+8070465bdf3b9c6ad6a89c32e8162ef1\t\n+86fa593a025714f89d6bc8c9c5a191ac\t\n+bbbd7247731cbb7ec1b3a5814ed4bc9d\t"
>>> c = "8eirwN1kTwCzgWA2HxTaRQ=="
>>> hashlib.md5("%s%s%s%s%s" % (c, ":coolgoog:", s, ":coolgoog:", c)).digest().encode("base64")
'qfb50mxpHrS82yTofPkcEg==\n'
</code></pre>
<p>But as you can see, 'qfb50mxpHrS82yTofPkcEg==\n' != 'dRalfTU+bXwUhlk0NCGJtQ=='.</p>
| 1 | 2008-10-08T09:59:55Z | 184,617 | <p>Anders' answer gives the necessary information, but isn't that clear: the client key needs to be decoded before it is combined. (The example above is also missing a newline at the end of the final table data).</p>
<p>So the working code is:</p>
<pre><code>>>> s = "+8070465bdf3b9c6ad6a89c32e8162ef1\t\n+86fa593a025714f89d6bc8c9c5a191ac\t\n+bbbd7247731cbb7ec1b3a5814ed4bc9d\t\n"
>>> c = "8eirwN1kTwCzgWA2HxTaRQ==".decode('base64')
>>> hashlib.md5("%s%s%s%s%s" % (c, ":coolgoog:", s, ":coolgoog:", c)).digest().encode("base64")
'dRalfTU+bXwUhlk0NCGJtQ==\n'
</code></pre>
| 2 | 2008-10-08T20:07:42Z | [
"python",
"api",
"verification",
"safe-browsing"
] |
Setup Python enviroment on windows | 182,053 | <p>How do I setup a Python enviroment on windows computer so I can start writing and running Python scripts, is there an install bundle? Also which database should i use?</p>
<p>Thanks</p>
<p><hr /></p>
<p>Sorry I should of mentioned that I am using this for web based applications. Does it require apache? or does it use another http server? What is the standard setup for Python running web apps?</p>
| 3 | 2008-10-08T10:29:28Z | 182,057 | <p>Download the Python 2.6 Windows installer from <a href="http://python.org/" rel="nofollow">python.org</a> (<a href="http://python.org/ftp/python/2.6/python-2.6.msi" rel="nofollow">direct link</a>). If you're just learning, use the included SQLite library so you don't have to fiddle with database servers.</p>
<p><hr /></p>
<p>Most web development frameworks (Django, Turbogears, etc) come with a built-in webserver command that runs on the local computer without Apache.</p>
| 7 | 2008-10-08T10:31:26Z | [
"python",
"windows",
"database",
"installation",
"development-environment"
] |
Setup Python enviroment on windows | 182,053 | <p>How do I setup a Python enviroment on windows computer so I can start writing and running Python scripts, is there an install bundle? Also which database should i use?</p>
<p>Thanks</p>
<p><hr /></p>
<p>Sorry I should of mentioned that I am using this for web based applications. Does it require apache? or does it use another http server? What is the standard setup for Python running web apps?</p>
| 3 | 2008-10-08T10:29:28Z | 182,120 | <p>Don't forget to install <a href="http://sourceforge.net/projects/pywin32/" rel="nofollow">pywin32</a> after installing the official (command line) installer. This will define additional <em>start menu</em> items and the highly useful <em>PythonWin IDE</em>.</p>
<p>An installer for both is available at <a href="http://activestate.com/Products/activepython/index.mhtml" rel="nofollow">Activestate</a> (no 2.6 yet). The Activestate distribution contains additional documentation.</p>
| 1 | 2008-10-08T10:54:18Z | [
"python",
"windows",
"database",
"installation",
"development-environment"
] |
Setup Python enviroment on windows | 182,053 | <p>How do I setup a Python enviroment on windows computer so I can start writing and running Python scripts, is there an install bundle? Also which database should i use?</p>
<p>Thanks</p>
<p><hr /></p>
<p>Sorry I should of mentioned that I am using this for web based applications. Does it require apache? or does it use another http server? What is the standard setup for Python running web apps?</p>
| 3 | 2008-10-08T10:29:28Z | 182,193 | <p>Django tutorial <a href="http://docs.djangoproject.com/en/dev/topics/install/" rel="nofollow">How to install Django</a> provides a good example how a web-development Python environment may look.</p>
| 0 | 2008-10-08T11:12:24Z | [
"python",
"windows",
"database",
"installation",
"development-environment"
] |
Setup Python enviroment on windows | 182,053 | <p>How do I setup a Python enviroment on windows computer so I can start writing and running Python scripts, is there an install bundle? Also which database should i use?</p>
<p>Thanks</p>
<p><hr /></p>
<p>Sorry I should of mentioned that I am using this for web based applications. Does it require apache? or does it use another http server? What is the standard setup for Python running web apps?</p>
| 3 | 2008-10-08T10:29:28Z | 182,195 | <p><strong>Bundle</strong>: go with Activestate's Python, which bundles many useful win32-related libraries. It has no version 2.6 yet, but most code you'll find online refers to 2.5 and lower anyway.</p>
<p><strong>Database</strong>: any of the popular open-source DBs are simple to configure. But as John already suggested, for simple beginning stuff just use SQLite which already comes bundled with Python.</p>
<p><strong>Web server</strong>: depends on the scale. You can configure Apache, yes, but for trying simple things the following is a quite complete web server in Python that will also serve CGI scripts writte in Python:</p>
<pre><code>import CGIHTTPServer
import BaseHTTPServer
class Handler(CGIHTTPServer.CGIHTTPRequestHandler):
cgi_directories = ["/cgi"]
PORT = 9999
httpd = BaseHTTPServer.HTTPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
</code></pre>
| 4 | 2008-10-08T11:12:43Z | [
"python",
"windows",
"database",
"installation",
"development-environment"
] |
Setup Python enviroment on windows | 182,053 | <p>How do I setup a Python enviroment on windows computer so I can start writing and running Python scripts, is there an install bundle? Also which database should i use?</p>
<p>Thanks</p>
<p><hr /></p>
<p>Sorry I should of mentioned that I am using this for web based applications. Does it require apache? or does it use another http server? What is the standard setup for Python running web apps?</p>
| 3 | 2008-10-08T10:29:28Z | 182,199 | <p>I strongly recommend <a href="http://www.activestate.com/Products/activepython/index.mhtml" rel="nofollow">ActiveState Python</a> for python on windows development. It comes with Win32Com and various other goodies, has a mature and clean installer, a chm version of the docs and works really well. I use this all of the time.</p>
<p>As for a database, Activestate comes with odbc support, which plays very nicely with SQL server. I've also had it working with Sybase and DB2/400 (although the connection strings for the latter tend to be rather convoluted). For Oracle, I recommend <a href="http://python.net/crew/atuining/cx_Oracle/" rel="nofollow">CX_Oracle</a> as the best interface library. Native drivers for most proprietary and open-source databases (such as <a href="http://mysql-python.sourceforge.net/" rel="nofollow">MySQL</a> and <a href="http://www.pygresql.org/" rel="nofollow">PostGreSQL</a>) also exist. Recent versions of Python (from 2.5 onwards IIRC) come with <a href="http://www.python.org/doc/2.5.2/lib/module-sqlite3.html" rel="nofollow">SQLite</a> bundled as standard.</p>
| 2 | 2008-10-08T11:13:07Z | [
"python",
"windows",
"database",
"installation",
"development-environment"
] |
Setup Python enviroment on windows | 182,053 | <p>How do I setup a Python enviroment on windows computer so I can start writing and running Python scripts, is there an install bundle? Also which database should i use?</p>
<p>Thanks</p>
<p><hr /></p>
<p>Sorry I should of mentioned that I am using this for web based applications. Does it require apache? or does it use another http server? What is the standard setup for Python running web apps?</p>
| 3 | 2008-10-08T10:29:28Z | 182,893 | <p>Might I suggest taking a look at <a href="http://karrigell.sourceforge.net/" rel="nofollow">Karrigell</a>? It's really a nice Python web framework if you don't require everything Django and Turbogears offers. It might be easier for you to work with web frameworks until you get comfortable with them.</p>
<p>For development, I recommend downloading the latest <a href="http://pythonide.blogspot.com" rel="nofollow">SPE</a> IDE. It should provide you nearly all the tools you will need, plus it includes wxGlade for GUI development.</p>
| 1 | 2008-10-08T13:56:21Z | [
"python",
"windows",
"database",
"installation",
"development-environment"
] |
How do I watch a file for changes using Python? | 182,197 | <p>I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.</p>
<p>What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the <code>win32file.FindNextChangeNotification</code> function but have no idea how to ask it to watch a specific file.</p>
<p>If anyone's done anything like this I'd be really grateful to hear how...</p>
<p><strong>[Edit]</strong> I should have mentioned that I was after a solution that doesn't require polling.</p>
<p><strong>[Edit]</strong> Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.</p>
| 197 | 2008-10-08T11:12:55Z | 182,234 | <p>I don't know any Windows specific function. You could try getting the MD5 hash of the file every second/minute/hour (depends on how fast you need it) and compare it to the last hash. When it differs you know the file has been changed and you read out the newest lines.</p>
| -2 | 2008-10-08T11:25:57Z | [
"python",
"file",
"pywin32",
"watch"
] |
How do I watch a file for changes using Python? | 182,197 | <p>I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.</p>
<p>What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the <code>win32file.FindNextChangeNotification</code> function but have no idea how to ask it to watch a specific file.</p>
<p>If anyone's done anything like this I'd be really grateful to hear how...</p>
<p><strong>[Edit]</strong> I should have mentioned that I was after a solution that doesn't require polling.</p>
<p><strong>[Edit]</strong> Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.</p>
| 197 | 2008-10-08T11:12:55Z | 182,235 | <p>I'd try something like this.</p>
<pre><code> try:
f = open(filePath)
except IOError:
print "No such file: %s" % filePath
raw_input("Press Enter to close window")
try:
lines = f.readlines()
while True:
line = f.readline()
try:
if not line:
time.sleep(1)
else:
functionThatAnalisesTheLine(line)
except Exception, e:
# handle the exception somehow (for example, log the trace) and raise the same exception again
raw_input("Press Enter to close window")
raise e
finally:
f.close()
</code></pre>
<p>The loop checks if there is a new line(s) since last time file was read - if there is, it's read and passed to the <code>functionThatAnalisesTheLine</code> function. If not, script waits 1 second and retries the process. </p>
| -6 | 2008-10-08T11:26:44Z | [
"python",
"file",
"pywin32",
"watch"
] |
How do I watch a file for changes using Python? | 182,197 | <p>I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.</p>
<p>What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the <code>win32file.FindNextChangeNotification</code> function but have no idea how to ask it to watch a specific file.</p>
<p>If anyone's done anything like this I'd be really grateful to hear how...</p>
<p><strong>[Edit]</strong> I should have mentioned that I was after a solution that doesn't require polling.</p>
<p><strong>[Edit]</strong> Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.</p>
| 197 | 2008-10-08T11:12:55Z | 182,242 | <p>Check <a href="http://stackoverflow.com/questions/62832/reading-data-from-a-log-file-as-a-separate-application-is-writing-to-it#63446">my answer</a> to a <a href="http://stackoverflow.com/questions/62832/">similar question</a>. You could try the same loop in Python. <a href="http://code.activestate.com/recipes/157035/">This page</a> suggests:</p>
<pre><code>import time
while 1:
where = file.tell()
line = file.readline()
if not line:
time.sleep(1)
file.seek(where)
else:
print line, # already has newline
</code></pre>
<p>Also see the question <a href="http://stackoverflow.com/questions/136168/tail-a-file-with-python">tail() a file with Python</a>.</p>
| 6 | 2008-10-08T11:28:12Z | [
"python",
"file",
"pywin32",
"watch"
] |
How do I watch a file for changes using Python? | 182,197 | <p>I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.</p>
<p>What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the <code>win32file.FindNextChangeNotification</code> function but have no idea how to ask it to watch a specific file.</p>
<p>If anyone's done anything like this I'd be really grateful to hear how...</p>
<p><strong>[Edit]</strong> I should have mentioned that I was after a solution that doesn't require polling.</p>
<p><strong>[Edit]</strong> Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.</p>
| 197 | 2008-10-08T11:12:55Z | 182,247 | <p>Have you already looked at the documentation available on <a href="http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html">http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html</a>? If you only need it to work under Windows the 2nd example seems to be exactly what you want (if you exchange the path of the directory with the one of the file you want to watch). </p>
<p>Otherwise, polling will probably be the only really platform-independent option.</p>
<p><strong>Note:</strong> I haven't tried any of these solutions.</p>
| 46 | 2008-10-08T11:29:43Z | [
"python",
"file",
"pywin32",
"watch"
] |
How do I watch a file for changes using Python? | 182,197 | <p>I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.</p>
<p>What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the <code>win32file.FindNextChangeNotification</code> function but have no idea how to ask it to watch a specific file.</p>
<p>If anyone's done anything like this I'd be really grateful to hear how...</p>
<p><strong>[Edit]</strong> I should have mentioned that I was after a solution that doesn't require polling.</p>
<p><strong>[Edit]</strong> Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.</p>
| 197 | 2008-10-08T11:12:55Z | 182,259 | <p>If polling is good enough for you, I'd just watch if the "modified time" file stat changes. To read it:</p>
<pre><code>os.stat(filename).st_mtime
</code></pre>
<p>(Also note that the Windows native change event solution does not work in all circumstances, e.g. on network drives.)</p>
<pre><code>import os
class Monkey(object):
def __init__(self):
self._cached_stamp = 0
self.filename = '/path/to/file'
def ook(self):
stamp = os.stat(self.filename).st_mtime
if stamp != self._cached_stamp:
self._cached_stamp = stamp
# File has changed, so do something...
</code></pre>
| 49 | 2008-10-08T11:34:14Z | [
"python",
"file",
"pywin32",
"watch"
] |
How do I watch a file for changes using Python? | 182,197 | <p>I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.</p>
<p>What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the <code>win32file.FindNextChangeNotification</code> function but have no idea how to ask it to watch a specific file.</p>
<p>If anyone's done anything like this I'd be really grateful to hear how...</p>
<p><strong>[Edit]</strong> I should have mentioned that I was after a solution that doesn't require polling.</p>
<p><strong>[Edit]</strong> Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.</p>
| 197 | 2008-10-08T11:12:55Z | 182,297 | <p>As you can see in <a href="http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html" rel="nofollow">Tim Golden's article</a>, pointed by <a href="http://stackoverflow.com/users/22312/horst-gutmann">Horst Gutmann</a>, WIN32 is relatively complex and watches directories, not a single file.</p>
<p>I'd like to suggest you look into <a href="http://www.codeplex.com/IronPython" rel="nofollow">IronPython</a>, which is a <em>.NET</em> python implementation.
With IronPython you can use all the <em>.NET</em> functionality - including</p>
<pre><code>System.IO.FileSystemWatcher
</code></pre>
<p>Which handles single files with a simple <em>Event</em> interface.</p>
| 2 | 2008-10-08T11:42:12Z | [
"python",
"file",
"pywin32",
"watch"
] |
How do I watch a file for changes using Python? | 182,197 | <p>I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.</p>
<p>What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the <code>win32file.FindNextChangeNotification</code> function but have no idea how to ask it to watch a specific file.</p>
<p>If anyone's done anything like this I'd be really grateful to hear how...</p>
<p><strong>[Edit]</strong> I should have mentioned that I was after a solution that doesn't require polling.</p>
<p><strong>[Edit]</strong> Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.</p>
| 197 | 2008-10-08T11:12:55Z | 182,441 | <p>Well, since you are using Python, you can just open a file and keep reading lines from it.</p>
<pre><code>f = open('file.log')
</code></pre>
<p>If the line read is <strong>not empty</strong>, you process it.</p>
<pre><code>line = f.readline()
if line:
// Do what you want with the line
</code></pre>
<p>You may be missing that it is ok to keep calling <code>readline</code> at the EOF. It will just keep returning an empty string in this case. And when something is appended to the log file, the reading will continue from where it stopped, as you need.</p>
<p>If you are looking for a solution that uses events, or a particular library, please specify this in your question. Otherwise, I think this solution is just fine.</p>
| 4 | 2008-10-08T12:18:25Z | [
"python",
"file",
"pywin32",
"watch"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.