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
'from X import a' versus 'import X; X.a'
186,472
<p>I've seen some Python programmers use the following style fairly consistently (we'll call it style 1):</p> <pre><code>import some_module # Use some_module.some_identifier in various places. </code></pre> <p>For support of this style, you can cite the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">"explicit is better than implicit"</a> maxim. I've seen other programmers use this style (style 2):</p> <pre><code>from some_module import some_identifier # Use some_identifier in various places. </code></pre> <p>The primary benefit that I see in style 2 is maintainability -- especially with <a href="http://en.wikipedia.org/wiki/Duck_typing" rel="nofollow">duck typing</a> ideals I may want to swap some_module for some_other_module. I also feel style 2 wins points with the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">"readability counts"</a> maxim. Although I tend to disagree, one can always argue that search-and-replace is just as good an option when using the first style.</p> <p><strong>Addendum:</strong> It was noted that you could use <code>as</code> to solve the switch from <code>some_module</code> to <code>some_other_module</code> in style 1. I forgot to mention that it is also common to decide to implement <code>some_identifier</code> in your <em>current</em> module, which makes creation of an equivalent <code>some_module</code> container slightly awkward.</p>
7
2008-10-09T09:04:34Z
186,541
<p>I find that the notation</p> <pre><code>from some_module import some_symbol </code></pre> <p>works best in most cases. Also, in case of name clash for the symbol, you can use:</p> <pre><code>from some_module import some_symbol as other_symbol </code></pre> <p>As the question states, it avoids rewriting the module name all the time, each time with a risk of mistyping it. I use the syntax:</p> <pre><code>import module [as other_module] </code></pre> <p>Only in two cases:</p> <ol> <li>I use too many of the module functions/objects to import them all</li> <li>The module defines some symbol that may change during execution</li> </ol>
1
2008-10-09T09:37:03Z
[ "python", "python-import", "maintainability", "duck-typing" ]
'from X import a' versus 'import X; X.a'
186,472
<p>I've seen some Python programmers use the following style fairly consistently (we'll call it style 1):</p> <pre><code>import some_module # Use some_module.some_identifier in various places. </code></pre> <p>For support of this style, you can cite the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">"explicit is better than implicit"</a> maxim. I've seen other programmers use this style (style 2):</p> <pre><code>from some_module import some_identifier # Use some_identifier in various places. </code></pre> <p>The primary benefit that I see in style 2 is maintainability -- especially with <a href="http://en.wikipedia.org/wiki/Duck_typing" rel="nofollow">duck typing</a> ideals I may want to swap some_module for some_other_module. I also feel style 2 wins points with the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">"readability counts"</a> maxim. Although I tend to disagree, one can always argue that search-and-replace is just as good an option when using the first style.</p> <p><strong>Addendum:</strong> It was noted that you could use <code>as</code> to solve the switch from <code>some_module</code> to <code>some_other_module</code> in style 1. I forgot to mention that it is also common to decide to implement <code>some_identifier</code> in your <em>current</em> module, which makes creation of an equivalent <code>some_module</code> container slightly awkward.</p>
7
2008-10-09T09:04:34Z
186,636
<p>I prefer to <code>import X</code> and then use <code>X.a</code> as much as possible.</p> <p>My exception centers on the deeply nested modules in a big framework like Django. Their module names tend to get lengthy, and their examples all say <code>from django.conf import settings</code> to save you typing <code>django.conf.settings.DEBUG</code> everywhere.</p> <p>If the module name is deeply nested, then the exception is to use <code>from X.Y.Z import a</code>.</p>
2
2008-10-09T10:13:42Z
[ "python", "python-import", "maintainability", "duck-typing" ]
'from X import a' versus 'import X; X.a'
186,472
<p>I've seen some Python programmers use the following style fairly consistently (we'll call it style 1):</p> <pre><code>import some_module # Use some_module.some_identifier in various places. </code></pre> <p>For support of this style, you can cite the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">"explicit is better than implicit"</a> maxim. I've seen other programmers use this style (style 2):</p> <pre><code>from some_module import some_identifier # Use some_identifier in various places. </code></pre> <p>The primary benefit that I see in style 2 is maintainability -- especially with <a href="http://en.wikipedia.org/wiki/Duck_typing" rel="nofollow">duck typing</a> ideals I may want to swap some_module for some_other_module. I also feel style 2 wins points with the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">"readability counts"</a> maxim. Although I tend to disagree, one can always argue that search-and-replace is just as good an option when using the first style.</p> <p><strong>Addendum:</strong> It was noted that you could use <code>as</code> to solve the switch from <code>some_module</code> to <code>some_other_module</code> in style 1. I forgot to mention that it is also common to decide to implement <code>some_identifier</code> in your <em>current</em> module, which makes creation of an equivalent <code>some_module</code> container slightly awkward.</p>
7
2008-10-09T09:04:34Z
186,644
<p>I personally try not to mess too much with my namespace, so in most situations I just do </p> <pre><code>import module </code></pre> <p>or import module as mod</p> <p>Only real diffrence is when I have a module with a single class that's used a lot. If I had sublclassed a <code>list</code> type to add some funcionality there, I'd use</p> <pre><code>from SuperImprovedListOverloadedWithFeatures import NewLIst nl = NewList() </code></pre> <p>etc.</p>
0
2008-10-09T10:16:30Z
[ "python", "python-import", "maintainability", "duck-typing" ]
'from X import a' versus 'import X; X.a'
186,472
<p>I've seen some Python programmers use the following style fairly consistently (we'll call it style 1):</p> <pre><code>import some_module # Use some_module.some_identifier in various places. </code></pre> <p>For support of this style, you can cite the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">"explicit is better than implicit"</a> maxim. I've seen other programmers use this style (style 2):</p> <pre><code>from some_module import some_identifier # Use some_identifier in various places. </code></pre> <p>The primary benefit that I see in style 2 is maintainability -- especially with <a href="http://en.wikipedia.org/wiki/Duck_typing" rel="nofollow">duck typing</a> ideals I may want to swap some_module for some_other_module. I also feel style 2 wins points with the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">"readability counts"</a> maxim. Although I tend to disagree, one can always argue that search-and-replace is just as good an option when using the first style.</p> <p><strong>Addendum:</strong> It was noted that you could use <code>as</code> to solve the switch from <code>some_module</code> to <code>some_other_module</code> in style 1. I forgot to mention that it is also common to decide to implement <code>some_identifier</code> in your <em>current</em> module, which makes creation of an equivalent <code>some_module</code> container slightly awkward.</p>
7
2008-10-09T09:04:34Z
186,813
<p>There are uses for both cases, so I don't think this is an either-or issue. I'd consider using from module <code>import x,y,z</code> when:</p> <ul> <li><p>There are a fairly small number of things to import</p></li> <li><p>The purpose of the functions imported is obvious when divorced from the module name. If the names are fairly generic, they may clash with others and tell you little. eg. seeing <code>remove</code> tells you little, but <code>os.remove</code> will probably hint that you're dealing with files.</p></li> <li><p>The names don't clash. Similar to the above, but more important. <strong>Never</strong> do something like:</p> <pre><code> from os import open </code></pre></li> </ul> <p><code>import module [as renamed_module]</code> has the advantage that it gives a bit more context about what is being called when you use it. It has the disadvantage that this is a bit more cluttered when the module isn't really giving more information, and is slightly less performant (2 lookups instead of 1).</p> <p>It also has advantages when testing however (eg. replacing os.open with a mock object, without having to change every module), and should be used when using mutable modules, e.g.</p> <pre><code>import config config.dburl = 'sqlite:///test.db' </code></pre> <p>If in doubt, I'd always go with the <code>import module</code> style.</p>
4
2008-10-09T11:24:46Z
[ "python", "python-import", "maintainability", "duck-typing" ]
'from X import a' versus 'import X; X.a'
186,472
<p>I've seen some Python programmers use the following style fairly consistently (we'll call it style 1):</p> <pre><code>import some_module # Use some_module.some_identifier in various places. </code></pre> <p>For support of this style, you can cite the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">"explicit is better than implicit"</a> maxim. I've seen other programmers use this style (style 2):</p> <pre><code>from some_module import some_identifier # Use some_identifier in various places. </code></pre> <p>The primary benefit that I see in style 2 is maintainability -- especially with <a href="http://en.wikipedia.org/wiki/Duck_typing" rel="nofollow">duck typing</a> ideals I may want to swap some_module for some_other_module. I also feel style 2 wins points with the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">"readability counts"</a> maxim. Although I tend to disagree, one can always argue that search-and-replace is just as good an option when using the first style.</p> <p><strong>Addendum:</strong> It was noted that you could use <code>as</code> to solve the switch from <code>some_module</code> to <code>some_other_module</code> in style 1. I forgot to mention that it is also common to decide to implement <code>some_identifier</code> in your <em>current</em> module, which makes creation of an equivalent <code>some_module</code> container slightly awkward.</p>
7
2008-10-09T09:04:34Z
187,352
<p>I tend to use only a few members of each module, so there's a lot of</p> <pre><code>from john import cleese from terry import jones, gilliam </code></pre> <p>in my code. I'll import whole modules (such as <code>os</code> or <code>wx</code>) if I expect to be using most of the module and the module name is short. I'll also import whole modules if there is a name conflict or I want to remind the reader what that function is associated with.</p> <pre><code>import michael import sarah import wave gov_speech = wave.open(sarah.palin.speechfile) parrot_sketch = wave.open(michael.palin.justresting) </code></pre> <p>(I could use <code>from wave import open as wave_open</code>, but I figure that <code>wave.open</code> will be more familiar to the reader.</p>
0
2008-10-09T13:54:15Z
[ "python", "python-import", "maintainability", "duck-typing" ]
'from X import a' versus 'import X; X.a'
186,472
<p>I've seen some Python programmers use the following style fairly consistently (we'll call it style 1):</p> <pre><code>import some_module # Use some_module.some_identifier in various places. </code></pre> <p>For support of this style, you can cite the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">"explicit is better than implicit"</a> maxim. I've seen other programmers use this style (style 2):</p> <pre><code>from some_module import some_identifier # Use some_identifier in various places. </code></pre> <p>The primary benefit that I see in style 2 is maintainability -- especially with <a href="http://en.wikipedia.org/wiki/Duck_typing" rel="nofollow">duck typing</a> ideals I may want to swap some_module for some_other_module. I also feel style 2 wins points with the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">"readability counts"</a> maxim. Although I tend to disagree, one can always argue that search-and-replace is just as good an option when using the first style.</p> <p><strong>Addendum:</strong> It was noted that you could use <code>as</code> to solve the switch from <code>some_module</code> to <code>some_other_module</code> in style 1. I forgot to mention that it is also common to decide to implement <code>some_identifier</code> in your <em>current</em> module, which makes creation of an equivalent <code>some_module</code> container slightly awkward.</p>
7
2008-10-09T09:04:34Z
6,386,083
<p>You may be interested in Stack Overflow question <em><a href="http://stackoverflow.com/questions/6386061">Why does 'import x;x.y' behave different from 'from x import y', and the first one fails when package x.<strong>init</strong> is not completed?</a></em>.</p>
0
2011-06-17T12:58:47Z
[ "python", "python-import", "maintainability", "duck-typing" ]
Splitting a semicolon-separated string to a dictionary, in Python
186,857
<p>I have a string that looks like this:</p> <pre><code>"Name1=Value1;Name2=Value2;Name3=Value3" </code></pre> <p>Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this:</p> <pre><code>dict = { "Name1": "Value1", "Name2": "Value2", "Name3": "Value3" } </code></pre> <p>I have looked through the modules available but can't seem to find anything that matches.</p> <p><hr /></p> <p>Thanks, I do know how to make the relevant code myself, but since such smallish solutions are usually mine-fields waiting to happen (ie. someone writes: Name1='Value1=2';) etc. then I usually prefer some pre-tested function.</p> <p>I'll do it myself then.</p>
56
2008-10-09T11:38:22Z
186,873
<p>There's no builtin, but you can accomplish this fairly simply with a generator comprehension:</p> <pre><code>s= "Name1=Value1;Name2=Value2;Name3=Value3" dict(item.split("=") for item in s.split(";")) </code></pre> <p><strong>[Edit]</strong> From your update you indicate you may need to handle quoting. This does complicate things, depending on what the exact format you are looking for is (what quote chars are accepted, what escape chars etc). You may want to look at the csv module to see if it can cover your format. Here's an example: (Note that the API is a little clunky for this example, as CSV is designed to iterate through a sequence of records, hence the .next() calls I'm making to just look at the first line. Adjust to suit your needs):</p> <pre><code>&gt;&gt;&gt; s = "Name1='Value=2';Name2=Value2;Name3=Value3" &gt;&gt;&gt; dict(csv.reader([item], delimiter='=', quotechar="'").next() for item in csv.reader([s], delimiter=';', quotechar="'").next()) {'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1=2'} </code></pre> <p>Depending on the exact structure of your format, you may need to write your own simple parser however.</p>
81
2008-10-09T11:43:42Z
[ "python", "string", "dictionary", "split" ]
Splitting a semicolon-separated string to a dictionary, in Python
186,857
<p>I have a string that looks like this:</p> <pre><code>"Name1=Value1;Name2=Value2;Name3=Value3" </code></pre> <p>Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this:</p> <pre><code>dict = { "Name1": "Value1", "Name2": "Value2", "Name3": "Value3" } </code></pre> <p>I have looked through the modules available but can't seem to find anything that matches.</p> <p><hr /></p> <p>Thanks, I do know how to make the relevant code myself, but since such smallish solutions are usually mine-fields waiting to happen (ie. someone writes: Name1='Value1=2';) etc. then I usually prefer some pre-tested function.</p> <p>I'll do it myself then.</p>
56
2008-10-09T11:38:22Z
5,149,981
<p>This comes close to doing what you wanted:</p> <pre><code>&gt;&gt;&gt; import urlparse &gt;&gt;&gt; urlparse.parse_qs("Name1=Value1;Name2=Value2;Name3=Value3") {'Name2': ['Value2'], 'Name3': ['Value3'], 'Name1': ['Value1']} </code></pre>
2
2011-03-01T02:46:12Z
[ "python", "string", "dictionary", "split" ]
Splitting a semicolon-separated string to a dictionary, in Python
186,857
<p>I have a string that looks like this:</p> <pre><code>"Name1=Value1;Name2=Value2;Name3=Value3" </code></pre> <p>Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this:</p> <pre><code>dict = { "Name1": "Value1", "Name2": "Value2", "Name3": "Value3" } </code></pre> <p>I have looked through the modules available but can't seem to find anything that matches.</p> <p><hr /></p> <p>Thanks, I do know how to make the relevant code myself, but since such smallish solutions are usually mine-fields waiting to happen (ie. someone writes: Name1='Value1=2';) etc. then I usually prefer some pre-tested function.</p> <p>I'll do it myself then.</p>
56
2008-10-09T11:38:22Z
15,649,648
<pre><code>easytiger $ cat test.out test.py | sed 's/^/ /' p_easytiger_quoting:1.84563302994 {'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1'} p_brian:2.30507516861 {'Name2': 'Value2', 'Name3': "'Value3'", 'Name1': 'Value1'} p_kyle:7.22536420822 {'Name2': ['Value2'], 'Name3': ["'Value3'"], 'Name1': ['Value1']} import timeit import urlparse s = "Name1=Value1;Name2=Value2;Name3='Value3'" def p_easytiger_quoting(s): d = {} s = s.replace("'", "") for x in s.split(';'): k, v = x.split('=') d[k] = v return d def p_brian(s): return dict(item.split("=") for item in s.split(";")) def p_kyle(s): return urlparse.parse_qs(s) print "p_easytiger_quoting:" + str(timeit.timeit(lambda: p_easytiger_quoting(s))) print p_easytiger_quoting(s) print "p_brian:" + str(timeit.timeit(lambda: p_brian(s))) print p_brian(s) print "p_kyle:" + str(timeit.timeit(lambda: p_kyle(s))) print p_kyle(s) </code></pre>
-2
2013-03-26T23:59:36Z
[ "python", "string", "dictionary", "split" ]
Splitting a semicolon-separated string to a dictionary, in Python
186,857
<p>I have a string that looks like this:</p> <pre><code>"Name1=Value1;Name2=Value2;Name3=Value3" </code></pre> <p>Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this:</p> <pre><code>dict = { "Name1": "Value1", "Name2": "Value2", "Name3": "Value3" } </code></pre> <p>I have looked through the modules available but can't seem to find anything that matches.</p> <p><hr /></p> <p>Thanks, I do know how to make the relevant code myself, but since such smallish solutions are usually mine-fields waiting to happen (ie. someone writes: Name1='Value1=2';) etc. then I usually prefer some pre-tested function.</p> <p>I'll do it myself then.</p>
56
2008-10-09T11:38:22Z
16,189,504
<p>IF your Value1, Value2 are just placeholders for actual values, you can also use the <code>dict()</code> function in combination with <code>eval()</code>. </p> <pre><code>&gt;&gt;&gt; s= "Name1=1;Name2=2;Name3='string'" &gt;&gt;&gt; print eval('dict('+s.replace(';',',')+')') {'Name2: 2, 'Name3': 'string', 'Name1': 1} </code></pre> <p>This is beacuse the <code>dict()</code> function understand the syntax <code>dict(Name1=1, Name2=2,Name3='string')</code>. Spaces in the string (e.g. after each semicolon) are ignored. But note the string values do require quoting.</p>
0
2013-04-24T10:22:23Z
[ "python", "string", "dictionary", "split" ]
Splitting a semicolon-separated string to a dictionary, in Python
186,857
<p>I have a string that looks like this:</p> <pre><code>"Name1=Value1;Name2=Value2;Name3=Value3" </code></pre> <p>Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this:</p> <pre><code>dict = { "Name1": "Value1", "Name2": "Value2", "Name3": "Value3" } </code></pre> <p>I have looked through the modules available but can't seem to find anything that matches.</p> <p><hr /></p> <p>Thanks, I do know how to make the relevant code myself, but since such smallish solutions are usually mine-fields waiting to happen (ie. someone writes: Name1='Value1=2';) etc. then I usually prefer some pre-tested function.</p> <p>I'll do it myself then.</p>
56
2008-10-09T11:38:22Z
27,619,606
<p>It can be simply done by string join and list comprehension</p> <p>','.join(['%s=%s'%x for x in d.items()])</p> <pre><code>&gt;&gt;d = {'a':1, 'b':2} &gt;&gt;','.join(['%s=%s'%x for x in d.items()]) &gt;&gt;'a=1,b=2' </code></pre>
0
2014-12-23T11:37:28Z
[ "python", "string", "dictionary", "split" ]
Configuration file with list of key-value pairs in python
186,916
<p>I have a python script that analyzes a set of error messages and checks for each message if it matches a certain pattern (regular expression) in order to group these messages. For example "file x does not exist" and "file y does not exist" would match "file .* does not exist" and be accounted as two occurrences of "file not found" category. </p> <p>As the number of patterns and categories is growing, I'd like to put these couples "regular expression/display string" in a configuration file, basically a dictionary serialization of some sort.</p> <p>I would like this file to be editable by hand, so I'm discarding any form of binary serialization, and also I'd rather not resort to xml serialization to avoid problems with characters to escape (&amp; &lt;> and so on...).</p> <p>Do you have any idea of what could be a good way of accomplishing this?</p> <p>Update: thanks to Daren Thomas and Federico Ramponi, but I cannot have an external python file with possibly arbitrary code.</p>
25
2008-10-09T11:55:48Z
186,937
<p>I think you want the <a href="http://docs.python.org/library/configparser.html#module-ConfigParser" rel="nofollow">ConfigParser</a> module in the standard library. It reads and writes INI style files. The examples and documentation in the standard documentation I've linked to are very comprehensive.</p>
4
2008-10-09T12:00:52Z
[ "python", "configuration", "serialization" ]
Configuration file with list of key-value pairs in python
186,916
<p>I have a python script that analyzes a set of error messages and checks for each message if it matches a certain pattern (regular expression) in order to group these messages. For example "file x does not exist" and "file y does not exist" would match "file .* does not exist" and be accounted as two occurrences of "file not found" category. </p> <p>As the number of patterns and categories is growing, I'd like to put these couples "regular expression/display string" in a configuration file, basically a dictionary serialization of some sort.</p> <p>I would like this file to be editable by hand, so I'm discarding any form of binary serialization, and also I'd rather not resort to xml serialization to avoid problems with characters to escape (&amp; &lt;> and so on...).</p> <p>Do you have any idea of what could be a good way of accomplishing this?</p> <p>Update: thanks to Daren Thomas and Federico Ramponi, but I cannot have an external python file with possibly arbitrary code.</p>
25
2008-10-09T11:55:48Z
186,990
<p>I've heard that <a href="http://www.voidspace.org.uk/python/configobj.html" rel="nofollow" title="ConfigObj">ConfigObj</a> is easier to work with than ConfigParser. It is used by a lot of big projects, IPython, Trac, Turbogears, etc... </p> <p>From their <a href="http://www.voidspace.org.uk/python/configobj.html#introduction" rel="nofollow">introduction</a>:</p> <p>ConfigObj is a simple but powerful config file reader and writer: an ini file round tripper. Its main feature is that it is very easy to use, with a straightforward programmer's interface and a simple syntax for config files. It has lots of other features though :</p> <ul> <li>Nested sections (subsections), to any level</li> <li>List values</li> <li>Multiple line values</li> <li>String interpolation (substitution)</li> <li>Integrated with a powerful validation system <ul> <li>including automatic type checking/conversion</li> <li>repeated sections</li> <li>and allowing default values</li> </ul></li> <li>When writing out config files, ConfigObj preserves all comments and the order of members and sections</li> <li>Many useful methods and options for working with configuration files (like the 'reload' method)</li> <li>Full Unicode support</li> </ul>
8
2008-10-09T12:13:27Z
[ "python", "configuration", "serialization" ]
Configuration file with list of key-value pairs in python
186,916
<p>I have a python script that analyzes a set of error messages and checks for each message if it matches a certain pattern (regular expression) in order to group these messages. For example "file x does not exist" and "file y does not exist" would match "file .* does not exist" and be accounted as two occurrences of "file not found" category. </p> <p>As the number of patterns and categories is growing, I'd like to put these couples "regular expression/display string" in a configuration file, basically a dictionary serialization of some sort.</p> <p>I would like this file to be editable by hand, so I'm discarding any form of binary serialization, and also I'd rather not resort to xml serialization to avoid problems with characters to escape (&amp; &lt;> and so on...).</p> <p>Do you have any idea of what could be a good way of accomplishing this?</p> <p>Update: thanks to Daren Thomas and Federico Ramponi, but I cannot have an external python file with possibly arbitrary code.</p>
25
2008-10-09T11:55:48Z
187,011
<p>If you are the only one that has access to the configuration file, you can use a simple, low-level solution. Keep the "dictionary" in a text file as a list of tuples (regexp, message) exactly as if it was a python expression: <pre><code>[ ("file .* does not exist", "file not found"), ("user .* not authorized", "authorization error") ] </pre></code> In your code, load it, then eval it, and compile the regexps in the result: <pre><code>f = open("messages.py") messages = eval(f.read()) # caution: you must be <em>sure</em> of what's in that file f.close() messages = [(re.compile(r), m) for (r,m) in messages] </pre></code> and you end up with a list of tuples (compiled_regexp, message).</p>
4
2008-10-09T12:22:03Z
[ "python", "configuration", "serialization" ]
Configuration file with list of key-value pairs in python
186,916
<p>I have a python script that analyzes a set of error messages and checks for each message if it matches a certain pattern (regular expression) in order to group these messages. For example "file x does not exist" and "file y does not exist" would match "file .* does not exist" and be accounted as two occurrences of "file not found" category. </p> <p>As the number of patterns and categories is growing, I'd like to put these couples "regular expression/display string" in a configuration file, basically a dictionary serialization of some sort.</p> <p>I would like this file to be editable by hand, so I'm discarding any form of binary serialization, and also I'd rather not resort to xml serialization to avoid problems with characters to escape (&amp; &lt;> and so on...).</p> <p>Do you have any idea of what could be a good way of accomplishing this?</p> <p>Update: thanks to Daren Thomas and Federico Ramponi, but I cannot have an external python file with possibly arbitrary code.</p>
25
2008-10-09T11:55:48Z
187,045
<p>I sometimes just write a python module (i.e. file) called <code>config.py</code> or something with following contents:</p> <pre><code>config = { 'name': 'hello', 'see?': 'world' } </code></pre> <p>this can then be 'read' like so:</p> <pre><code>from config import config config['name'] config['see?'] </code></pre> <p>easy.</p>
36
2008-10-09T12:32:37Z
[ "python", "configuration", "serialization" ]
Configuration file with list of key-value pairs in python
186,916
<p>I have a python script that analyzes a set of error messages and checks for each message if it matches a certain pattern (regular expression) in order to group these messages. For example "file x does not exist" and "file y does not exist" would match "file .* does not exist" and be accounted as two occurrences of "file not found" category. </p> <p>As the number of patterns and categories is growing, I'd like to put these couples "regular expression/display string" in a configuration file, basically a dictionary serialization of some sort.</p> <p>I would like this file to be editable by hand, so I'm discarding any form of binary serialization, and also I'd rather not resort to xml serialization to avoid problems with characters to escape (&amp; &lt;> and so on...).</p> <p>Do you have any idea of what could be a good way of accomplishing this?</p> <p>Update: thanks to Daren Thomas and Federico Ramponi, but I cannot have an external python file with possibly arbitrary code.</p>
25
2008-10-09T11:55:48Z
187,135
<p>I typically do as Daren suggested, just make your config file a Python script:</p> <pre><code>patterns = { 'file .* does not exist': 'file not found', 'user .* not found': 'authorization error', } </code></pre> <p>Then you can use it as:</p> <pre><code>import config for pattern in config.patterns: if re.search(pattern, log_message): print config.patterns[pattern] </code></pre> <p>This is what Django does with their settings file, by the way.</p>
3
2008-10-09T12:57:56Z
[ "python", "configuration", "serialization" ]
Configuration file with list of key-value pairs in python
186,916
<p>I have a python script that analyzes a set of error messages and checks for each message if it matches a certain pattern (regular expression) in order to group these messages. For example "file x does not exist" and "file y does not exist" would match "file .* does not exist" and be accounted as two occurrences of "file not found" category. </p> <p>As the number of patterns and categories is growing, I'd like to put these couples "regular expression/display string" in a configuration file, basically a dictionary serialization of some sort.</p> <p>I would like this file to be editable by hand, so I'm discarding any form of binary serialization, and also I'd rather not resort to xml serialization to avoid problems with characters to escape (&amp; &lt;> and so on...).</p> <p>Do you have any idea of what could be a good way of accomplishing this?</p> <p>Update: thanks to Daren Thomas and Federico Ramponi, but I cannot have an external python file with possibly arbitrary code.</p>
25
2008-10-09T11:55:48Z
187,628
<p>You have two decent options:</p> <ol> <li>Python standard config file format using <a href="http://docs.python.org/lib/module-ConfigParser.html">ConfigParser</a></li> <li><a href="http://www.yaml.org/">YAML</a> using a library like <a href="http://pyyaml.org/">PyYAML</a></li> </ol> <p>The standard Python configuration files look like INI files with <code>[sections]</code> and <code>key : value</code> or <code>key = value</code> pairs. The advantages to this format are:</p> <ul> <li>No third-party libraries necessary</li> <li>Simple, familiar file format.</li> </ul> <p>YAML is different in that it is designed to be a human friendly data serialization format rather than specifically designed for configuration. It is very readable and gives you a couple different ways to represent the same data. For your problem, you could create a YAML file that looks like this:</p> <pre><code>file .* does not exist : file not found user .* not found : authorization error </code></pre> <p>Or like this:</p> <pre><code>{ file .* does not exist: file not found, user .* not found: authorization error } </code></pre> <p>Using PyYAML couldn't be simpler:</p> <pre><code>import yaml errors = yaml.load(open('my.yaml')) </code></pre> <p>At this point <code>errors</code> is a Python dictionary with the expected format. YAML is capable of representing more than dictionaries: if you prefer a list of pairs, use this format:</p> <pre><code>- - file .* does not exist - file not found - - user .* not found - authorization error </code></pre> <p>Or</p> <pre><code>[ [file .* does not exist, file not found], [user .* not found, authorization error]] </code></pre> <p>Which will produce a list of lists when <code>yaml.load</code> is called.</p> <p>One advantage of YAML is that you could use it to export your existing, hard-coded data out to a file to create the initial version, rather than cut/paste plus a bunch of find/replace to get the data into the right format.</p> <p>The YAML format will take a little more time to get familiar with, but using PyYAML is even simpler than using ConfigParser with the advantage is that you have more options regarding how your data is represented using YAML.</p> <p>Either one sounds like it will fit your current needs, ConfigParser will be easier to start with while YAML gives you more flexibilty in the future, if your needs expand.</p> <p>Best of luck!</p>
35
2008-10-09T14:57:08Z
[ "python", "configuration", "serialization" ]
Base-2 (Binary) Representation Using Python
187,273
<p>Building on <a href="http://stackoverflow.com/questions/1476/how-do-you-express-binary-literals-in-python#13107">How Do You Express Binary Literals in Python</a>, I was thinking about sensible, intuitive ways to do that Programming 101 chestnut of displaying integers in base-2 form. This is the best I came up with, but I'd like to replace it with a better algorithm, or at least one that should have screaming-fast performance. </p> <pre><code>def num_bin(N, places=8): def bit_at_p(N, p): ''' find the bit at place p for number n ''' two_p = 1 &lt;&lt; p # 2 ^ p, using bitshift, will have exactly one # bit set, at place p x = N &amp; two_p # binary composition, will be one where *both* numbers # have a 1 at that bit. this can only happen # at position p. will yield two_p if N has a 1 at # bit p return int(x &gt; 0) bits = ( bit_at_p(N,x) for x in xrange(places)) return "".join( (str(x) for x in bits) ) # or, more consisely # return "".join([str(int((N &amp; 1 &lt;&lt; x)&gt;0)) for x in xrange(places)]) </code></pre>
4
2008-10-09T13:38:32Z
187,536
<p>For best efficiency, you generally want to process more than a single bit at a time. You can use a simple method to get a fixed width binary representation. eg.</p> <pre><code>def _bin(x, width): return ''.join(str((x&gt;&gt;i)&amp;1) for i in xrange(width-1,-1,-1)) </code></pre> <p>_bin(x, 8) will now give a zero padded representation of x's lower 8 bits. This can be used to build a lookup table, allowing your converter to process 8 bits at a time (or more if you want to devote the memory to it).</p> <pre><code>_conv_table = [_bin(x,8) for x in range(256)] </code></pre> <p>Then you can use this in your real function, stripping off leading zeroes when returning it. I've also added handling for signed numbers, as without it you will get an infinite loop (Negative integers conceptually have an infinite number of set sign bits.)</p> <pre><code>def bin(x): if x == 0: return '0' #Special case: Don't strip leading zero if no other digits elif x &lt; 0: sign='-' x*=-1 else: sign = '' l=[] while x: l.append(_conv_table[x &amp; 0xff]) x &gt;&gt;= 8 return sign + ''.join(reversed(l)).lstrip("0") </code></pre> <p>[Edit] Changed code to handle signed integers.<br /> [Edit2] Here are some timing figures of the various solutions. bin is the function above, constantin_bin is from <a href="http://stackoverflow.com/questions/187273/base-2-binary-representation-using-python#189579">Constantin's answer</a> and num_bin is the original version. Out of curiosity, I also tried a 16 bit lookup table variant of the above (bin16 below), and tried out Python3's builtin bin() function. All timings were for 100000 runs using an 01010101 bit pattern.</p> <pre><code>Num Bits: 8 16 32 64 128 256 --------------------------------------------------------------------- bin 0.544 0.586 0.744 1.942 1.854 3.357 bin16 0.542 0.494 0.592 0.773 1.150 1.886 constantin_bin 2.238 3.803 7.794 17.869 34.636 94.799 num_bin 3.712 5.693 12.086 32.566 67.523 128.565 Python3's bin 0.079 0.045 0.062 0.069 0.212 0.201 </code></pre> <p>As you can see, when processing long values using large chunks really pays off, but nothing beats the low-level C code of python3's builtin (which bizarrely seems consistently faster at 256 bits than 128!). Using a 16 bit lookup table improves things, but probably isn't worth it unless you really need it, as it uses up a large chunk of memory, and can introduce a small but noticalbe startup delay to precompute the table.</p>
13
2008-10-09T14:29:59Z
[ "python" ]
Base-2 (Binary) Representation Using Python
187,273
<p>Building on <a href="http://stackoverflow.com/questions/1476/how-do-you-express-binary-literals-in-python#13107">How Do You Express Binary Literals in Python</a>, I was thinking about sensible, intuitive ways to do that Programming 101 chestnut of displaying integers in base-2 form. This is the best I came up with, but I'd like to replace it with a better algorithm, or at least one that should have screaming-fast performance. </p> <pre><code>def num_bin(N, places=8): def bit_at_p(N, p): ''' find the bit at place p for number n ''' two_p = 1 &lt;&lt; p # 2 ^ p, using bitshift, will have exactly one # bit set, at place p x = N &amp; two_p # binary composition, will be one where *both* numbers # have a 1 at that bit. this can only happen # at position p. will yield two_p if N has a 1 at # bit p return int(x &gt; 0) bits = ( bit_at_p(N,x) for x in xrange(places)) return "".join( (str(x) for x in bits) ) # or, more consisely # return "".join([str(int((N &amp; 1 &lt;&lt; x)&gt;0)) for x in xrange(places)]) </code></pre>
4
2008-10-09T13:38:32Z
189,579
<p>Not screaming-fast, but straightforward:</p> <pre><code>&gt;&gt;&gt; def bin(x): ... sign = '-' if x &lt; 0 else '' ... x = abs(x) ... bits = [] ... while x: ... x, rmost = divmod(x, 2) ... bits.append(rmost) ... return sign + ''.join(str(b) for b in reversed(bits or [0])) </code></pre> <p>It is also faster than <code>num_bin</code>:</p> <pre><code>&gt;&gt;&gt; import timeit &gt;&gt;&gt; t_bin = timeit.Timer('bin(0xf0)', 'from __main__ import bin') &gt;&gt;&gt; print t_bin.timeit(number=100000) 4.19453350997 &gt;&gt;&gt; t_num_bin = timeit.Timer('num_bin(0xf0)', 'from __main__ import num_bin') &gt;&gt;&gt; print t_num_bin.timeit(number=100000) 4.70694716882 </code></pre> <p>Even more, it actually works correctly (for my definition of "correctness" :)):</p> <pre><code>&gt;&gt;&gt; bin(1) '1' &gt;&gt;&gt; num_bin(1) '10000000' </code></pre>
3
2008-10-09T23:24:24Z
[ "python" ]
How to make parts of a website under SSL and the rest not?
187,434
<p>I need to create a cherrypy main page that has a login area. I want the login area to be secure, but the rest of the page should not be so. How can I do this in CherryPy?</p> <p>Ideally, any suggestions will be compatible with <a href="http://tools.cherrypy.org/wiki/AuthenticationAndAccessRestrictions" rel="nofollow">http://tools.cherrypy.org/wiki/AuthenticationAndAccessRestrictions</a></p> <p>Thanks.</p>
1
2008-10-09T14:09:05Z
187,499
<p>This is commonly considered a bad idea. The primary reason is that it confuses most people due to the website identity markers appearing in just about every current browsers url area.</p>
1
2008-10-09T14:23:57Z
[ "python", "ssl", "cherrypy" ]
How to make parts of a website under SSL and the rest not?
187,434
<p>I need to create a cherrypy main page that has a login area. I want the login area to be secure, but the rest of the page should not be so. How can I do this in CherryPy?</p> <p>Ideally, any suggestions will be compatible with <a href="http://tools.cherrypy.org/wiki/AuthenticationAndAccessRestrictions" rel="nofollow">http://tools.cherrypy.org/wiki/AuthenticationAndAccessRestrictions</a></p> <p>Thanks.</p>
1
2008-10-09T14:09:05Z
187,502
<p>Assuming you only want parts of the actual <em>page</em> to be secure, you should create an iframe pointing to a HTTPS source. However, this shows a <em>"secure and non-secure items on page"</em> warning to the user.</p>
1
2008-10-09T14:24:55Z
[ "python", "ssl", "cherrypy" ]
Counting array elements in Python
187,455
<p>How can I count the number of elements in an array, because contrary to logic array.count(string) does not count all the elements in the array, it just searches for the number of occurrences of string.</p>
64
2008-10-09T14:12:55Z
187,463
<p>The method len() returns the number of elements in the list.</p> <p>Syntax:</p> <pre><code>len(myArray) </code></pre> <p>Eg:</p> <pre><code>myArray = [1, 2, 3] len(myArray) </code></pre> <p>Output:</p> <pre><code>3 </code></pre> <p></p>
156
2008-10-09T14:14:56Z
[ "python", "arrays" ]
Counting array elements in Python
187,455
<p>How can I count the number of elements in an array, because contrary to logic array.count(string) does not count all the elements in the array, it just searches for the number of occurrences of string.</p>
64
2008-10-09T14:12:55Z
187,493
<p>Or,</p> <pre><code>myArray.__len__() </code></pre> <p>if you want to be oopy; "len(myArray)" is a lot easier to type! :)</p>
2
2008-10-09T14:23:27Z
[ "python", "arrays" ]
Counting array elements in Python
187,455
<p>How can I count the number of elements in an array, because contrary to logic array.count(string) does not count all the elements in the array, it just searches for the number of occurrences of string.</p>
64
2008-10-09T14:12:55Z
188,867
<p><code>len</code> is a built-in function that calls the given container object's <code>__len__</code> member function to get the number of elements in the object. </p> <p>Functions encased with double underscores are usually "special methods" implementing one of the standard interfaces in Python (container, number, etc). Special methods are used via syntactic sugar (object creation, container indexing and slicing, attribute access, built-in functions, etc.).</p> <p>Using <code>obj.__len__()</code> wouldn't be the correct way of using the special method, but I don't see why the others were modded down so much.</p>
23
2008-10-09T19:40:04Z
[ "python", "arrays" ]
Counting array elements in Python
187,455
<p>How can I count the number of elements in an array, because contrary to logic array.count(string) does not count all the elements in the array, it just searches for the number of occurrences of string.</p>
64
2008-10-09T14:12:55Z
31,467,803
<p>Before I saw this, I thought to myself, "I need to make a way to do this!"</p> <pre><code>for tempVar in arrayName: tempVar+=1 </code></pre> <p>And then I thought, "There must be a simpler way to do this." and I was right.</p> <p><code>len(arrayName)</code></p>
1
2015-07-17T03:05:05Z
[ "python", "arrays" ]
Counting array elements in Python
187,455
<p>How can I count the number of elements in an array, because contrary to logic array.count(string) does not count all the elements in the array, it just searches for the number of occurrences of string.</p>
64
2008-10-09T14:12:55Z
31,937,513
<p>If you have a multi-dimensional array, len() might not give you the value you are looking for. For instance:</p> <pre><code>a = np.arange(10).reshape(2, 5) print len(a) == 2 </code></pre> <p>This code block will return true, telling you the size of the array is 2. However, there are in actual fact 10 elements in this 2D array. In the case of multi-dimensional arrays, len() gives you the length of the <em>first</em> dimension of the array i.e. </p> <pre><code>len(a) == np.shape(a)[0] </code></pre> <p>To get the number of elements in a multi-dimensional array of arbitrary shape:</p> <pre><code>size = 1 for dim in np.shape(a): size *= dim </code></pre>
3
2015-08-11T09:03:51Z
[ "python", "arrays" ]
How do I capture an mp3 stream with python
187,552
<p>What's the best way of capturing an mp3 stream coming off of http and saving it to disk with python?</p> <p>Thus far I've tried</p> <pre><code>target = open(target_path, "w") conn = urllib.urlopen(stream_url) while True: target.write(conn.read(buf_size)) </code></pre> <p>This gives me data but its garbled or wont play in mp3 players.</p>
11
2008-10-09T14:36:02Z
187,563
<p>If you're on Windows, you might accidentally be doing CRLF conversions, corrupting the binary data. Try opening <code>target</code> in binary mode:</p> <pre><code>target = open(target_path, "wb") </code></pre>
15
2008-10-09T14:40:25Z
[ "python", "streaming" ]
How do I capture an mp3 stream with python
187,552
<p>What's the best way of capturing an mp3 stream coming off of http and saving it to disk with python?</p> <p>Thus far I've tried</p> <pre><code>target = open(target_path, "w") conn = urllib.urlopen(stream_url) while True: target.write(conn.read(buf_size)) </code></pre> <p>This gives me data but its garbled or wont play in mp3 players.</p>
11
2008-10-09T14:36:02Z
3,193,428
<p>The best way for this is:</p> <pre><code>urllib.urlretrieve(stream_url, target_path); </code></pre>
4
2010-07-07T09:20:11Z
[ "python", "streaming" ]
How to make a python, command-line program autocomplete arbitrary things NOT interpreter
187,621
<p>I am aware of how to setup autocompletion of python objects in the python interpreter (on unix). </p> <ul> <li>Google shows many hits for explanations on how to do this.</li> <li>Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different.</li> </ul> <p>I need to know how to enable, tab/auto completion of arbitrary items in a command-line program written in python.</p> <p>My specific use case is a command-line python program that needs to send emails. I want to be able to autocomplete email addresses (I have the addresses on disk) when the user types part of it (and optionally presses the TAB key).</p> <p>I do not need it to work on windows or mac, just linux.</p>
61
2008-10-09T14:55:02Z
187,660
<p>Use Python's <code>readline</code> bindings. For example,</p> <pre><code>import readline def completer(text, state): options = [i for i in commands if i.startswith(text)] if state &lt; len(options): return options[state] else: return None readline.parse_and_bind("tab: complete") readline.set_completer(completer) </code></pre> <p>The official <a href="http://docs.python.org/lib/module-readline.html">module docs</a> aren't much more detailed, see the <a href="http://tiswww.case.edu/php/chet/readline/readline.html#SEC44">readline docs</a> for more info.</p>
38
2008-10-09T15:01:38Z
[ "python", "linux", "unix", "command-line", "autocomplete" ]
How to make a python, command-line program autocomplete arbitrary things NOT interpreter
187,621
<p>I am aware of how to setup autocompletion of python objects in the python interpreter (on unix). </p> <ul> <li>Google shows many hits for explanations on how to do this.</li> <li>Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different.</li> </ul> <p>I need to know how to enable, tab/auto completion of arbitrary items in a command-line program written in python.</p> <p>My specific use case is a command-line python program that needs to send emails. I want to be able to autocomplete email addresses (I have the addresses on disk) when the user types part of it (and optionally presses the TAB key).</p> <p>I do not need it to work on windows or mac, just linux.</p>
61
2008-10-09T14:55:02Z
187,701
<p>Follow the <a href="http://docs.python.org/library/cmd.html#cmd.Cmd.cmdloop">cmd documentation</a> and you'll be fine</p> <pre><code>import cmd addresses = [ '[email protected]', '[email protected]', '[email protected]', ] class MyCmd(cmd.Cmd): def do_send(self, line): pass def complete_send(self, text, line, start_index, end_index): if text: return [ address for address in addresses if address.startswith(text) ] else: return addresses if __name__ == '__main__': my_cmd = MyCmd() my_cmd.cmdloop() </code></pre> <p>Output for tab -> tab -> send -> tab -> tab -> f -> tab</p> <pre><code>(Cmd) help send (Cmd) send [email protected] [email protected] [email protected] (Cmd) send [email protected] (Cmd) </code></pre>
46
2008-10-09T15:08:18Z
[ "python", "linux", "unix", "command-line", "autocomplete" ]
How to make a python, command-line program autocomplete arbitrary things NOT interpreter
187,621
<p>I am aware of how to setup autocompletion of python objects in the python interpreter (on unix). </p> <ul> <li>Google shows many hits for explanations on how to do this.</li> <li>Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different.</li> </ul> <p>I need to know how to enable, tab/auto completion of arbitrary items in a command-line program written in python.</p> <p>My specific use case is a command-line python program that needs to send emails. I want to be able to autocomplete email addresses (I have the addresses on disk) when the user types part of it (and optionally presses the TAB key).</p> <p>I do not need it to work on windows or mac, just linux.</p>
61
2008-10-09T14:55:02Z
197,158
<p>Since you say "NOT interpreter" in your question, I guess you don't want answers involving python readline and suchlike. (<strong><em>edit</strong>: in hindsight, that's obviously not the case. Ho hum. I think this info is interesting anyway, so I'll leave it here.</em>)</p> <p>I think you might be after <a href="http://www.debian-administration.org/articles/317">this</a>.</p> <p>It's about adding shell-level completion to arbitrary commands, extending bash's own tab-completion.</p> <p>In a nutshell, you'll create a file containing a shell-function that will generate possible completions, save it into <code>/etc/bash_completion.d/</code> and register it with the command <code>complete</code>. Here's a snippet from the linked page:</p> <pre><code>_foo() { local cur prev opts COMPREPLY=() cur="${COMP_WORDS[COMP_CWORD]}" prev="${COMP_WORDS[COMP_CWORD-1]}" opts="--help --verbose --version" if [[ ${cur} == -* ]] ; then COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) ) return 0 fi } complete -F _foo foo </code></pre> <p>In this case, the typing <code>foo --[TAB]</code> will give you the values in the variable <code>opts</code>, i.e. <code>--help</code>, <code>--verbose</code> and <code>--version</code>. For your purposes, you'll essentially want to customise the values that are put into <code>opts</code>.</p> <p>Do have a look at the example on the linked page, it's all pretty straightforward. </p>
19
2008-10-13T09:59:23Z
[ "python", "linux", "unix", "command-line", "autocomplete" ]
How to make a python, command-line program autocomplete arbitrary things NOT interpreter
187,621
<p>I am aware of how to setup autocompletion of python objects in the python interpreter (on unix). </p> <ul> <li>Google shows many hits for explanations on how to do this.</li> <li>Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different.</li> </ul> <p>I need to know how to enable, tab/auto completion of arbitrary items in a command-line program written in python.</p> <p>My specific use case is a command-line python program that needs to send emails. I want to be able to autocomplete email addresses (I have the addresses on disk) when the user types part of it (and optionally presses the TAB key).</p> <p>I do not need it to work on windows or mac, just linux.</p>
61
2008-10-09T14:55:02Z
209,915
<p>Here is a full-working version of the code that was very supplied by ephemient <a href="http://stackoverflow.com/questions/187621/how-to-make-a-python-command-line-program-autocomplete-arbitrary-things-not-int#187660">here</a> (thank you).</p> <pre><code>import readline addrs = ['[email protected]', '[email protected]', '[email protected]'] def completer(text, state): options = [x for x in addrs if x.startswith(text)] try: return options[state] except IndexError: return None readline.set_completer(completer) readline.parse_and_bind("tab: complete") while 1: a = raw_input("&gt; ") print "You entered", a </code></pre>
10
2008-10-16T19:26:31Z
[ "python", "linux", "unix", "command-line", "autocomplete" ]
How to make a python, command-line program autocomplete arbitrary things NOT interpreter
187,621
<p>I am aware of how to setup autocompletion of python objects in the python interpreter (on unix). </p> <ul> <li>Google shows many hits for explanations on how to do this.</li> <li>Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different.</li> </ul> <p>I need to know how to enable, tab/auto completion of arbitrary items in a command-line program written in python.</p> <p>My specific use case is a command-line python program that needs to send emails. I want to be able to autocomplete email addresses (I have the addresses on disk) when the user types part of it (and optionally presses the TAB key).</p> <p>I do not need it to work on windows or mac, just linux.</p>
61
2008-10-09T14:55:02Z
19,554,961
<pre><code># ~/.pythonrc import rlcompleter, readline readline.parse_and_bind('tab:complete') # ~/.bashrc export PYTHONSTARTUP=~/.pythonrc </code></pre>
5
2013-10-24T00:48:58Z
[ "python", "linux", "unix", "command-line", "autocomplete" ]
How to make a python, command-line program autocomplete arbitrary things NOT interpreter
187,621
<p>I am aware of how to setup autocompletion of python objects in the python interpreter (on unix). </p> <ul> <li>Google shows many hits for explanations on how to do this.</li> <li>Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different.</li> </ul> <p>I need to know how to enable, tab/auto completion of arbitrary items in a command-line program written in python.</p> <p>My specific use case is a command-line python program that needs to send emails. I want to be able to autocomplete email addresses (I have the addresses on disk) when the user types part of it (and optionally presses the TAB key).</p> <p>I do not need it to work on windows or mac, just linux.</p>
61
2008-10-09T14:55:02Z
23,959,790
<p>I am surprised that nobody has mentioned argcomplete, here is an example from the docs:</p> <pre><code>from argcomplete.completers import ChoicesCompleter parser.add_argument("--protocol", choices=('http', 'https', 'ssh', 'rsync', 'wss')) parser.add_argument("--proto").completer=ChoicesCompleter(('http', 'https', 'ssh', 'rsync', 'wss')) </code></pre>
12
2014-05-30T16:59:54Z
[ "python", "linux", "unix", "command-line", "autocomplete" ]
How to run included tests on deployed pylons application
188,417
<p>I have installed pylons based application from egg, so it sits somewhere under /usr/lib/python2.5/site-packages. I see that the tests are packaged too and I would like to run them (to catch a problem that shows up on deployed application but not on development version). </p> <p>So how do I run them? Doing "nosetests" from directory containing only test.ini and development.ini gives an error about nonexistent test.ini under site-packages.</p>
0
2008-10-09T17:58:56Z
526,861
<p>Straight from <a href="http://wiki.pylonshq.com/display/pylonsdocs/Unit+Testing" rel="nofollow">the horse's mouth</a>:</p> <p>Install nose: easy_install -W nose.</p> <p>Run nose: nosetests --with-pylons=test.ini OR python setup.py nosetests </p> <p>To run "python setup.py nosetests" you need to have a [nosetests] block in your setup.cfg looking like this:</p> <blockquote> <p>[nosetests]</p> <p>verbose=True</p> <p>verbosity=2</p> <p>with-pylons=test.ini</p> <p>detailed-errors=1</p> <p>with-doctest=True</p> </blockquote>
1
2009-02-09T01:22:31Z
[ "python", "unit-testing", "pylons", "nose", "paster" ]
Reading/Writing MS Word files in Python
188,444
<p>Is it possible to read and write Word (2003 and 2007) files in Python without using a COM object?<br /> I know that I can:</p> <pre><code>f = open('c:\file.doc', "w") f.write(text) f.close() </code></pre> <p>but Word will read it as an HTML file not a native .doc file.</p>
15
2008-10-09T18:06:51Z
188,608
<p>doc (Word 2003 in this case) and docx (Word 2007) are different formats, where the latter is usually just an archive of xml and image files. I would imagine that it is very possible to write to docx files by manipulating the contents of those xml files. However I don't see how you could read and write to a doc file without some type of COM component interface. </p>
2
2008-10-09T18:36:25Z
[ "python", "ms-word", "read-write" ]
Reading/Writing MS Word files in Python
188,444
<p>Is it possible to read and write Word (2003 and 2007) files in Python without using a COM object?<br /> I know that I can:</p> <pre><code>f = open('c:\file.doc', "w") f.write(text) f.close() </code></pre> <p>but Word will read it as an HTML file not a native .doc file.</p>
15
2008-10-09T18:06:51Z
188,620
<p>I'd look into <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython">IronPython</a> which intrinsically has access to windows/office APIs because it runs on .NET runtime.</p>
6
2008-10-09T18:39:55Z
[ "python", "ms-word", "read-write" ]
Reading/Writing MS Word files in Python
188,444
<p>Is it possible to read and write Word (2003 and 2007) files in Python without using a COM object?<br /> I know that I can:</p> <pre><code>f = open('c:\file.doc', "w") f.write(text) f.close() </code></pre> <p>but Word will read it as an HTML file not a native .doc file.</p>
15
2008-10-09T18:06:51Z
7,848,324
<p>See <a href="https://github.com/python-openxml/python-docx" rel="nofollow">python-docx</a>, its official documentation is available <a href="https://python-docx.readthedocs.org/en/latest/" rel="nofollow">here</a>. </p> <p>This has worked very well for me.</p>
34
2011-10-21T10:45:37Z
[ "python", "ms-word", "read-write" ]
Reading/Writing MS Word files in Python
188,444
<p>Is it possible to read and write Word (2003 and 2007) files in Python without using a COM object?<br /> I know that I can:</p> <pre><code>f = open('c:\file.doc', "w") f.write(text) f.close() </code></pre> <p>but Word will read it as an HTML file not a native .doc file.</p>
15
2008-10-09T18:06:51Z
30,122,394
<p>If you only what to read, it is <a href="http://stackoverflow.com/questions/16516044/is-it-possible-to-read-word-files-doc-docx-in-python/30122239#30122239">simplest</a> to use the linux soffice command to convert it to text, and then load the text into python: </p>
2
2015-05-08T11:11:58Z
[ "python", "ms-word", "read-write" ]
Django admin interface inlines placement
188,451
<p>I want to be able to place an inline inbetween two different fields in a fieldset. You can already do this with foreignkeys, I figured that inlining the class I wanted and defining it to get extra forms would do the trick, but apparently I get a:<br /> "class x" has no ForeignKey to "class y"<br /> error. Is this not something that is supported in Django 1.0? If so, how would I go about fixing the problem, if there isn't a pre-existing solution? </p> <p>in models.py </p> <pre><code>class Place(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=80) class Owner(models.Model): name = models.CharField(max_length=100) place = models.ForeignKey(Place) background = models.TextField() license_expiration = models.DateTimeField('license expiration') </code></pre> <p>in admin.py</p> <pre><code>class PlaceInline(admin.TabularInline): model = Place extra = 5 class OwnerAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['background','place', 'license_expiration']}), ] inlines = [PlaceInline] </code></pre>
6
2008-10-09T18:08:53Z
188,854
<p>It seems to be impossible in Django admin site itself (you should not include inlined fields in "fields" at all) but you can use JS to move inlined fields wherever you want.</p>
3
2008-10-09T19:36:56Z
[ "python", "django", "django-admin" ]
How can I, in python, iterate over multiple 2d lists at once, cleanly?
189,087
<p>If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this.</p> <pre><code>for i in range(len(alist)): for j in range(len(alist[i])): if alist[i][j].isWhatever: blist[i][j].doSomething() </code></pre> <p>Is there a nicer way to do something like this?</p>
22
2008-10-09T20:32:13Z
189,096
<pre><code>for d1 in alist for d2 in d1 if d2 = "whatever" do_my_thing() </code></pre>
-4
2008-10-09T20:35:28Z
[ "python" ]
How can I, in python, iterate over multiple 2d lists at once, cleanly?
189,087
<p>If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this.</p> <pre><code>for i in range(len(alist)): for j in range(len(alist[i])): if alist[i][j].isWhatever: blist[i][j].doSomething() </code></pre> <p>Is there a nicer way to do something like this?</p>
22
2008-10-09T20:32:13Z
189,111
<p>You could zip them. ie:</p> <pre><code>for a_row,b_row in zip(alist, blist): for a_item, b_item in zip(a_row,b_row): if a_item.isWhatever: b_item.doSomething() </code></pre> <p>However the overhead of zipping and iterating over the items may be higher than your original method if you rarely actually use the b_item (ie a_item.isWhatever is usually False). You could use itertools.izip instead of zip to reduce the memory impact of this, but its still probably going to be slightly slower unless you always need the b_item.</p> <p>Alternatively, consider using a 3D list instead, so terrain for cell i,j is at l[i][j][0], objects at l[i][j][1] etc, or even combine the objects so you can do a[i][j].terrain, a[i][j].object etc.</p> <p>[Edit] <a href="http://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly#189497">DzinX's timings</a> actually show that the impact of the extra check for b_item isn't really significant, next to the performance penalty of re-looking up by index, so the above (using izip) seems to be fastest. </p> <p>I've now given a quick test for the 3d approach as well, and it seems faster still, so if you can store your data in that form, it could be both simpler and faster to access. Here's an example of using it:</p> <pre><code># Initialise 3d list: alist = [ [[A(a_args), B(b_args)] for i in xrange(WIDTH)] for j in xrange(HEIGHT)] # Process it: for row in xlist: for a,b in row: if a.isWhatever(): b.doSomething() </code></pre> <p>Here are my timings for 10 loops using a 1000x1000 array, with various proportions of isWhatever being true are:</p> <pre><code> ( Chance isWhatever is True ) Method 100% 50% 10% 1% 3d 3.422 2.151 1.067 0.824 izip 3.647 2.383 1.282 0.985 original 5.422 3.426 1.891 1.534 </code></pre>
10
2008-10-09T20:39:29Z
[ "python" ]
How can I, in python, iterate over multiple 2d lists at once, cleanly?
189,087
<p>If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this.</p> <pre><code>for i in range(len(alist)): for j in range(len(alist[i])): if alist[i][j].isWhatever: blist[i][j].doSomething() </code></pre> <p>Is there a nicer way to do something like this?</p>
22
2008-10-09T20:32:13Z
189,112
<p>Are you sure that the objects in the two matrices you are iterating in parallel are instances of conceptually distinct classes? What about merging the two classes ending up with a matrix of objects that contain <em>both</em> isWhatever() and doSomething()?</p>
2
2008-10-09T20:39:35Z
[ "python" ]
How can I, in python, iterate over multiple 2d lists at once, cleanly?
189,087
<p>If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this.</p> <pre><code>for i in range(len(alist)): for j in range(len(alist[i])): if alist[i][j].isWhatever: blist[i][j].doSomething() </code></pre> <p>Is there a nicer way to do something like this?</p>
22
2008-10-09T20:32:13Z
189,165
<p>I'd start by writing a generator method:</p> <pre><code>def grid_objects(alist, blist): for i in range(len(alist)): for j in range(len(alist[i])): yield(alist[i][j], blist[i][j]) </code></pre> <p>Then whenever you need to iterate over the lists your code looks like this:</p> <pre><code>for (a, b) in grid_objects(alist, blist): if a.is_whatever(): b.do_something() </code></pre>
14
2008-10-09T20:51:33Z
[ "python" ]
How can I, in python, iterate over multiple 2d lists at once, cleanly?
189,087
<p>If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this.</p> <pre><code>for i in range(len(alist)): for j in range(len(alist[i])): if alist[i][j].isWhatever: blist[i][j].doSomething() </code></pre> <p>Is there a nicer way to do something like this?</p>
22
2008-10-09T20:32:13Z
189,234
<p><a href="http://www.python.org/doc/2.5.2/ref/genexpr.html" rel="nofollow">Generator expressions</a> and <code>izip</code> from <a href="http://www.python.org/doc/2.5.2/lib/itertools-functions.html" rel="nofollow">itertools module</a> will do very nicely here:</p> <pre><code>from itertools import izip for a, b in (pair for (aline, bline) in izip(alist, blist) for pair in izip(aline, bline)): if a.isWhatever: b.doSomething() </code></pre> <p>The line in <code>for</code> statement above means:</p> <ul> <li>take each line from combined grids <code>alist</code> and <code>blist</code> and make a tuple from them <code>(aline, bline)</code></li> <li>now combine these lists with <code>izip</code> again and take each element from them (<code>pair</code>).</li> </ul> <p>This method has two advantages:</p> <ul> <li>there are no indices used anywhere</li> <li>you don't have to create lists with <code>zip</code> and use more efficient generators with <code>izip</code> instead.</li> </ul>
3
2008-10-09T21:12:10Z
[ "python" ]
How can I, in python, iterate over multiple 2d lists at once, cleanly?
189,087
<p>If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this.</p> <pre><code>for i in range(len(alist)): for j in range(len(alist[i])): if alist[i][j].isWhatever: blist[i][j].doSomething() </code></pre> <p>Is there a nicer way to do something like this?</p>
22
2008-10-09T20:32:13Z
189,270
<p>As a slight style change, you could use enumerate:</p> <pre><code>for i, arow in enumerate(alist): for j, aval in enumerate(arow): if aval.isWhatever(): blist[i][j].doSomething() </code></pre> <p>I don't think you'll get anything significantly simpler unless you rearrange your data structures as Federico suggests. So that you could turn the last line into something like "aval.b.doSomething()".</p>
3
2008-10-09T21:24:17Z
[ "python" ]
How can I, in python, iterate over multiple 2d lists at once, cleanly?
189,087
<p>If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this.</p> <pre><code>for i in range(len(alist)): for j in range(len(alist[i])): if alist[i][j].isWhatever: blist[i][j].doSomething() </code></pre> <p>Is there a nicer way to do something like this?</p>
22
2008-10-09T20:32:13Z
189,348
<p>If the two 2D-lists remain constant during the lifetime of your game <em>and</em> you can't enjoy Python's multiple inheritance to join the alist[i][j] and blist[i][j] object classes (as others have suggested), you could add a pointer to the corresponding <em>b</em> item in each <em>a</em> item after the lists are created, like this:</p> <pre><code>for a_row, b_row in itertools.izip(alist, blist): for a_item, b_item in itertools.izip(a_row, b_row): a_item.b_item= b_item </code></pre> <p>Various optimisations can apply here, like your classes having <code>__slots__</code> defined, or the initialization code above could be merged with your own initialization code e.t.c. After that, your loop will become:</p> <pre><code>for a_row in alist: for a_item in a_row: if a_item.isWhatever(): a_item.b_item.doSomething() </code></pre> <p>That should be more efficient.</p>
1
2008-10-09T21:53:23Z
[ "python" ]
How can I, in python, iterate over multiple 2d lists at once, cleanly?
189,087
<p>If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this.</p> <pre><code>for i in range(len(alist)): for j in range(len(alist[i])): if alist[i][j].isWhatever: blist[i][j].doSomething() </code></pre> <p>Is there a nicer way to do something like this?</p>
22
2008-10-09T20:32:13Z
189,497
<p>If anyone is interested in performance of the above solutions, here they are for 4000x4000 grids, from fastest to slowest:</p> <ul> <li><a href="http://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly#189111">Brian</a>: 1.08s (modified, with <code>izip</code> instead of <code>zip</code>)</li> <li><a href="http://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly#189270">John</a>: 2.33s</li> <li><a href="http://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly#189234">DzinX</a>: 2.36s</li> <li><a href="http://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly#189348">ΤΖΩΤΖΙΟΥ</a>: 2.41s (but object initialization took 62s)</li> <li><a href="http://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly">Eugene</a>: 3.17s</li> <li><a href="http://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly#189165">Robert</a>: 4.56s</li> <li><a href="http://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly#189111">Brian</a>: 27.24s (original, with <code>zip</code>)</li> </ul> <p><strong>EDIT</strong>: Added Brian's scores with <code>izip</code> modification and it won by a large amount!</p> <p>John's solution is also very fast, although it uses indices (I was really surprised to see this!), whereas Robert's and Brian's (with <code>zip</code>) are slower than the question creator's initial solution.</p> <p>So let's present <a href="http://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly#189111">Brian</a>'s winning function, as it is not shown in proper form anywhere in this thread:</p> <pre><code>from itertools import izip for a_row,b_row in izip(alist, blist): for a_item, b_item in izip(a_row,b_row): if a_item.isWhatever: b_item.doSomething() </code></pre>
32
2008-10-09T22:49:19Z
[ "python" ]
How can I, in python, iterate over multiple 2d lists at once, cleanly?
189,087
<p>If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this.</p> <pre><code>for i in range(len(alist)): for j in range(len(alist[i])): if alist[i][j].isWhatever: blist[i][j].doSomething() </code></pre> <p>Is there a nicer way to do something like this?</p>
22
2008-10-09T20:32:13Z
190,904
<p>When you are operating with grids of numbers and want really good performance, you should consider using <a href="http://numpy.scipy.org" rel="nofollow">Numpy</a>. It's surprisingly easy to use and lets you think in terms of operations with grids instead of loops over grids. The performance comes from the fact that the operations are then run over whole grids with optimised SSE code.</p> <p>For example here is some numpy using code that I wrote that does brute force numerical simulation of charged particles connected by springs. This code calculates a timestep for a 3d system with 100 nodes and 99 edges in 31ms. That is over 10x faster than the best pure python code I could come up with.</p> <pre><code>from numpy import array, sqrt, float32, newaxis def evolve(points, velocities, edges, timestep=0.01, charge=0.1, mass=1., edgelen=0.5, dampen=0.95): """Evolve a n body system of electrostatically repulsive nodes connected by springs by one timestep.""" velocities *= dampen # calculate matrix of distance vectors between all points and their lengths squared dists = array([[p2 - p1 for p2 in points] for p1 in points]) l_2 = (dists*dists).sum(axis=2) # make the diagonal 1's to avoid division by zero for i in xrange(points.shape[0]): l_2[i,i] = 1 l_2_inv = 1/l_2 l_3_inv = l_2_inv*sqrt(l_2_inv) # repulsive force: distance vectors divided by length cubed, summed and multiplied by scale scale = timestep*charge*charge/mass velocities -= scale*(l_3_inv[:,:,newaxis].repeat(points.shape[1], axis=2)*dists).sum(axis=1) # calculate spring contributions for each point for idx, (point, outedges) in enumerate(izip(points, edges)): edgevecs = point - points.take(outedges, axis=0) edgevec_lens = sqrt((edgevecs*edgevecs).sum(axis=1)) scale = timestep/mass velocities[idx] += (edgevecs*((((edgelen*scale)/edgevec_lens - scale))[:,newaxis].repeat(points.shape[1],axis=1))).sum(axis=0) # move points to new positions points += velocities*timestep </code></pre>
3
2008-10-10T11:30:37Z
[ "python" ]
How can I, in python, iterate over multiple 2d lists at once, cleanly?
189,087
<p>If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this.</p> <pre><code>for i in range(len(alist)): for j in range(len(alist[i])): if alist[i][j].isWhatever: blist[i][j].doSomething() </code></pre> <p>Is there a nicer way to do something like this?</p>
22
2008-10-09T20:32:13Z
193,825
<p>If <code>a.isWhatever</code> is rarely true you could build an "index" once:</p> <pre><code>a_index = set((i,j) for i,arow in enumerate(a) for j,a in enumerate(arow) if a.IsWhatever()) </code></pre> <p>and each time you want something to be done:</p> <pre><code>for (i,j) in a_index: b[i][j].doSomething() </code></pre> <p>If a changes over time, then you will need to keep the index up-to-date. That's why I used a set, so items can be added and removed fast.</p>
0
2008-10-11T07:49:43Z
[ "python" ]
How to use Python to login to a webpage and retrieve cookies for later usage?
189,555
<p>I want to download and parse webpage using python, but to access it I need a couple of cookies set. Therefore I need to login over https to the webpage first. The login moment involves sending two POST params (username, password) to /login.php. During the login request I want to retrieve the cookies from the response header and store them so I can use them in the request to download the webpage /data.php.</p> <p>How would I do this in python (preferably 2.6)? If possible I only want to use builtin modules.</p>
126
2008-10-09T23:14:43Z
189,580
<pre><code>import urllib, urllib2, cookielib username = 'myuser' password = 'mypassword' cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) login_data = urllib.urlencode({'username' : username, 'j_password' : password}) opener.open('http://www.example.com/login.php', login_data) resp = opener.open('http://www.example.com/hiddenpage.php') print resp.read() </code></pre> <p><code>resp.read()</code> is the straight html of the page you want to open, and you can use <code>opener</code> to view any page using your session cookie.</p>
132
2008-10-09T23:24:39Z
[ "python", "http", "authentication", "cookies" ]
How to use Python to login to a webpage and retrieve cookies for later usage?
189,555
<p>I want to download and parse webpage using python, but to access it I need a couple of cookies set. Therefore I need to login over https to the webpage first. The login moment involves sending two POST params (username, password) to /login.php. During the login request I want to retrieve the cookies from the response header and store them so I can use them in the request to download the webpage /data.php.</p> <p>How would I do this in python (preferably 2.6)? If possible I only want to use builtin modules.</p>
126
2008-10-09T23:14:43Z
12,103,969
<p>Here's a version using the excellent <a href="http://docs.python-requests.org/en/latest/index.html">requests</a> library:</p> <pre><code>from requests import session payload = { 'action': 'login', 'username': USERNAME, 'password': PASSWORD } with session() as c: c.post('http://example.com/login.php', data=payload) response = c.get('http://example.com/protected_page.php') print(response.headers) print(response.text) </code></pre>
122
2012-08-24T06:07:36Z
[ "python", "http", "authentication", "cookies" ]
How to break out of multiple loops in Python?
189,645
<p>Given the following code (that doesn't work):</p> <pre><code>while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p> <p><strong>Edit-FYI:</strong> get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns <code>stdin.readline().strip()</code></p>
226
2008-10-10T00:02:01Z
189,664
<p>First, ordinary logic is helpful. </p> <p>If, for some reason, the terminating conditions can't be worked out, exceptions are a fall-back plan. </p> <pre><code>class GetOutOfLoop( Exception ): pass try: done= False while not done: isok= False while not (done or isok): ok = get_input("Is this ok? (y/n)") if ok in ("y", "Y") or ok in ("n", "N") : done= True # probably better raise GetOutOfLoop # other stuff except GetOutOfLoop: pass </code></pre> <p>For this specific example, an exception may not be necessary. </p> <p>On other other hand, we often have "Y", "N" and "Q" options in character-mode applications. For the "Q" option, we want an immediate exit. That's more exceptional.</p>
70
2008-10-10T00:11:37Z
[ "python", "control-flow" ]
How to break out of multiple loops in Python?
189,645
<p>Given the following code (that doesn't work):</p> <pre><code>while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p> <p><strong>Edit-FYI:</strong> get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns <code>stdin.readline().strip()</code></p>
226
2008-10-10T00:02:01Z
189,666
<p>First, you may also consider making the process of getting and validating the input a function; within that function, you can just return the value if its correct, and keep spinning in the <em>while</em> loop if not. This essentially obviates the problem you solved, and can usually be applied in the more general case (breaking out of multiple loops). If you absolutely must keep this structure in your code, and really don't want to deal with bookkeeping booleans...</p> <p>You may also use <em>goto</em> in the following way (using an April Fools module from <a href="http://entrian.com/goto/">here</a>):</p> <pre><code>#import the stuff from goto import goto, label while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": goto .breakall if ok == "n" or ok == "N": break #do more processing with menus and stuff label .breakall </code></pre> <p>I know, I know, "thou shalt not use goto" and all that, but it works well in strange cases like this.</p>
29
2008-10-10T00:12:38Z
[ "python", "control-flow" ]
How to break out of multiple loops in Python?
189,645
<p>Given the following code (that doesn't work):</p> <pre><code>while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p> <p><strong>Edit-FYI:</strong> get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns <code>stdin.readline().strip()</code></p>
226
2008-10-10T00:02:01Z
189,685
<p>My first instinct would be to refactor the nested loop into a function and use <code>return</code> to break out. </p>
258
2008-10-10T00:25:05Z
[ "python", "control-flow" ]
How to break out of multiple loops in Python?
189,645
<p>Given the following code (that doesn't work):</p> <pre><code>while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p> <p><strong>Edit-FYI:</strong> get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns <code>stdin.readline().strip()</code></p>
226
2008-10-10T00:02:01Z
189,696
<pre><code> keeplooping=True while keeplooping: #Do Stuff while keeplooping: #do some other stuff if finisheddoingstuff(): keeplooping=False </code></pre> <p>or something like that. You could set a variable in the inner loop, and check it in the outer loop immediately after the inner loop exits, breaking if appropriate. I kinda like the GOTO method, provided you don't mind using an April Fool's joke module - its not Pythonic, but it does make sense.</p>
7
2008-10-10T00:29:37Z
[ "python", "control-flow" ]
How to break out of multiple loops in Python?
189,645
<p>Given the following code (that doesn't work):</p> <pre><code>while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p> <p><strong>Edit-FYI:</strong> get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns <code>stdin.readline().strip()</code></p>
226
2008-10-10T00:02:01Z
189,838
<p>This isn't the prettiest way to do it, but in my opinion, it's the best way. </p> <pre><code>def loop(): while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": return if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>I'm pretty sure you could work out something using recursion here as well, but I dunno if that's a good option for you.</p>
7
2008-10-10T01:41:42Z
[ "python", "control-flow" ]
How to break out of multiple loops in Python?
189,645
<p>Given the following code (that doesn't work):</p> <pre><code>while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p> <p><strong>Edit-FYI:</strong> get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns <code>stdin.readline().strip()</code></p>
226
2008-10-10T00:02:01Z
190,070
<p><a href="http://www.python.org/dev/peps/pep-3136/">PEP 3136</a> proposes labeled break/continue. Guido <a href="http://mail.python.org/pipermail/python-3000/2007-July/008663.html">rejected it</a> because "code so complicated to require this feature is very rare". The PEP does mention some workarounds, though (such as the exception technique), while Guido feels refactoring to use return will be simpler in most cases.</p>
93
2008-10-10T03:50:44Z
[ "python", "control-flow" ]
How to break out of multiple loops in Python?
189,645
<p>Given the following code (that doesn't work):</p> <pre><code>while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p> <p><strong>Edit-FYI:</strong> get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns <code>stdin.readline().strip()</code></p>
226
2008-10-10T00:02:01Z
2,621,659
<p>Factor your loop logic into an iterator that yields the loop variables and returns when done -- here is a simple one that lays out images in rows/columns until we're out of images or out of places to put them:</p> <pre><code>def it(rows, cols, images): i = 0 for r in xrange(rows): for c in xrange(cols): if i &gt;= len(images): return yield r, c, images[i] i += 1 for r, c, image in it(rows=4, cols=4, images=['a.jpg', 'b.jpg', 'c.jpg']): ... do something with r, c, image ... </code></pre> <p>This has the advantage of splitting up the complicated loop logic and the processing...</p>
7
2010-04-12T11:33:15Z
[ "python", "control-flow" ]
How to break out of multiple loops in Python?
189,645
<p>Given the following code (that doesn't work):</p> <pre><code>while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p> <p><strong>Edit-FYI:</strong> get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns <code>stdin.readline().strip()</code></p>
226
2008-10-10T00:02:01Z
3,150,107
<p>Here's another approach that is short. The disadvantage is that you can only break the outer loop, but sometimes it's exactly what you want.</p> <pre><code>for a in xrange(10): for b in xrange(20): if something(a, b): # Break the inner loop... break else: # Continue if the inner loop wasn't broken. continue # Inner loop was broken, break the outer. break </code></pre>
63
2010-06-30T14:15:59Z
[ "python", "control-flow" ]
How to break out of multiple loops in Python?
189,645
<p>Given the following code (that doesn't work):</p> <pre><code>while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p> <p><strong>Edit-FYI:</strong> get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns <code>stdin.readline().strip()</code></p>
226
2008-10-10T00:02:01Z
3,171,971
<p>I tend to agree that refactoring into a function is usually the best approach for this sort of situation, but for when you <em>really</em> need to break out of nested loops, here's an interesting variant of the exception-raising approach that @S.Lott described. It uses Python's <code>with</code> statement to make the exception raising look a bit nicer. Define a new context manager (you only have to do this once) with:</p> <pre><code>from contextlib import contextmanager @contextmanager def nested_break(): class NestedBreakException(Exception): pass try: yield NestedBreakException except NestedBreakException: pass </code></pre> <p>Now you can use this context manager as follows:</p> <pre><code>with nested_break() as mylabel: while True: print "current state" while True: ok = raw_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": raise mylabel if ok == "n" or ok == "N": break print "more processing" </code></pre> <p>Advantages: (1) it's slightly cleaner (no explicit try-except block), and (2) you get a custom-built <code>Exception</code> subclass for each use of <code>nested_break</code>; no need to declare your own <code>Exception</code> subclass each time.</p>
34
2010-07-03T15:50:53Z
[ "python", "control-flow" ]
How to break out of multiple loops in Python?
189,645
<p>Given the following code (that doesn't work):</p> <pre><code>while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p> <p><strong>Edit-FYI:</strong> get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns <code>stdin.readline().strip()</code></p>
226
2008-10-10T00:02:01Z
6,564,670
<p>Introduce a new variable that you'll use as a 'loop breaker'. First assign something to it(False,0, etc.), and then, inside the outer loop, before you break from it, change the value to something else(True,1,...). Once the loop exits make the 'parent' loop check for that value. Let me demonstrate:</p> <pre><code>breaker = False #our mighty loop exiter! while True: while True: if conditionMet: #insert code here... breaker = True break if breaker: # the interesting part! break # &lt;--- ! </code></pre> <p>If you have an infinite loop, this is the only way out; for other loops execution is really a lot faster. This also works if you have many nested loops. You can exit all, or just a few. Endless possibilities! Hope this helped!</p>
12
2011-07-03T18:15:55Z
[ "python", "control-flow" ]
How to break out of multiple loops in Python?
189,645
<p>Given the following code (that doesn't work):</p> <pre><code>while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p> <p><strong>Edit-FYI:</strong> get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns <code>stdin.readline().strip()</code></p>
226
2008-10-10T00:02:01Z
10,930,656
<p>Similar like the one before, but more compact. (Booleans are just numbers)</p> <pre><code>breaker = False #our mighty loop exiter! while True: while True: ok = get_input("Is this ok? (y/n)") breaker+= (ok.lower() == "y") break if breaker: # the interesting part! break # &lt;--- ! </code></pre>
0
2012-06-07T11:12:22Z
[ "python", "control-flow" ]
How to break out of multiple loops in Python?
189,645
<p>Given the following code (that doesn't work):</p> <pre><code>while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p> <p><strong>Edit-FYI:</strong> get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns <code>stdin.readline().strip()</code></p>
226
2008-10-10T00:02:01Z
11,974,716
<p>My reason for coming here is that i had an outer loop and an inner loop like so:</p> <pre><code>for x in array: for y in dont_use_these_values: if x.value==y: array.pop(x) continue do some other stuff with x </code></pre> <p>As you can see, it won't actually go to the next x, but will go to the next y instead.</p> <p>what i found to solve this simply was to run through the array twice instead:</p> <pre><code>for x in array: for y in dont_use_these_values: if x.value==y: array.pop(x) continue for x in array: do some other stuff with x </code></pre> <p>I know this was a specific case of OP's question, but I am posting it in the hope that it will help someone think about their problem differently while keeping things simple.</p>
0
2012-08-15T18:12:49Z
[ "python", "control-flow" ]
How to break out of multiple loops in Python?
189,645
<p>Given the following code (that doesn't work):</p> <pre><code>while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p> <p><strong>Edit-FYI:</strong> get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns <code>stdin.readline().strip()</code></p>
226
2008-10-10T00:02:01Z
13,252,668
<p>And why not to keep looping if two conditions are true? I think this is a more pythonic way:</p> <pre><code>dejaVu = True while dejaVu: while True: ok = raw_input("Is this ok? (y/n)") if ok == "y" or ok == "Y" or ok == "n" or ok == "N": dejaVu = False break </code></pre> <p>Isn't it?</p> <p>All the best.</p>
4
2012-11-06T14:02:32Z
[ "python", "control-flow" ]
How to break out of multiple loops in Python?
189,645
<p>Given the following code (that doesn't work):</p> <pre><code>while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p> <p><strong>Edit-FYI:</strong> get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns <code>stdin.readline().strip()</code></p>
226
2008-10-10T00:02:01Z
15,559,616
<pre><code>Try using an infinite generator. from itertools import repeat inputs = (get_input("Is this ok? (y/n)") for _ in repeat(None)) response = (i.lower()=="y" for i in inputs if i.lower() in ("y", "n")) while True: #snip: print out current state if next(response): break #do more processing with menus and stuff </code></pre>
0
2013-03-21T22:45:58Z
[ "python", "control-flow" ]
How to break out of multiple loops in Python?
189,645
<p>Given the following code (that doesn't work):</p> <pre><code>while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p> <p><strong>Edit-FYI:</strong> get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns <code>stdin.readline().strip()</code></p>
226
2008-10-10T00:02:01Z
17,092,776
<pre><code>break_levels = 0 while True: # snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break_levels = 1 # how far nested, excluding this break break if ok == "n" or ok == "N": break # normal break if break_levels: break_levels -= 1 break # pop another level if break_levels: break_levels -= 1 break # ...and so on </code></pre>
0
2013-06-13T16:53:56Z
[ "python", "control-flow" ]
How to break out of multiple loops in Python?
189,645
<p>Given the following code (that doesn't work):</p> <pre><code>while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p> <p><strong>Edit-FYI:</strong> get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns <code>stdin.readline().strip()</code></p>
226
2008-10-10T00:02:01Z
17,093,146
<pre><code>break_label = None while True: # snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break_label = "outer" # specify label to break to break if ok == "n" or ok == "N": break if break_label: if break_label != "inner": break # propagate up break_label = None # we have arrived! if break_label: if break_label != "outer": break # propagate up break_label = None # we have arrived! #do more processing with menus and stuff </code></pre>
0
2013-06-13T17:15:18Z
[ "python", "control-flow" ]
How to break out of multiple loops in Python?
189,645
<p>Given the following code (that doesn't work):</p> <pre><code>while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p> <p><strong>Edit-FYI:</strong> get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns <code>stdin.readline().strip()</code></p>
226
2008-10-10T00:02:01Z
32,023,069
<p>In this case, as pointed out by others as well, functional decomposition is the way to go. Code in Python 3:</p> <pre><code>def user_confirms(): while True: answer = input("Is this OK? (y/n) ").strip().lower() if answer in "yn": return answer == "y" def main(): while True: # do stuff if user_confirms(): break </code></pre>
1
2015-08-15T08:42:47Z
[ "python", "control-flow" ]
How to break out of multiple loops in Python?
189,645
<p>Given the following code (that doesn't work):</p> <pre><code>while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p> <p><strong>Edit-FYI:</strong> get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns <code>stdin.readline().strip()</code></p>
226
2008-10-10T00:02:01Z
33,121,569
<p>There is a hidden trick in the Python <code>while ... else</code> structure which can be used to simulate the double break without much code changes/additions. In essence if the <code>while</code> condition is false, the <code>else</code> block is triggered. Neither exceptions, <code>continue</code> or <code>break</code> trigger the <code>else</code> block. For more information see answers to "<a href="http://stackoverflow.com/q/3295938/1548472">Else clause on Python while statement</a>", or <a href="//docs.python.org/2.7/reference/compound_stmts.html#the-while-statement" rel="nofollow">Python doc on while (v2.7)</a>.</p> <pre><code>while True: #snip: print out current state ok = "" while ok != "y" and ok != "n": ok = get_input("Is this ok? (y/n)") if ok == "n" or ok == "N": break # Breaks out of inner loop, skipping else else: break # Breaks out of outer loop #do more processing with menus and stuff </code></pre> <p>The only downside is that you need to move the double breaking condition into the <code>while</code> condition (or add a flag variable). Variations of this exists also for the <code>for</code> loop, where the <code>else</code> block is triggered after loop completion.</p>
0
2015-10-14T09:29:41Z
[ "python", "control-flow" ]
How to break out of multiple loops in Python?
189,645
<p>Given the following code (that doesn't work):</p> <pre><code>while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff </code></pre> <p>Is there a way to make this work? Or do I have do one check to break out of the input loop, then another, more limited, check in the outside loop to break out all together if the user is satisfied?</p> <p><strong>Edit-FYI:</strong> get_input is a short function I wrote that supports showing a prompt and default values and all that fanciness and returns <code>stdin.readline().strip()</code></p>
226
2008-10-10T00:02:01Z
40,120,729
<p>probably little trick like below will do if not prefer to refactorial into function</p> <p>added 1 break_level variable to control the while loop condition</p> <pre><code>break_level = 0 # while break_level &lt; 3: # if we have another level of nested loop here while break_level &lt; 2: #snip: print out current state while break_level &lt; 1: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break_level = 2 # break 2 level if ok == "n" or ok == "N": break_level = 1 # break 1 level </code></pre>
0
2016-10-19T01:44:36Z
[ "python", "control-flow" ]
Google App Engine and 404 error
189,751
<p>I've setup a static website on GAE using hints found elsewhere, but can't figure out how to return a 404 error. My app.yaml file looks like</p> <pre><code>- url: (.*)/ static_files: static\1/index.html upload: static/index.html - url: / static_dir: static </code></pre> <p>with all the static html/jpg files stored under the static directory. The above works for files that exist, but returns a null length file if they don't. The answer is probably to write a python script to return a 404 error, but how do you set things up to serve the static files that exist but run the script for files that don't?</p> <p>Here is the log from fetching a non-existent file (nosuch.html) on the development application server:</p> <pre><code>ERROR 2008-11-25 20:08:34,084 dev_appserver.py] Error encountered reading file "/usr/home/ctuffli/www/tufflinet/static/nosuch.html": [Errno 2] No such file or directory: '/usr/home/ctuffli/www/tufflinet/static/nosuch.html' INFO 2008-11-25 20:08:34,088 dev_appserver.py] "GET /nosuch.html HTTP/1.1" 404 - </code></pre>
35
2008-10-10T00:51:00Z
189,935
<p>You need to register a catch-all script handler. Append this at the end of your app.yaml:</p> <pre><code>- url: /.* script: main.py </code></pre> <p>In main.py you will need to put this code:</p> <pre><code>from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app class NotFoundPageHandler(webapp.RequestHandler): def get(self): self.error(404) self.response.out.write('&lt;Your 404 error html page&gt;') application = webapp.WSGIApplication([('/.*', NotFoundPageHandler)], debug=True) def main(): run_wsgi_app(application) if __name__ == "__main__": main() </code></pre> <p>Replace <code>&lt;Your 404 error html page&gt;</code> with something meaningful. Or better use a template, you can read how to do that <a href="http://code.google.com/appengine/docs/gettingstarted/templates.html">here</a>.</p> <p>Please let me know if you have problems setting this up.</p>
33
2008-10-10T02:36:02Z
[ "python", "google-app-engine", "http-status-code-404" ]
Google App Engine and 404 error
189,751
<p>I've setup a static website on GAE using hints found elsewhere, but can't figure out how to return a 404 error. My app.yaml file looks like</p> <pre><code>- url: (.*)/ static_files: static\1/index.html upload: static/index.html - url: / static_dir: static </code></pre> <p>with all the static html/jpg files stored under the static directory. The above works for files that exist, but returns a null length file if they don't. The answer is probably to write a python script to return a 404 error, but how do you set things up to serve the static files that exist but run the script for files that don't?</p> <p>Here is the log from fetching a non-existent file (nosuch.html) on the development application server:</p> <pre><code>ERROR 2008-11-25 20:08:34,084 dev_appserver.py] Error encountered reading file "/usr/home/ctuffli/www/tufflinet/static/nosuch.html": [Errno 2] No such file or directory: '/usr/home/ctuffli/www/tufflinet/static/nosuch.html' INFO 2008-11-25 20:08:34,088 dev_appserver.py] "GET /nosuch.html HTTP/1.1" 404 - </code></pre>
35
2008-10-10T00:51:00Z
855,877
<p>A significantly simpler way to do this without requiring any CPU cycles is to place this handler at the bottom of your app.yaml</p> <pre><code>- url: /.* static_files: views/404.html upload: views/404.html </code></pre> <p>This then allows you to place a static 404.html file in your views directory. No need for a python handler. Anything that isn't handled in your app.yaml already will hit that.</p>
4
2009-05-13T03:08:55Z
[ "python", "google-app-engine", "http-status-code-404" ]
Google App Engine and 404 error
189,751
<p>I've setup a static website on GAE using hints found elsewhere, but can't figure out how to return a 404 error. My app.yaml file looks like</p> <pre><code>- url: (.*)/ static_files: static\1/index.html upload: static/index.html - url: / static_dir: static </code></pre> <p>with all the static html/jpg files stored under the static directory. The above works for files that exist, but returns a null length file if they don't. The answer is probably to write a python script to return a 404 error, but how do you set things up to serve the static files that exist but run the script for files that don't?</p> <p>Here is the log from fetching a non-existent file (nosuch.html) on the development application server:</p> <pre><code>ERROR 2008-11-25 20:08:34,084 dev_appserver.py] Error encountered reading file "/usr/home/ctuffli/www/tufflinet/static/nosuch.html": [Errno 2] No such file or directory: '/usr/home/ctuffli/www/tufflinet/static/nosuch.html' INFO 2008-11-25 20:08:34,088 dev_appserver.py] "GET /nosuch.html HTTP/1.1" 404 - </code></pre>
35
2008-10-10T00:51:00Z
3,722,135
<p>google app engine now has <a href="https://cloud.google.com/appengine/docs/python/config/appconfig?csw=1#Python_app_yaml_Custom_error_responses" rel="nofollow">Custom Error Responses</a></p> <p>so you can now add an error_handlers section to your app.yaml, as in this example:</p> <pre><code>error_handlers: - file: default_error.html - error_code: over_quota file: over_quota.html </code></pre>
25
2010-09-15T21:50:05Z
[ "python", "google-app-engine", "http-status-code-404" ]
Google App Engine and 404 error
189,751
<p>I've setup a static website on GAE using hints found elsewhere, but can't figure out how to return a 404 error. My app.yaml file looks like</p> <pre><code>- url: (.*)/ static_files: static\1/index.html upload: static/index.html - url: / static_dir: static </code></pre> <p>with all the static html/jpg files stored under the static directory. The above works for files that exist, but returns a null length file if they don't. The answer is probably to write a python script to return a 404 error, but how do you set things up to serve the static files that exist but run the script for files that don't?</p> <p>Here is the log from fetching a non-existent file (nosuch.html) on the development application server:</p> <pre><code>ERROR 2008-11-25 20:08:34,084 dev_appserver.py] Error encountered reading file "/usr/home/ctuffli/www/tufflinet/static/nosuch.html": [Errno 2] No such file or directory: '/usr/home/ctuffli/www/tufflinet/static/nosuch.html' INFO 2008-11-25 20:08:34,088 dev_appserver.py] "GET /nosuch.html HTTP/1.1" 404 - </code></pre>
35
2008-10-10T00:51:00Z
4,041,691
<p>The dev_appserver is already returning 404 responses for anything that doesn't match the mapping, or does match the mapping but doesn't exist. The 404 response itself has no body, but it's still a 404:</p> <pre><code>$ wget -O - http://127.0.0.1:8080/foo --2010-10-28 10:54:51-- http://127.0.0.1:8080/foo Connecting to 127.0.0.1:8080... connected. HTTP request sent, awaiting response... 404 2010-10-28 10:54:51 ERROR 404: (no description). $ wget -O - http://127.0.0.1:8080/foo/ --2010-10-28 10:54:54-- http://127.0.0.1:8080/foo/ Connecting to 127.0.0.1:8080... connected. HTTP request sent, awaiting response... 404 2010-10-28 10:54:54 ERROR 404: (no description). </code></pre> <p>If you want to return a more user-friendly error page, follow jonmiddleton's advice and specify a custom 404 page.</p>
2
2010-10-28T09:56:02Z
[ "python", "google-app-engine", "http-status-code-404" ]
Google App Engine and 404 error
189,751
<p>I've setup a static website on GAE using hints found elsewhere, but can't figure out how to return a 404 error. My app.yaml file looks like</p> <pre><code>- url: (.*)/ static_files: static\1/index.html upload: static/index.html - url: / static_dir: static </code></pre> <p>with all the static html/jpg files stored under the static directory. The above works for files that exist, but returns a null length file if they don't. The answer is probably to write a python script to return a 404 error, but how do you set things up to serve the static files that exist but run the script for files that don't?</p> <p>Here is the log from fetching a non-existent file (nosuch.html) on the development application server:</p> <pre><code>ERROR 2008-11-25 20:08:34,084 dev_appserver.py] Error encountered reading file "/usr/home/ctuffli/www/tufflinet/static/nosuch.html": [Errno 2] No such file or directory: '/usr/home/ctuffli/www/tufflinet/static/nosuch.html' INFO 2008-11-25 20:08:34,088 dev_appserver.py] "GET /nosuch.html HTTP/1.1" 404 - </code></pre>
35
2008-10-10T00:51:00Z
5,160,778
<p>I can't comment on jonmiddleton's answer, but the custom error responses is for App engine specific errors by the look of it. I don't see a way to specify a custom 404 page.</p> <p>Django let's you <a href="http://docs.djangoproject.com/en/dev/topics/http/urls/#handler404" rel="nofollow">specify</a> one though.</p>
0
2011-03-01T21:47:10Z
[ "python", "google-app-engine", "http-status-code-404" ]
Google App Engine and 404 error
189,751
<p>I've setup a static website on GAE using hints found elsewhere, but can't figure out how to return a 404 error. My app.yaml file looks like</p> <pre><code>- url: (.*)/ static_files: static\1/index.html upload: static/index.html - url: / static_dir: static </code></pre> <p>with all the static html/jpg files stored under the static directory. The above works for files that exist, but returns a null length file if they don't. The answer is probably to write a python script to return a 404 error, but how do you set things up to serve the static files that exist but run the script for files that don't?</p> <p>Here is the log from fetching a non-existent file (nosuch.html) on the development application server:</p> <pre><code>ERROR 2008-11-25 20:08:34,084 dev_appserver.py] Error encountered reading file "/usr/home/ctuffli/www/tufflinet/static/nosuch.html": [Errno 2] No such file or directory: '/usr/home/ctuffli/www/tufflinet/static/nosuch.html' INFO 2008-11-25 20:08:34,088 dev_appserver.py] "GET /nosuch.html HTTP/1.1" 404 - </code></pre>
35
2008-10-10T00:51:00Z
10,861,989
<p>You can create a function to handle your errors for any of the status codes. You're case being 404, define a function like this: </p> <pre><code>def Handle404(request, response, exception): response.out.write("Your error message") response.set_status(404)` </code></pre> <p>You can pass anything - HTML / plain-text / templates in the <code>response.out.write</code> function. Now, add the following declaration after your <code>app</code> declaration.</p> <p><code>app.error_handlers[404] = Handle404</code></p> <p>This worked for me.</p>
4
2012-06-02T11:37:26Z
[ "python", "google-app-engine", "http-status-code-404" ]
Google App Engine and 404 error
189,751
<p>I've setup a static website on GAE using hints found elsewhere, but can't figure out how to return a 404 error. My app.yaml file looks like</p> <pre><code>- url: (.*)/ static_files: static\1/index.html upload: static/index.html - url: / static_dir: static </code></pre> <p>with all the static html/jpg files stored under the static directory. The above works for files that exist, but returns a null length file if they don't. The answer is probably to write a python script to return a 404 error, but how do you set things up to serve the static files that exist but run the script for files that don't?</p> <p>Here is the log from fetching a non-existent file (nosuch.html) on the development application server:</p> <pre><code>ERROR 2008-11-25 20:08:34,084 dev_appserver.py] Error encountered reading file "/usr/home/ctuffli/www/tufflinet/static/nosuch.html": [Errno 2] No such file or directory: '/usr/home/ctuffli/www/tufflinet/static/nosuch.html' INFO 2008-11-25 20:08:34,088 dev_appserver.py] "GET /nosuch.html HTTP/1.1" 404 - </code></pre>
35
2008-10-10T00:51:00Z
17,082,291
<p>My approach is to handle both 404 and permanent redirects in a catch all handler that I put as the last one. This is usefull when I redesign and app and rename/substitute urls:</p> <pre><code>app = webapp2.WSGIApplication([ ... ... ('/.*', ErrorsHandler) ], debug=True) class ErrorsHandler(webapp2.RequestHandler): def get(self): p = self.request.path_qs if p in ['/index.html', 'resources-that-I-removed']: return self.redirect('/and-substituted-with-this', permanent=True) else: self.error(404) template = jinja_environment.get_template('404.html') context = { 'page_title': '404', } self.response.out.write(template.render(context)) </code></pre>
0
2013-06-13T08:13:53Z
[ "python", "google-app-engine", "http-status-code-404" ]
Google App Engine and 404 error
189,751
<p>I've setup a static website on GAE using hints found elsewhere, but can't figure out how to return a 404 error. My app.yaml file looks like</p> <pre><code>- url: (.*)/ static_files: static\1/index.html upload: static/index.html - url: / static_dir: static </code></pre> <p>with all the static html/jpg files stored under the static directory. The above works for files that exist, but returns a null length file if they don't. The answer is probably to write a python script to return a 404 error, but how do you set things up to serve the static files that exist but run the script for files that don't?</p> <p>Here is the log from fetching a non-existent file (nosuch.html) on the development application server:</p> <pre><code>ERROR 2008-11-25 20:08:34,084 dev_appserver.py] Error encountered reading file "/usr/home/ctuffli/www/tufflinet/static/nosuch.html": [Errno 2] No such file or directory: '/usr/home/ctuffli/www/tufflinet/static/nosuch.html' INFO 2008-11-25 20:08:34,088 dev_appserver.py] "GET /nosuch.html HTTP/1.1" 404 - </code></pre>
35
2008-10-10T00:51:00Z
22,150,908
<p><code>webapp2</code> provides the <code>error_handlers</code> dictionary that you can use to serve custom error pages. Example below:</p> <pre><code>def handle_404(request, response, exception): logging.warn(str(exception)) response.set_status(404) h = YourAppBaseHandler(request, response) h.render_template('notfound') def handle_500(request, response, exception): logging.error(str(exception)) response.set_status(500) h = YourAppBaseHandler(request, response) h.render_template('servererror') app = webapp2.WSGIApplication([ webapp2.Route('/', MainHandler, name='home') ], debug=True) app.error_handlers[404] = handle_404 app.error_handlers[500] = handle_500 </code></pre> <p>More details are available on <code>webapp2</code>'s documentation pages: <a href="http://webapp-improved.appspot.com/guide/app.html#error-handlers" rel="nofollow">http://webapp-improved.appspot.com/guide/app.html#error-handlers</a></p>
1
2014-03-03T15:38:51Z
[ "python", "google-app-engine", "http-status-code-404" ]
Google App Engine and 404 error
189,751
<p>I've setup a static website on GAE using hints found elsewhere, but can't figure out how to return a 404 error. My app.yaml file looks like</p> <pre><code>- url: (.*)/ static_files: static\1/index.html upload: static/index.html - url: / static_dir: static </code></pre> <p>with all the static html/jpg files stored under the static directory. The above works for files that exist, but returns a null length file if they don't. The answer is probably to write a python script to return a 404 error, but how do you set things up to serve the static files that exist but run the script for files that don't?</p> <p>Here is the log from fetching a non-existent file (nosuch.html) on the development application server:</p> <pre><code>ERROR 2008-11-25 20:08:34,084 dev_appserver.py] Error encountered reading file "/usr/home/ctuffli/www/tufflinet/static/nosuch.html": [Errno 2] No such file or directory: '/usr/home/ctuffli/www/tufflinet/static/nosuch.html' INFO 2008-11-25 20:08:34,088 dev_appserver.py] "GET /nosuch.html HTTP/1.1" 404 - </code></pre>
35
2008-10-10T00:51:00Z
34,583,480
<p>I have reviewed all the above given answers and used the following at the end as the most universal 404 solution:</p> <p>Add this link at the end of <code>app.yaml</code></p> <pre><code>- url: /(.*) script: 404.app </code></pre> <p>and create <code>404.py</code> with the following content</p> <pre><code>import webapp2 from google.appengine.ext.webapp import template class NotFound(webapp2.RequestHandler): def get(self): self.error(404) self.response.out.write(template.render('404.html', {})) app = webapp2.WSGIApplication([ ('/.*', NotFound) ], debug=True) </code></pre> <p>This will display contents of <code>404.html</code> file with 404 error code.</p> <p>The advantage of this solution is simplicity, correctness of bahaviour and flexibility, as it allows to use a static <code>404.html</code> file as error page content.</p> <p>I also want to warn against some of the solutions suggested above. </p> <ul> <li><code>Custom Error Responses</code> don not work with 404 error</li> <li>Also don't use static files, as they would return 200 instead of 404 error. This can cause a lot of headache ahead.</li> </ul>
1
2016-01-04T01:06:44Z
[ "python", "google-app-engine", "http-status-code-404" ]
What property returns the regular expression used when re.compile was called?
189,861
<pre><code>def foo (): x = re.compile('^abc') foo2(x) def foo2(x): # How do I get x to return '^abc'? logging.info('x is ' + x.???) </code></pre>
1
2008-10-10T01:55:27Z
189,870
<p><a href="http://www.python.org/doc/2.5.2/lib/re-objects.html" rel="nofollow">pattern</a></p>
4
2008-10-10T02:03:04Z
[ "python", "regex" ]
How can I quantify difference between two images?
189,943
<p>Here's what I would like to do:</p> <p>I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much <em>looks</em> the same, I don't want to store the latest snapshot.</p> <p>I imagine there's some way of quantifying the difference, and I would have to empirically determine a threshold. </p> <p>I'm looking for simplicity rather than perfection. I'm using python.</p>
88
2008-10-10T02:39:33Z
189,960
<p><strong>A simple solution:</strong></p> <p>Encode the image as a <strong>jpeg</strong> and look for a substantial change in <strong>filesize</strong>.</p> <p>I've implemented something similar with video thumbnails, and had a lot of success and scalability.</p>
41
2008-10-10T02:46:02Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
How can I quantify difference between two images?
189,943
<p>Here's what I would like to do:</p> <p>I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much <em>looks</em> the same, I don't want to store the latest snapshot.</p> <p>I imagine there's some way of quantifying the difference, and I would have to empirically determine a threshold. </p> <p>I'm looking for simplicity rather than perfection. I'm using python.</p>
88
2008-10-10T02:39:33Z
189,967
<p>I think you could simply compute the euclidean distance (i.e. sqrt(sum of squares of differences, pixel by pixel)) between the luminance of the two images, and consider them equal if this falls under some empirical threshold. And you would better do it wrapping a C function.</p>
0
2008-10-10T02:48:15Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
How can I quantify difference between two images?
189,943
<p>Here's what I would like to do:</p> <p>I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much <em>looks</em> the same, I don't want to store the latest snapshot.</p> <p>I imagine there's some way of quantifying the difference, and I would have to empirically determine a threshold. </p> <p>I'm looking for simplicity rather than perfection. I'm using python.</p>
88
2008-10-10T02:39:33Z
189,968
<p><a href="http://www.google.ca/search?hl=en&amp;safe=off&amp;client=firefox-a&amp;rls=org.mozilla:en-US:official&amp;hs=HD8&amp;pwst=1&amp;sa=X&amp;oi=spell&amp;resnum=0&amp;ct=result&amp;cd=1&amp;q=earth+mover%27s+distance+image&amp;spell=1" rel="nofollow">Earth movers distance</a> might be exactly what you need. It might be <em>abit</em> heavy to implement in real time though.</p>
1
2008-10-10T02:48:35Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
How can I quantify difference between two images?
189,943
<p>Here's what I would like to do:</p> <p>I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much <em>looks</em> the same, I don't want to store the latest snapshot.</p> <p>I imagine there's some way of quantifying the difference, and I would have to empirically determine a threshold. </p> <p>I'm looking for simplicity rather than perfection. I'm using python.</p>
88
2008-10-10T02:39:33Z
189,977
<p>What about calculating the <a href="http://en.wikipedia.org/wiki/Manhattan_distance" rel="nofollow">Manhattan Distance</a> of the two images. That gives you n*n values. Then you could do something like an row average to reduce to n values and a function over that to get one single value.</p>
1
2008-10-10T02:53:30Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
How can I quantify difference between two images?
189,943
<p>Here's what I would like to do:</p> <p>I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much <em>looks</em> the same, I don't want to store the latest snapshot.</p> <p>I imagine there's some way of quantifying the difference, and I would have to empirically determine a threshold. </p> <p>I'm looking for simplicity rather than perfection. I'm using python.</p>
88
2008-10-10T02:39:33Z
190,000
<p>Have you seen the <a href="http://stackoverflow.com/questions/75891/algorithm-for-finding-similar-images">Algorithm for finding similar images</a> question? Check it out to see suggestions.</p> <p>I would suggest a wavelet transformation of your frames (I've written a C extension for that using Haar transformation); then, comparing the indexes of the largest (proportionally) wavelet factors between the two pictures, you should get a numerical similarity approximation.</p>
1
2008-10-10T03:13:42Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
How can I quantify difference between two images?
189,943
<p>Here's what I would like to do:</p> <p>I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much <em>looks</em> the same, I don't want to store the latest snapshot.</p> <p>I imagine there's some way of quantifying the difference, and I would have to empirically determine a threshold. </p> <p>I'm looking for simplicity rather than perfection. I'm using python.</p>
88
2008-10-10T02:39:33Z
190,004
<p>I was reading about this on Processing.org recently and found it stashed in my favorites. Maybe it helps you...</p> <p><a href="http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Video;action=display;num=1159141301" rel="nofollow">http://processing.org/discourse/yabb_beta/YaBB.cgi?board=Video;action=display;num=1159141301</a></p>
1
2008-10-10T03:19:03Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
How can I quantify difference between two images?
189,943
<p>Here's what I would like to do:</p> <p>I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much <em>looks</em> the same, I don't want to store the latest snapshot.</p> <p>I imagine there's some way of quantifying the difference, and I would have to empirically determine a threshold. </p> <p>I'm looking for simplicity rather than perfection. I'm using python.</p>
88
2008-10-10T02:39:33Z
190,036
<p>A trivial thing to try:</p> <p>Resample both images to small thumbnails (e.g. 64 x 64) and compare the thumbnails pixel-by-pixel with a certain threshold. If the original images are almost the same, the resampled thumbnails will be very similar or even exactly the same. This method takes care of noise that can occur especially in low-light scenes. It may even be better if you go grayscale.</p>
12
2008-10-10T03:37:57Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
How can I quantify difference between two images?
189,943
<p>Here's what I would like to do:</p> <p>I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much <em>looks</em> the same, I don't want to store the latest snapshot.</p> <p>I imagine there's some way of quantifying the difference, and I would have to empirically determine a threshold. </p> <p>I'm looking for simplicity rather than perfection. I'm using python.</p>
88
2008-10-10T02:39:33Z
190,061
<p>Two popular and relatively simple methods are: (a) the Euclidean distance already suggested, or (b) normalized cross-correlation. Normalized cross-correlation tends to be noticeably more robust to lighting changes than simple cross-correlation. Wikipedia gives a formula for the <a href="http://en.wikipedia.org/wiki/Cross-correlation#Normalized_cross-correlation">normalized cross-correlation</a>. More sophisticated methods exist too, but they require quite a bit more work.</p> <p>Using numpy-like syntax,</p> <pre> dist_euclidean = sqrt(sum((i1 - i2)^2)) / i1.size dist_manhattan = sum(abs(i1 - i2)) / i1.size dist_ncc = sum( (i1 - mean(i1)) * (i2 - mean(i2)) ) / ( (i1.size - 1) * stdev(i1) * stdev(i2) ) </pre> <p>assuming that <code>i1</code> and <code>i2</code> are 2D grayscale image arrays. </p>
14
2008-10-10T03:47:44Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
How can I quantify difference between two images?
189,943
<p>Here's what I would like to do:</p> <p>I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much <em>looks</em> the same, I don't want to store the latest snapshot.</p> <p>I imagine there's some way of quantifying the difference, and I would have to empirically determine a threshold. </p> <p>I'm looking for simplicity rather than perfection. I'm using python.</p>
88
2008-10-10T02:39:33Z
190,078
<p>Most of the answers given won't deal with lighting levels.</p> <p>I would first normalize the image to a standard light level before doing the comparison.</p>
5
2008-10-10T03:55:20Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
How can I quantify difference between two images?
189,943
<p>Here's what I would like to do:</p> <p>I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much <em>looks</em> the same, I don't want to store the latest snapshot.</p> <p>I imagine there's some way of quantifying the difference, and I would have to empirically determine a threshold. </p> <p>I'm looking for simplicity rather than perfection. I'm using python.</p>
88
2008-10-10T02:39:33Z
196,882
<p>You can compare two images using functions from <a href="http://www.pythonware.com/products/pil/">PIL</a>. </p> <pre><code>import Image import ImageChops im1 = Image.open("splash.png") im2 = Image.open("splash2.png") diff = ImageChops.difference(im2, im1) </code></pre> <p>The diff object is an image in which every pixel is the result of the subtraction of the color values of that pixel in the second image from the first image. Using the diff image you can do several things. The simplest one is the <code>diff.getbbox()</code> function. It will tell you the minimal rectangle that contains all the changes between your two images.</p> <p>You can probably implement approximations of the other stuff mentioned here using functions from PIL as well.</p>
40
2008-10-13T06:50:17Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
How can I quantify difference between two images?
189,943
<p>Here's what I would like to do:</p> <p>I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much <em>looks</em> the same, I don't want to store the latest snapshot.</p> <p>I imagine there's some way of quantifying the difference, and I would have to empirically determine a threshold. </p> <p>I'm looking for simplicity rather than perfection. I'm using python.</p>
88
2008-10-10T02:39:33Z
3,935,002
<h2>General idea</h2> <p>Option 1: Load both images as arrays (<code>scipy.misc.imread</code>) and calculate an element-wise (pixel-by-pixel) difference. Calculate the norm of the difference.</p> <p>Option 2: Load both images. Calculate some feature vector for each of them (like a histogram). Calculate distance between feature vectors rather than images.</p> <p>However, there are some decisions to make first.</p> <h2>Questions</h2> <p>You should answer these questions first:</p> <ul> <li><p>Are images of the same shape and dimension?</p> <p>If not, you may need to resize or crop them. PIL library will help to do it in Python.</p> <p>If they are taken with the same settings and the same device, they are probably the same.</p></li> <li><p>Are images well-aligned?</p> <p>If not, you may want to run cross-correlation first, to find the best alignment first. SciPy has functions to do it.</p> <p>If the camera and the scene are still, the images are likely to be well-aligned.</p></li> <li><p>Is exposure of the images always the same? (Is lightness/contrast the same?)</p> <p>If not, you may want <a href="http://en.wikipedia.org/wiki/Normalization_(image_processing)">to normalize</a> images.</p> <p>But be careful, in some situations this may do more wrong than good. For example, a single bright pixel on a dark background will make the normalized image very different.</p></li> <li><p>Is color information important?</p> <p>If you want to notice color changes, you will have a vector of color values per point, rather than a scalar value as in gray-scale image. You need more attention when writing such code.</p></li> <li><p>Are there distinct edges in the image? Are they likely to move?</p> <p>If yes, you can apply edge detection algorithm first (e.g. calculate gradient with Sobel or Prewitt transform, apply some threshold), then compare edges on the first image to edges on the second.</p></li> <li><p>Is there noise in the image?</p> <p>All sensors pollute the image with some amount of noise. Low-cost sensors have more noise. You may wish to apply some noise reduction before you compare images. Blur is the most simple (but not the best) approach here.</p></li> <li><p>What kind of changes do you want to notice?</p> <p>This may affect the choice of norm to use for the difference between images.</p> <p>Consider using Manhattan norm (the sum of the absolute values) or zero norm (the number of elements not equal to zero) to measure how much the image has changed. The former will tell you how much the image is off, the latter will tell only how many pixels differ.</p></li> </ul> <h2>Example</h2> <p>I assume your images are well-aligned, the same size and shape, possibly with different exposure. For simplicity, I convert them to grayscale even if they are color (RGB) images.</p> <p>You will need these imports:</p> <pre><code>import sys from scipy.misc import imread from scipy.linalg import norm from scipy import sum, average </code></pre> <p>Main function, read two images, convert to grayscale, compare and print results:</p> <pre><code>def main(): file1, file2 = sys.argv[1:1+2] # read images as 2D arrays (convert to grayscale for simplicity) img1 = to_grayscale(imread(file1).astype(float)) img2 = to_grayscale(imread(file2).astype(float)) # compare n_m, n_0 = compare_images(img1, img2) print "Manhattan norm:", n_m, "/ per pixel:", n_m/img1.size print "Zero norm:", n_0, "/ per pixel:", n_0*1.0/img1.size </code></pre> <p>How to compare. <code>img1</code> and <code>img2</code> are 2D SciPy arrays here:</p> <pre><code>def compare_images(img1, img2): # normalize to compensate for exposure difference, this may be unnecessary # consider disabling it img1 = normalize(img1) img2 = normalize(img2) # calculate the difference and its norms diff = img1 - img2 # elementwise for scipy arrays m_norm = sum(abs(diff)) # Manhattan norm z_norm = norm(diff.ravel(), 0) # Zero norm return (m_norm, z_norm) </code></pre> <p>If the file is a color image, <code>imread</code> returns a 3D array, average RGB channels (the last array axis) to obtain intensity. No need to do it for grayscale images (e.g. <code>.pgm</code>):</p> <pre><code>def to_grayscale(arr): "If arr is a color image (3D array), convert it to grayscale (2D array)." if len(arr.shape) == 3: return average(arr, -1) # average over the last axis (color channels) else: return arr </code></pre> <p>Normalization is trivial, you may choose to normalize to [0,1] instead of [0,255]. <code>arr</code> is a SciPy array here, so all operations are element-wise:</p> <pre><code>def normalize(arr): rng = arr.max()-arr.min() amin = arr.min() return (arr-amin)*255/rng </code></pre> <p>Run the <code>main</code> function:</p> <pre><code>if __name__ == "__main__": main() </code></pre> <p>Now you can put this all in a script and run against two images. If we compare image to itself, there is no difference:</p> <pre><code>$ python compare.py one.jpg one.jpg Manhattan norm: 0.0 / per pixel: 0.0 Zero norm: 0 / per pixel: 0.0 </code></pre> <p>If we blur the image and compare to the original, there is some difference:</p> <pre><code>$ python compare.py one.jpg one-blurred.jpg Manhattan norm: 92605183.67 / per pixel: 13.4210411116 Zero norm: 6900000 / per pixel: 1.0 </code></pre> <p>P.S. Entire <a href="http://gist.github.com/626356">compare.py</a> script.</p> <h2>Update: relevant techniques</h2> <p>As the question is about a video sequence, where frames are likely to be almost the same, and you look for something unusual, I'd like to mention some alternative approaches which may be relevant:</p> <ul> <li>background subtraction and segmentation (to detect foreground objects)</li> <li>sparse optical flow (to detect motion)</li> <li>comparing histograms or some other statistics instead of images</li> </ul> <p>I strongly recommend taking a look at “Learning OpenCV” book, Chapters 9 (Image parts and segmentation) and 10 (Tracking and motion). The former teaches to use Background subtraction method, the latter gives some info on optical flow methods. All methods are implemented in OpenCV library. If you use Python, I suggest to use OpenCV ≥ 2.3, and its <code>cv2</code> Python module.</p> <p>The most simple version of the background subtraction:</p> <ul> <li>learn the average value μ and standard deviation σ for every pixel of the background</li> <li>compare current pixel values to the range of (μ-2σ,μ+2σ) or (μ-σ,μ+σ)</li> </ul> <p>More advanced versions make take into account time series for every pixel and handle non-static scenes (like moving trees or grass).</p> <p>The idea of optical flow is to take two or more frames, and assign velocity vector to every pixel (dense optical flow) or to some of them (sparse optical flow). To estimate sparse optical flow, you may use <a href="http://en.wikipedia.org/wiki/Lucas%E2%80%93Kanade_method">Lucas-Kanade method</a> (it is also implemented in OpenCV). Obviously, if there is a lot of flow (high average over max values of the velocity field), then something is moving in the frame, and subsequent images are more different.</p> <p>Comparing histograms may help to detect sudden changes between consecutive frames. This approach was used in <a href="http://www.sciencedirect.com/science/article/pii/S0967066110000808">Courbon et al, 2010</a>:</p> <blockquote> <p><em>Similarity of consecutive frames.</em> The distance between two consecutive frames is measured. If it is too high, it means that the second frame is corrupted and thus the image is eliminated. The <a href="https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence">Kullback–Leibler distance</a>, or mutual entropy, on the histograms of the two frames:</p> <p><img src="http://i.imgur.com/hdeh8ni.gif" alt="$$ d(p,q) = \sum_i p(i) \log (p(i)/q(i)) $$"></p> <p>where <em>p</em> and <em>q</em> are the histograms of the frames is used. The threshold is fixed on 0.2.</p> </blockquote>
143
2010-10-14T15:43:55Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
How can I quantify difference between two images?
189,943
<p>Here's what I would like to do:</p> <p>I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much <em>looks</em> the same, I don't want to store the latest snapshot.</p> <p>I imagine there's some way of quantifying the difference, and I would have to empirically determine a threshold. </p> <p>I'm looking for simplicity rather than perfection. I'm using python.</p>
88
2008-10-10T02:39:33Z
3,935,187
<p>I am addressing specifically the question of how to compute if they are "different enough". I assume you can figure out how to subtract the pixels one by one.</p> <p>First, I would take a bunch of images with <em>nothing</em> changing, and find out the maximum amount that any pixel changes just because of variations in the capture, noise in the imaging system, JPEG compression artifacts, and moment-to-moment changes in lighting. Perhaps you'll find that 1 or 2 bit differences are to be expected even when nothing moves.</p> <p>Then for the "real" test, you want a criterion like this:</p> <ul> <li>same if up to P pixels differ by no more than E.</li> </ul> <p>So, perhaps, if E = 0.02, P = 1000, that would mean (approximately) that it would be "different" if any single pixel changes by more than ~5 units (assuming 8-bit images), or if more than 1000 pixels had any errors at all.</p> <p>This is intended mainly as a good "triage" technique to quickly identify images that are close enough to not need further examination. The images that "fail" may then more to a more elaborate/expensive technique that wouldn't have false positives if the camera shook bit, for example, or was more robust to lighting changes.</p> <p>I run an open source project, <a href="http://www.openimageio.org">OpenImageIO</a>, that contains a utility called "idiff" that compares differences with thresholds like this (even more elaborate, actually). Even if you don't want to use this software, you may want to look at the source to see how we did it. It's used commercially quite a bit and this thresholding technique was developed so that we could have a test suite for rendering and image processing software, with "reference images" that might have small differences from platform-to-platform or as we made minor tweaks to tha algorithms, so we wanted a "match within tolerance" operation.</p>
6
2010-10-14T16:04:18Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
How can I quantify difference between two images?
189,943
<p>Here's what I would like to do:</p> <p>I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much <em>looks</em> the same, I don't want to store the latest snapshot.</p> <p>I imagine there's some way of quantifying the difference, and I would have to empirically determine a threshold. </p> <p>I'm looking for simplicity rather than perfection. I'm using python.</p>
88
2008-10-10T02:39:33Z
5,053,648
<p>I have been having a lot of luck with jpg images taken with the same camera on a tripod by (1) simplifying greatly (like going from 3000 pixels wide to 100 pixels wide or even fewer) (2) flattening each jpg array into a single vector (3) pairwise correlating sequential images with a simple correlate algorithm to get correlation coefficient (4) squaring correlation coefficient to get r-square (i.e fraction of variability in one image explained by variation in the next) (5) generally in my application if r-square &lt; 0.9, I say the two images are different and something happened in between.</p> <p>This is robust and fast in my implementation (Mathematica 7)</p> <p>It's worth playing around with the part of the image you are interested in and focussing on that by cropping all images to that little area, otherwise a distant-from-the-camera but important change will be missed. </p> <p>I don't know how to use Python, but am sure it does correlations, too, no?</p>
1
2011-02-19T21:28:00Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
How can I quantify difference between two images?
189,943
<p>Here's what I would like to do:</p> <p>I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much <em>looks</em> the same, I don't want to store the latest snapshot.</p> <p>I imagine there's some way of quantifying the difference, and I would have to empirically determine a threshold. </p> <p>I'm looking for simplicity rather than perfection. I'm using python.</p>
88
2008-10-10T02:39:33Z
5,100,965
<p>you can compute the histogram of both the images and then calculate the <a href="http://en.wikipedia.org/wiki/Bhattacharyya_distance#Bhattacharyya_coefficient" rel="nofollow">Bhattacharyya Coefficient</a>, this is a very fast algorithm and I have used it to detect shot changes in a cricket video (in C using openCV)</p>
1
2011-02-24T06:00:48Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
How can I quantify difference between two images?
189,943
<p>Here's what I would like to do:</p> <p>I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much <em>looks</em> the same, I don't want to store the latest snapshot.</p> <p>I imagine there's some way of quantifying the difference, and I would have to empirically determine a threshold. </p> <p>I'm looking for simplicity rather than perfection. I'm using python.</p>
88
2008-10-10T02:39:33Z
8,886,316
<p>Check out how Haar Wavelets are implemented by <a href="http://server.imgseek.net/" rel="nofollow">isk-daemon</a>. You could use it's imgdb C++ code to calculate the difference between images on-the-fly:</p> <blockquote> <p>isk-daemon is an open source database server capable of adding content-based (visual) image searching to any image related website or software.</p> <p>This technology allows users of any image-related website or software to sketch on a widget which image they want to find and have the website reply to them the most similar images or simply request for more similar photos at each image detail page.</p> </blockquote>
1
2012-01-16T21:11:08Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
Daemon Threads Explanation
190,010
<p>In the <a href="https://docs.python.org/2/library/threading.html#thread-objects">Python documentation</a> it says:</p> <blockquote> <p>A thread can be flagged as a "daemon thread". The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread.</p> </blockquote> <p>Does anyone have a clearer explanation of what that means or a practical example showing where you would want to set threads as <code>daemonic</code>?</p> <hr> <p>To clarify for me:</p> <p>so the only time you <strong>wouldn't</strong> set threads as daemonic is if you wanted them to continue running after the main thread exits?</p>
104
2008-10-10T03:24:07Z
190,017
<p>Some threads do background tasks, like sending keepalive packets, or performing periodic garbage collection, or whatever. These are only useful when the main program is running, and it's okay to kill them off once the other, non-daemon, threads have exited.</p> <p>Without daemon threads, you'd have to keep track of them, and tell them to exit, before your program can completely quit. By setting them as daemon threads, you can let them run and forget about them, and when your program quits, any daemon threads are killed automatically.</p>
220
2008-10-10T03:27:36Z
[ "python", "multithreading" ]
Daemon Threads Explanation
190,010
<p>In the <a href="https://docs.python.org/2/library/threading.html#thread-objects">Python documentation</a> it says:</p> <blockquote> <p>A thread can be flagged as a "daemon thread". The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread.</p> </blockquote> <p>Does anyone have a clearer explanation of what that means or a practical example showing where you would want to set threads as <code>daemonic</code>?</p> <hr> <p>To clarify for me:</p> <p>so the only time you <strong>wouldn't</strong> set threads as daemonic is if you wanted them to continue running after the main thread exits?</p>
104
2008-10-10T03:24:07Z
190,033
<p>Let's say you're making some kind of dashboard widget. As part of this, you want it to display the unread message count in your email box. So you make a little thread that will:</p> <ol> <li>Connect to the mail server and ask how many unread messages you have.</li> <li>Signal the GUI with the updated count.</li> <li>Sleep for a little while.</li> </ol> <p>When your widget starts up, it would create this thread, designate it a daemon, and start it. Because it's a daemon, you don't have to think about it; when your widget exits, the thread will stop automatically.</p>
14
2008-10-10T03:36:16Z
[ "python", "multithreading" ]
Daemon Threads Explanation
190,010
<p>In the <a href="https://docs.python.org/2/library/threading.html#thread-objects">Python documentation</a> it says:</p> <blockquote> <p>A thread can be flagged as a "daemon thread". The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread.</p> </blockquote> <p>Does anyone have a clearer explanation of what that means or a practical example showing where you would want to set threads as <code>daemonic</code>?</p> <hr> <p>To clarify for me:</p> <p>so the only time you <strong>wouldn't</strong> set threads as daemonic is if you wanted them to continue running after the main thread exits?</p>
104
2008-10-10T03:24:07Z
190,131
<p>A simpler way to think about it, perhaps: when main returns, your process will not exit if there are non-daemon threads still running.</p> <p>A bit of advice: Clean shutdown is easy to get wrong when threads and synchronization are involved - if you can avoid it, do so. Use daemon threads whenever possible.</p>
8
2008-10-10T04:34:28Z
[ "python", "multithreading" ]
Daemon Threads Explanation
190,010
<p>In the <a href="https://docs.python.org/2/library/threading.html#thread-objects">Python documentation</a> it says:</p> <blockquote> <p>A thread can be flagged as a "daemon thread". The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread.</p> </blockquote> <p>Does anyone have a clearer explanation of what that means or a practical example showing where you would want to set threads as <code>daemonic</code>?</p> <hr> <p>To clarify for me:</p> <p>so the only time you <strong>wouldn't</strong> set threads as daemonic is if you wanted them to continue running after the main thread exits?</p>
104
2008-10-10T03:24:07Z
583,996
<p>Other posters gave some examples for situations in which you'd use daemon threads. My recommendation, however, is never to use them.</p> <p>It's not because they're not useful, but because there are some bad side effects you can experience if you use them. Daemon threads can still execute after the Python runtime starts tearing down things in the main thread, causing some pretty bizarre exceptions.</p> <p>More info here:</p> <p><a href="http://joeshaw.org/2009/02/24/605">http://joeshaw.org/2009/02/24/605</a></p> <p><a href="http://mail.python.org/pipermail/python-list/2005-February/307042.html">http://mail.python.org/pipermail/python-list/2005-February/307042.html</a></p> <p>Strictly speaking you never need them, it just makes implementation easier in some cases.</p>
7
2009-02-24T22:55:10Z
[ "python", "multithreading" ]