title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
'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...
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 modul...
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...
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>dja...
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...
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 ...
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...
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 ...
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...
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. ...
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...
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", "N...
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 ...
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", "N...
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", "N...
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'...
-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", "N...
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': ...
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", "N...
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 "...
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 "...
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#...
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 "...
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", "auth...
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 "...
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?'] </cod...
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 "...
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...
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 "...
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 configura...
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,...
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 ...
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,...
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])...
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="nofol...
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="nofol...
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,...
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 t...
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 ...
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 ...
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> ...
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") readl...
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> ...
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 = [ 'here@blubb.com', 'foo@bar.com', 'whatever@wherever.org', ] class MyCmd(cmd.Cmd): def do_send(self, line): pass def complete_se...
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> ...
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="h...
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> ...
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 = ['angela@domain.com', 'michael@domai...
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> ...
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> ...
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', ...
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 "nosetest...
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]...
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 ...
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 thi...
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><c...
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><c...
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 rarel...
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><c...
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><c...
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...
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><c...
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 (p...
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><c...
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 structur...
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><c...
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 c...
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><c...
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> ins...
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><c...
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 ...
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><c...
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,...
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 respons...
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)...
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 respons...
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.ph...
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 stu...
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 ...
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 stu...
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 ca...
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 stu...
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 stu...
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 e...
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 stu...
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 ...
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 stu...
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...
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 stu...
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(co...
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 stu...
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 i...
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 stu...
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 t...
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 stu...
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>br...
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 stu...
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 # &l...
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 stu...
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 th...
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 stu...
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>...
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 stu...
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 wi...
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 stu...
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 ...
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 stu...
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...
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 stu...
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: ...
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 stu...
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<...
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 stu...
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 curren...
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 ...
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 ...
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 ...
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 nee...
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 ...
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...
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 ...
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...
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 ...
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 ...
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 ...
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 ...
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.Requ...
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 ...
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_...
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 ...
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>impor...
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 quantif...
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 quantif...
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 quantif...
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...
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 quantif...
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 quantif...
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)...
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 quantif...
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;...
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 quantif...
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 occu...
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 quantif...
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/wik...
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 quantif...
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 quantif...
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 eve...
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 quantif...
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 betwe...
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 quantif...
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 variatio...
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 quantif...
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...
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 quantif...
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)<...
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 quantif...
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) imag...
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 inh...
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...
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 inh...
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> ...
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 inh...
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 inh...
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...
7
2009-02-24T22:55:10Z
[ "python", "multithreading" ]