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
Difference between class foo and class foo(object) in Python
332,255
<p>I know <code>class foo(object)</code> is an old school way of defining a class. But I would like to understand in more detail the difference between these two.</p>
28
2008-12-01T21:17:40Z
332,290
<p><code>class foo(object):</code> is the 'new' way of declaring classes.</p> <p>This change was made in python 2.2, see <a href="https://docs.python.org/whatsnew/2.2.html" rel="nofollow">this PEP for an explanation</a> of the differences. </p>
6
2008-12-01T21:24:44Z
[ "python" ]
Difference between class foo and class foo(object) in Python
332,255
<p>I know <code>class foo(object)</code> is an old school way of defining a class. But I would like to understand in more detail the difference between these two.</p>
28
2008-12-01T21:17:40Z
332,575
<p>Subclassing <code>object</code> yields a new-style class. Two well known advantages of new-style classes are:</p> <ul> <li>Metaclasses (like class factories, but works transparently)</li> <li>Properties (getters &amp; setters...)</li> </ul>
4
2008-12-01T23:17:35Z
[ "python" ]
Difference between class foo and class foo(object) in Python
332,255
<p>I know <code>class foo(object)</code> is an old school way of defining a class. But I would like to understand in more detail the difference between these two.</p>
28
2008-12-01T21:17:40Z
332,815
<p>Prior to python 2.2 there were essentially two different types of class: Those defined by C extensions and C coded builtins (types) and those defined by python class statements (classes). This led to problems when you wanted to mix python-types and builtin types. The most common reason for this is subclassing. If you wanted to subclass the list type in python code, you were out of luck, and so various workarounds were used instead, such as subclassing the pure python implementation of lists (in the UserList module) instead.</p> <p>This was a fairly ugly, so in 2.2 there was a <a href="http://www.python.org/dev/peps/pep-0252/">move</a> to unify python and builtin types, including the ability to <a href="http://www.python.org/dev/peps/pep-0253/">inherit</a> from them. The result is "new style classes". These do have some incompatible differences to old-style classes however, so for backward compatability the bare class syntax creates an old-style class, while the new behaviour is obtained by inheriting from object. The most visible behaviour differences are:</p> <ul> <li><p>The method resolution order (MRO). There is a difference in behaviour in diamond-shaped inheritance hierarchies (where A inherits from both B and C, which both inherit from a common base class D. Previously, methods were looked up left-to right, depth first (ie A B D C D) However if C overloads a member of D, it won't be used by A (as it finds D's implementation first) This is bad for various styles of programming (eg. using mixin classes). New style classes will treat this situation as A B C D, (look at the <code>__mro__</code> attribute of a class to see the order it will search)</p></li> <li><p>The <code>__new__</code> constructor is added, which allows the class to act as a factory method, rather than return a new instance of the class. Useful for returning particular subclasses, or reusing immutable objects rather than creating new ones without having to change the creation interface.</p></li> <li><p><a href="https://docs.python.org/2/reference/datamodel.html#implementing-descriptors">Descriptors</a>. These are the feature behind such things as properties, classmethods, staticmethods etc. Essentially, they provide a way to control what happens when you access or set a particular attribute on a (new style) class.</p></li> </ul>
34
2008-12-02T01:59:21Z
[ "python" ]
How do you change the size of figures drawn with matplotlib?
332,289
<p>How do you change the size of figure drawn with matplotlib?</p>
518
2008-12-01T21:24:44Z
332,311
<p>The following seems to work:</p> <pre><code>from pylab import rcParams rcParams['figure.figsize'] = 5, 10 </code></pre> <p>This makes the figure's width 5 inches, and its height 10 <b>inches</b>. </p> <p>The Figure class then uses this as the default value for one of its arguments.</p>
153
2008-12-01T21:28:56Z
[ "python", "graph", "matplotlib", "plot", "visualization" ]
How do you change the size of figures drawn with matplotlib?
332,289
<p>How do you change the size of figure drawn with matplotlib?</p>
518
2008-12-01T21:24:44Z
334,462
<p>The first link in Google for <code>'matplotlib figure size'</code> is <a href="http://www.scipy.org/Cookbook/Matplotlib/AdjustingImageSize">AdjustingImageSize</a> (<a href="https://webcache.googleusercontent.com/search?q=cache:5oqjjm8c8UMJ:https://scipy.github.io/old-wiki/pages/Cookbook/Matplotlib/AdjustingImageSize.html+&amp;cd=2&amp;hl=en&amp;ct=clnk&amp;gl=fr">Google cache of the page</a>).</p> <p>Here's a test script from the above page. It creates <code>test[1-3].png</code> files of different sizes of the same image:</p> <pre><code>#!/usr/bin/env python """ This is a small demo file that helps teach how to adjust figure sizes for matplotlib """ import matplotlib print "using MPL version:", matplotlib.__version__ matplotlib.use("WXAgg") # do this before pylab so you don'tget the default back end. import pylab import matplotlib.numerix as N # Generate and plot some simple data: x = N.arange(0, 2*N.pi, 0.1) y = N.sin(x) pylab.plot(x,y) F = pylab.gcf() # Now check everything with the defaults: DPI = F.get_dpi() print "DPI:", DPI DefaultSize = F.get_size_inches() print "Default size in Inches", DefaultSize print "Which should result in a %i x %i Image"%(DPI*DefaultSize[0], DPI*DefaultSize[1]) # the default is 100dpi for savefig: F.savefig("test1.png") # this gives me a 797 x 566 pixel image, which is about 100 DPI # Now make the image twice as big, while keeping the fonts and all the # same size F.set_size_inches( (DefaultSize[0]*2, DefaultSize[1]*2) ) Size = F.get_size_inches() print "Size in Inches", Size F.savefig("test2.png") # this results in a 1595x1132 image # Now make the image twice as big, making all the fonts and lines # bigger too. F.set_size_inches( DefaultSize )# resetthe size Size = F.get_size_inches() print "Size in Inches", Size F.savefig("test3.png", dpi = (200)) # change the dpi # this also results in a 1595x1132 image, but the fonts are larger. </code></pre> <p>Output:</p> <pre><code>using MPL version: 0.98.1 DPI: 80 Default size in Inches [ 8. 6.] Which should result in a 640 x 480 Image Size in Inches [ 16. 12.] Size in Inches [ 16. 12.] </code></pre> <p>Two notes:</p> <ol> <li><p>The module comments and the actual output differ.</p></li> <li><p><a href="http://stackoverflow.com/questions/335896/how-to-complete-this-python-function-to-save-in-the-same-folder#336001">This answer</a> allows easily to combine all three images in one image file to see the difference in sizes.</p></li> </ol>
43
2008-12-02T16:01:32Z
[ "python", "graph", "matplotlib", "plot", "visualization" ]
How do you change the size of figures drawn with matplotlib?
332,289
<p>How do you change the size of figure drawn with matplotlib?</p>
518
2008-12-01T21:24:44Z
638,443
<p><a href="http://matplotlib.sourceforge.net/api/figure_api.html#matplotlib.figure.Figure">figure</a> tells you the call signature:</p> <pre><code>figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k') </code></pre> <p>So <code>figure(figsize=(1,1))</code> creates an inch-by-inch image, which will be 80-by-80 pixels unless you also give a different dpi argument.</p>
380
2009-03-12T12:41:35Z
[ "python", "graph", "matplotlib", "plot", "visualization" ]
How do you change the size of figures drawn with matplotlib?
332,289
<p>How do you change the size of figure drawn with matplotlib?</p>
518
2008-12-01T21:24:44Z
4,306,340
<p>If you've already got the figure created you can quickly do this:</p> <pre><code>fig = matplotlib.pyplot.gcf() fig.set_size_inches(18.5, 10.5) fig.savefig('test2png.png', dpi=100) </code></pre> <p>To propagate the size change to an existing gui window add <code>forward=True</code></p> <pre><code>fig.set_size_inches(18.5, 10.5, forward=True) </code></pre>
328
2010-11-29T17:30:40Z
[ "python", "graph", "matplotlib", "plot", "visualization" ]
How do you change the size of figures drawn with matplotlib?
332,289
<p>How do you change the size of figure drawn with matplotlib?</p>
518
2008-12-01T21:24:44Z
22,399,608
<p>Try commenting out the <code>fig = ...</code> line</p> <pre><code>%matplotlib inline import numpy as np import matplotlib.pyplot as plt N = 50 x = np.random.rand(N) y = np.random.rand(N) area = np.pi * (15 * np.random.rand(N))**2 fig = plt.figure(figsize=(18, 18)) plt.scatter(x, y, s=area, alpha=0.5) plt.show() </code></pre>
6
2014-03-14T08:22:25Z
[ "python", "graph", "matplotlib", "plot", "visualization" ]
How do you change the size of figures drawn with matplotlib?
332,289
<p>How do you change the size of figure drawn with matplotlib?</p>
518
2008-12-01T21:24:44Z
23,903,662
<p>This works well for me:</p> <pre><code>from matplotlib import pyplot as plt F = gcf() Size = F.get_size_inches() F.set_size_inches(Size[0]*2, Size[1]*2, forward=True)#Set forward to True to resize window along with plot in figure. plt.show() #or plt.imshow(z_array) if using an animation, where z_array is a matrix or numpy array </code></pre> <p>This might also help: <a href="http://matplotlib.1069221.n5.nabble.com/Resizing-figure-windows-td11424.html" rel="nofollow">http://matplotlib.1069221.n5.nabble.com/Resizing-figure-windows-td11424.html</a></p>
4
2014-05-28T05:47:34Z
[ "python", "graph", "matplotlib", "plot", "visualization" ]
How do you change the size of figures drawn with matplotlib?
332,289
<p>How do you change the size of figure drawn with matplotlib?</p>
518
2008-12-01T21:24:44Z
24,073,700
<p>Please try a simple code as following:</p> <pre><code>from matplotlib import pyplot as plt plt.figure(figsize=(1,1)) x = [1,2,3] plt.plot(x, x) plt.show() </code></pre> <p>You need to set the figure size before you plot.</p>
62
2014-06-06T03:24:00Z
[ "python", "graph", "matplotlib", "plot", "visualization" ]
How do you change the size of figures drawn with matplotlib?
332,289
<p>How do you change the size of figure drawn with matplotlib?</p>
518
2008-12-01T21:24:44Z
26,601,247
<p>This resizes the figure immediately even after the figure has been drawn (at least using Qt4Agg/TkAgg - but not MacOSX - with matplotlib 1.4.0):</p> <pre><code>matplotlib.pyplot.get_current_fig_manager().resize(width_px, height_px) </code></pre>
0
2014-10-28T05:08:13Z
[ "python", "graph", "matplotlib", "plot", "visualization" ]
How do you change the size of figures drawn with matplotlib?
332,289
<p>How do you change the size of figure drawn with matplotlib?</p>
518
2008-12-01T21:24:44Z
26,650,785
<p>To increase size of your figure N times you need to insert this just before your pl.show():</p> <pre><code>N = 2 params = pl.gcf() plSize = params.get_size_inches() params.set_size_inches( (plSize[0]*N, plSize[1]*N) ) </code></pre> <p>It also works well with ipython notebook.</p>
6
2014-10-30T10:38:37Z
[ "python", "graph", "matplotlib", "plot", "visualization" ]
How do you change the size of figures drawn with matplotlib?
332,289
<p>How do you change the size of figure drawn with matplotlib?</p>
518
2008-12-01T21:24:44Z
38,750,738
<p>Since Matplotlib <a href="https://github.com/matplotlib/matplotlib/issues/1369" rel="nofollow">isn't able</a> to use the metric system natively, if you want to specify the size of your figure in a reasonable unit of length such as centimeters, you can do the following (code from <a href="http://stackoverflow.com/a/22787457/395857">gns-ank</a>):</p> <pre><code>def cm2inch(*tupl): inch = 2.54 if isinstance(tupl[0], tuple): return tuple(i/inch for i in tupl[0]) else: return tuple(i/inch for i in tupl) </code></pre> <p>Then you can use:</p> <pre><code>plt.figure(figsize=cm2inch(21, 29.7)) </code></pre>
2
2016-08-03T18:04:36Z
[ "python", "graph", "matplotlib", "plot", "visualization" ]
How do you change the size of figures drawn with matplotlib?
332,289
<p>How do you change the size of figure drawn with matplotlib?</p>
518
2008-12-01T21:24:44Z
39,770,939
<p>In case you're looking for a way to change the figure size in Pandas, you could do e.g.:</p> <pre><code>df['some_column'].plot(figsize=(10, 5)) </code></pre> <p>where <code>df</code> is a Pandas dataframe. If you want to change the default settings, you could do the following:</p> <pre><code>import pandas as pd # update 'default' stylesheet pd.tools.plotting.mpl_stylesheet['figure.figsize'] = (10.0, 5.0) # start using the 'default' style sheet (not used by default) pd.set_option('display.mpl_style', 'default') </code></pre>
-1
2016-09-29T12:54:32Z
[ "python", "graph", "matplotlib", "plot", "visualization" ]
Integer (representing a sequence of bits) reinterpretation as Character Array in Python
333,097
<p>I've written some C code that I would like to port to python, as I feel python is a better 'concept' language.</p> <p>In my C code, I use memory reinterpretation to achieve my goals, for example:</p> <pre><code>sizeof(int) is 4 byte sizeof(char) is 1 byte char c[4]={0x01,0x30,0x00,0x80}; int* i=(int*)c; *i has the value 0x80003001 </code></pre> <p>similarly if i have:</p> <pre><code>int* j = (int*)malloc(sizeof(int)); char* c = (char*)j; *j = 0x78FF00AA; c is now {0xAA, 0x00, 0xFF, 0x78} </code></pre> <p>I would like to do a similar thing in python, I realise that I can use bit operations to accomplish this:</p> <pre><code>chararray=[] num=1234567890 size=8 while len(chararray) &lt; size: char = chr( (num &amp; 255 ) ) num = num &gt;&gt; 8 chararray.append(char) </code></pre> <p>However I was hoping there would be a faster way of accomplishing this.</p> <p>Does python have anything similar to C's union?</p>
4
2008-12-02T05:03:37Z
333,116
<p>You can use the <a href="http://www.python.org/doc/2.5.2/lib/module-struct.html" rel="nofollow">struct module</a>:</p> <pre><code>import struct # Pack a Python long as if it was a C unsigned integer, little endian bytes = struct.pack("&lt;I", 0x78FF00AA) print [hex(ord(byte)) for byte in bytes] ['0xaa', '0x0', '0xff', '0x78'] </code></pre> <p>Read the documentation page to find about datatypes, and pay attention to endianness.</p>
9
2008-12-02T05:16:21Z
[ "python" ]
getting redirect loop for admin_only decorator
333,487
<p>I've made this decorator, which results in an infinite redirect loop.</p> <p>The problem is this: </p> <pre><code>args[0].redirect(users.create_login_url(args[0].request.path)) </code></pre> <p>It appears to be a perfectly valid URL. So why wouldn't it properly redirect?</p> <pre><code>def admin_only(handler, *args): def redirect_to_login(*args, **kwargs): return args[0].redirect(users.create_login_url(args[0].request.path)) user = users.get_current_user() if user: if authorized(user): return handler(args[0]) else: logging.warning('An unauthorized user has attempted to enter an authorized page') return redirect_to_login else: return redirect_to_login </code></pre>
1
2008-12-02T09:47:08Z
333,599
<p>Are you sure proper status code is being sent, you can use live http headers add-on for firefox to check whether 301 or 303 is being sent or not.</p>
0
2008-12-02T10:43:07Z
[ "python", "google-app-engine", "redirect", "decorator" ]
getting redirect loop for admin_only decorator
333,487
<p>I've made this decorator, which results in an infinite redirect loop.</p> <p>The problem is this: </p> <pre><code>args[0].redirect(users.create_login_url(args[0].request.path)) </code></pre> <p>It appears to be a perfectly valid URL. So why wouldn't it properly redirect?</p> <pre><code>def admin_only(handler, *args): def redirect_to_login(*args, **kwargs): return args[0].redirect(users.create_login_url(args[0].request.path)) user = users.get_current_user() if user: if authorized(user): return handler(args[0]) else: logging.warning('An unauthorized user has attempted to enter an authorized page') return redirect_to_login else: return redirect_to_login </code></pre>
1
2008-12-02T09:47:08Z
333,653
<p>You should use firebug, or live http headers, or somesuch, to see what exactly is happening here. My guess: Your authorized() function is always returning false (even when a user is logged in), so it redirects to the login page, which (if the user is already logged in) immediately redirects the user back to your page, which redirects... you get the idea.</p>
0
2008-12-02T11:10:45Z
[ "python", "google-app-engine", "redirect", "decorator" ]
getting redirect loop for admin_only decorator
333,487
<p>I've made this decorator, which results in an infinite redirect loop.</p> <p>The problem is this: </p> <pre><code>args[0].redirect(users.create_login_url(args[0].request.path)) </code></pre> <p>It appears to be a perfectly valid URL. So why wouldn't it properly redirect?</p> <pre><code>def admin_only(handler, *args): def redirect_to_login(*args, **kwargs): return args[0].redirect(users.create_login_url(args[0].request.path)) user = users.get_current_user() if user: if authorized(user): return handler(args[0]) else: logging.warning('An unauthorized user has attempted to enter an authorized page') return redirect_to_login else: return redirect_to_login </code></pre>
1
2008-12-02T09:47:08Z
333,658
<p>It seems that you aren't defining your decorator properly.</p> <p>A decorator is called only <strong>once</strong> every time you wrap a function with it; from then on the function that the decorator <strong>returned</strong> will be called. It seems that you (mistakenly) believe that the decorator function <strong>itself</strong> will be called every time.</p> <p>Try something like this instead:</p> <pre><code>def redirect_to_login(*args, **kwargs): return args[0].redirect(users.create_login_url(args[0].request.path)) def admin_only(handler): def wrapped_handler(*args, **kwargs): user = users.get_current_user() if user: if authorized(user): return handler(args[0]) else: logging.warning('An unauthorized user has attempted ' 'to enter an authorized page') return redirect_to_login(*args, **kwargs) else: return redirect_to_login(*args, **kwargs) return wrapped_handler </code></pre> <p>Note that in the above code, the decorator just defines a new function and returns it, and this new function itself does the relevant checks.</p>
2
2008-12-02T11:11:45Z
[ "python", "google-app-engine", "redirect", "decorator" ]
getting redirect loop for admin_only decorator
333,487
<p>I've made this decorator, which results in an infinite redirect loop.</p> <p>The problem is this: </p> <pre><code>args[0].redirect(users.create_login_url(args[0].request.path)) </code></pre> <p>It appears to be a perfectly valid URL. So why wouldn't it properly redirect?</p> <pre><code>def admin_only(handler, *args): def redirect_to_login(*args, **kwargs): return args[0].redirect(users.create_login_url(args[0].request.path)) user = users.get_current_user() if user: if authorized(user): return handler(args[0]) else: logging.warning('An unauthorized user has attempted to enter an authorized page') return redirect_to_login else: return redirect_to_login </code></pre>
1
2008-12-02T09:47:08Z
334,975
<p>The problem is actually when I use </p> <pre><code>return args[0].redirect(users.create_logout_url(args[0].request.uri)) </code></pre> <p>This goes to the logout page, which then redirects to the current page. However, my logs show that the current page thinks I'm still logged in, even after the logging out is complete.</p> <p>This is strange, since I haven't modified anything in the app engine users API. </p>
0
2008-12-02T18:37:27Z
[ "python", "google-app-engine", "redirect", "decorator" ]
string.split(text) or text.split() what's the difference?
333,706
<p>There is one thing that I do not understand... </p> <p>Imagine you have a <strong>text</strong> = "hello world" and you want to split it.</p> <p>In some places I see people that want to split the <strong>text</strong> doing:</p> <pre><code>string.split(text) </code></pre> <p>In other places I see people just doing:</p> <pre><code>text.split() </code></pre> <p>What’s the difference? Why you do in one way or in the other way? Can you give me a theorist explanation about that?</p>
9
2008-12-02T11:41:05Z
333,715
<p>The <code>string.split(stringobj)</code> is a feature of the <code>string</code> module, which must be imported separately. Once upon a time, that was the only way to split a string. That's some old code you're looking at.</p> <p>The <code>stringobj.split()</code> is a feature of a string object, <code>stringobj</code>, which is more recent than the <code>string</code> module. But pretty old, nonetheless. That's the current practice.</p>
11
2008-12-02T11:46:16Z
[ "python" ]
string.split(text) or text.split() what's the difference?
333,706
<p>There is one thing that I do not understand... </p> <p>Imagine you have a <strong>text</strong> = "hello world" and you want to split it.</p> <p>In some places I see people that want to split the <strong>text</strong> doing:</p> <pre><code>string.split(text) </code></pre> <p>In other places I see people just doing:</p> <pre><code>text.split() </code></pre> <p>What’s the difference? Why you do in one way or in the other way? Can you give me a theorist explanation about that?</p>
9
2008-12-02T11:41:05Z
333,727
<p>Interestingly, the docstrings for the two are not completely the same in Python 2.5.1:</p> <pre><code>&gt;&gt;&gt; import string &gt;&gt;&gt; help(string.split) Help on function split in module string: split(s, sep=None, maxsplit=-1) split(s [,sep [,maxsplit]]) -&gt; list of strings Return a list of the words in the string s, using sep as the delimiter string. If maxsplit is given, splits at no more than maxsplit places (resulting in at most maxsplit+1 words). If sep is not specified or is None, any whitespace string is a separator. (split and splitfields are synonymous) &gt;&gt;&gt; help("".split) Help on built-in function split: split(...) S.split([sep [,maxsplit]]) -&gt; list of strings Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator. </code></pre> <p>Digging deeper, you'll see that the two forms are completely equivalent, as <a href="http://svn.python.org/view/python/tags/r251/Lib/string.py?rev=54864&amp;view=markup">string.split(s)</a> actually calls <a href="http://svn.python.org/view/python/tags/r251/Objects/unicodeobject.c?rev=54864&amp;view=markup">s.split()</a> (search for the <em>split</em>-functions).</p>
20
2008-12-02T11:49:56Z
[ "python" ]
string.split(text) or text.split() what's the difference?
333,706
<p>There is one thing that I do not understand... </p> <p>Imagine you have a <strong>text</strong> = "hello world" and you want to split it.</p> <p>In some places I see people that want to split the <strong>text</strong> doing:</p> <pre><code>string.split(text) </code></pre> <p>In other places I see people just doing:</p> <pre><code>text.split() </code></pre> <p>What’s the difference? Why you do in one way or in the other way? Can you give me a theorist explanation about that?</p>
9
2008-12-02T11:41:05Z
334,013
<p>An extra note: <code>str</code> is the string type, as S.Lott points out above. That means that these two forms:</p> <pre><code>'a b c'.split() str.split('a b c') # both return ['a', 'b', 'c'] </code></pre> <p>...are equivalent, because <code>str.split</code> is the unbound method, while <code>s.split</code> is a bound method of a <code>str</code> object. In the second case, the string that gets passed in to <code>str.split</code> is used as <code>self</code> in the method.</p> <p>This doesn't make much difference here, but it's an important feature of how Python's object system works.</p> <p><a href="http://www.python.org/doc/2.6/library/stdtypes.html#methods" rel="nofollow">More info about bound and unbound methods.</a></p>
3
2008-12-02T14:04:17Z
[ "python" ]
string.split(text) or text.split() what's the difference?
333,706
<p>There is one thing that I do not understand... </p> <p>Imagine you have a <strong>text</strong> = "hello world" and you want to split it.</p> <p>In some places I see people that want to split the <strong>text</strong> doing:</p> <pre><code>string.split(text) </code></pre> <p>In other places I see people just doing:</p> <pre><code>text.split() </code></pre> <p>What’s the difference? Why you do in one way or in the other way? Can you give me a theorist explanation about that?</p>
9
2008-12-02T11:41:05Z
334,061
<p>Use whichever you like, but realize that str.split is the recommended way of doing it. :-)</p> <p>string.split is a tad older method of doing the same thing.</p> <p>str.split is a bit more efficient (since you don't have to import the string module or look up any names from it), but not enough to make a huge difference if you prefer string.split.</p>
0
2008-12-02T14:18:56Z
[ "python" ]
string.split(text) or text.split() what's the difference?
333,706
<p>There is one thing that I do not understand... </p> <p>Imagine you have a <strong>text</strong> = "hello world" and you want to split it.</p> <p>In some places I see people that want to split the <strong>text</strong> doing:</p> <pre><code>string.split(text) </code></pre> <p>In other places I see people just doing:</p> <pre><code>text.split() </code></pre> <p>What’s the difference? Why you do in one way or in the other way? Can you give me a theorist explanation about that?</p>
9
2008-12-02T11:41:05Z
334,109
<p>Short answer: the string module was the only way to perform these operations before python 1.6 - they've since been added to strings as methods.</p>
4
2008-12-02T14:32:16Z
[ "python" ]
How to detect that Python code is being executed through the debugger?
333,995
<p>Is there a simple way to detect, within Python code, that this code is being executed through the Python debugger?</p> <p>I have a small Python application that uses Java code (thanks to JPype). When I'm debugging the Python part, I'd like the embedded JVM to be given debug options too.</p>
12
2008-12-02T13:58:30Z
334,073
<p>From taking a quick look at the pdb docs and source code, it doesn't look like there is a built in way to do this. I suggest that you set an environment variable that indicates debugging is in progress and have your application respond to that.</p> <pre><code>$ USING_PDB=1 pdb yourprog.py </code></pre> <p>Then in yourprog.py:</p> <pre><code>import os if os.environ.get('USING_PDB'): # debugging actions pass </code></pre>
2
2008-12-02T14:21:17Z
[ "python" ]
How to detect that Python code is being executed through the debugger?
333,995
<p>Is there a simple way to detect, within Python code, that this code is being executed through the Python debugger?</p> <p>I have a small Python application that uses Java code (thanks to JPype). When I'm debugging the Python part, I'd like the embedded JVM to be given debug options too.</p>
12
2008-12-02T13:58:30Z
334,090
<p>Python debuggers (as well as profilers and coverage tools) use the <code>sys.settrace</code> function (in the <code>sys</code> module) to register a callback that gets called when interesting events happen.</p> <p>If you're using Python 2.6, you can call <code>sys.gettrace()</code> to get the current trace callback function. If it's not <code>None</code> then you can assume you should be passing debug parameters to the JVM.</p> <p>It's not clear how you could do this pre 2.6.</p>
13
2008-12-02T14:25:10Z
[ "python" ]
How to detect that Python code is being executed through the debugger?
333,995
<p>Is there a simple way to detect, within Python code, that this code is being executed through the Python debugger?</p> <p>I have a small Python application that uses Java code (thanks to JPype). When I'm debugging the Python part, I'd like the embedded JVM to be given debug options too.</p>
12
2008-12-02T13:58:30Z
334,612
<p>You can try to peek into your stacktrace.</p> <p><a href="https://docs.python.org/library/inspect.html#the-interpreter-stack" rel="nofollow">https://docs.python.org/library/inspect.html#the-interpreter-stack</a></p> <p>when you try this in a debugger session:</p> <pre><code>import inspect inspect.getouterframes(inspect.currentframe() </code></pre> <p>you will get a list of framerecords and can peek for any frames that refer to the pdb file.</p>
1
2008-12-02T16:36:14Z
[ "python" ]
How to detect that Python code is being executed through the debugger?
333,995
<p>Is there a simple way to detect, within Python code, that this code is being executed through the Python debugger?</p> <p>I have a small Python application that uses Java code (thanks to JPype). When I'm debugging the Python part, I'd like the embedded JVM to be given debug options too.</p>
12
2008-12-02T13:58:30Z
338,391
<p>A solution working with Python 2.4 (it should work with any version superior to 2.1) and Pydev:</p> <pre><code>import inspect def isdebugging(): for frame in inspect.stack(): if frame[1].endswith("pydevd.py"): return True return False </code></pre> <p>The same should work with pdb by simply replacing <code>pydevd.py</code> with <code>pdb.py</code>. As do3cc suggested, it tries to find the debugger within the stack of the caller.</p> <p>Useful links:</p> <ul> <li><a href="https://docs.python.org/library/pdb.html" rel="nofollow">The Python Debugger</a></li> <li><a href="https://docs.python.org/library/inspect.html#the-interpreter-stack" rel="nofollow">The interpreter stack</a></li> </ul>
7
2008-12-03T19:13:56Z
[ "python" ]
How to detect that Python code is being executed through the debugger?
333,995
<p>Is there a simple way to detect, within Python code, that this code is being executed through the Python debugger?</p> <p>I have a small Python application that uses Java code (thanks to JPype). When I'm debugging the Python part, I'd like the embedded JVM to be given debug options too.</p>
12
2008-12-02T13:58:30Z
7,546,741
<p>If you're using Pydev, you can detect it in such way:</p> <pre><code>import sys if 'pydevd' in sys.modules: print "Debugger" else: print "commandline" </code></pre>
1
2011-09-25T16:09:11Z
[ "python" ]
How to detect that Python code is being executed through the debugger?
333,995
<p>Is there a simple way to detect, within Python code, that this code is being executed through the Python debugger?</p> <p>I have a small Python application that uses Java code (thanks to JPype). When I'm debugging the Python part, I'd like the embedded JVM to be given debug options too.</p>
12
2008-12-02T13:58:30Z
8,028,466
<p>Another way to do it hinges on how your python interpreter is started. It requires you start Python using -O for production and with no -O for debugging. So it does require an external discipline that might be hard to maintain .. but then again it might fit your processes perfectly.</p> <p>From the python docs (see "Built-in Constants" <a href="http://docs.python.org/library/constants.html" rel="nofollow">here</a> or <a href="http://docs.python.org/release/3.1.3/library/constants.html" rel="nofollow">here</a>):</p> <pre><code>__debug__ This constant is true if Python was not started with an -O option. </code></pre> <p>Usage would be something like:</p> <pre><code>if __debug__: print 'Python started without optimization' </code></pre>
3
2011-11-06T16:30:00Z
[ "python" ]
How to detect that Python code is being executed through the debugger?
333,995
<p>Is there a simple way to detect, within Python code, that this code is being executed through the Python debugger?</p> <p>I have a small Python application that uses Java code (thanks to JPype). When I'm debugging the Python part, I'd like the embedded JVM to be given debug options too.</p>
12
2008-12-02T13:58:30Z
22,724,125
<p>I found a cleaner way to do it,</p> <p>Just add the following line in your <code>manage.py</code></p> <pre><code>#!/usr/bin/env python import os import sys if __debug__: sys.path.append('/path/to/views.py') if __name__ == "__main__": .... </code></pre> <p>Then it would automatically add it when you are debugging.</p>
1
2014-03-28T22:18:11Z
[ "python" ]
How to detect that Python code is being executed through the debugger?
333,995
<p>Is there a simple way to detect, within Python code, that this code is being executed through the Python debugger?</p> <p>I have a small Python application that uses Java code (thanks to JPype). When I'm debugging the Python part, I'd like the embedded JVM to be given debug options too.</p>
12
2008-12-02T13:58:30Z
26,605,963
<p>Other alternative if you're using Pydev that also works in a multithreading is:</p> <pre><code>try: import pydevd DEBUGGING = True except ImportError: DEBUGGING = False </code></pre>
5
2014-10-28T10:28:09Z
[ "python" ]
Passing a dictionary to a function in python as keyword parameters
334,655
<p>I'd like to call a function in python using a dictionary.</p> <p>Here is some code:</p> <pre><code>d = dict(param='test') def f(param): print param f(d) </code></pre> <p>This prints <code>{'param': 'test'}</code> but I'd like it to just print <code>test</code>.</p> <p>I'd like it to work similarly for more parameters:</p> <pre><code>d = dict(p1=1, p2=2) def f2(p1,p2): print p1, p2 f2(d) </code></pre> <p>Is this possible?</p>
165
2008-12-02T16:49:11Z
334,661
<p>Here ya go - works just any other iterable:</p> <pre><code>d = {'param' : 'test'} def f(dictionary): for key in dictionary: print key f(d) </code></pre>
-1
2008-12-02T16:52:20Z
[ "python", "function", "dictionary", "parameters", "keyword" ]
Passing a dictionary to a function in python as keyword parameters
334,655
<p>I'd like to call a function in python using a dictionary.</p> <p>Here is some code:</p> <pre><code>d = dict(param='test') def f(param): print param f(d) </code></pre> <p>This prints <code>{'param': 'test'}</code> but I'd like it to just print <code>test</code>.</p> <p>I'd like it to work similarly for more parameters:</p> <pre><code>d = dict(p1=1, p2=2) def f2(p1,p2): print p1, p2 f2(d) </code></pre> <p>Is this possible?</p>
165
2008-12-02T16:49:11Z
334,666
<p>Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary</p> <p>So my example becomes:</p> <pre><code>d = dict(p1=1, p2=2) def f2(p1,p2): print p1, p2 f2(**d) </code></pre>
258
2008-12-02T16:53:34Z
[ "python", "function", "dictionary", "parameters", "keyword" ]
Passing a dictionary to a function in python as keyword parameters
334,655
<p>I'd like to call a function in python using a dictionary.</p> <p>Here is some code:</p> <pre><code>d = dict(param='test') def f(param): print param f(d) </code></pre> <p>This prints <code>{'param': 'test'}</code> but I'd like it to just print <code>test</code>.</p> <p>I'd like it to work similarly for more parameters:</p> <pre><code>d = dict(p1=1, p2=2) def f2(p1,p2): print p1, p2 f2(d) </code></pre> <p>Is this possible?</p>
165
2008-12-02T16:49:11Z
335,626
<p>In python, this is called "unpacking", and you can find a bit about it in the <a href="https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists">tutorial</a>. The documentation of it sucks, I agree, especially because of how fantasically useful it is.</p>
19
2008-12-02T22:03:11Z
[ "python", "function", "dictionary", "parameters", "keyword" ]
Does PyS60 produce sis files that are native?
334,765
<p>I am currently looking at developing a mobile apps for the S60 platform and is specifically looking at PyS60. It seems to suggest that the it can be compiled into native .sis files without the need for an embedded python interpreter. Reading through the documentations I could not find any statements where this is explicitly mentioned. While I am right now downloading the SDKs, Emulators, and the whole bunch of tool chains needed to test the development out on Linux, I thought I would ask here a bit while I am doing that. </p>
9
2008-12-02T17:30:18Z
337,308
<p>Linux is not officially supported for Series60 development yet. You will save yourself a lot of headache using Windows, weirdly enough.</p> <p>As far as Python is oncerned, I think the developed application is packaged into a .sis file but still requires the PyS60 interpreter to run once installed.</p>
1
2008-12-03T14:33:34Z
[ "python", "symbian", "s60", "pys60" ]
Does PyS60 produce sis files that are native?
334,765
<p>I am currently looking at developing a mobile apps for the S60 platform and is specifically looking at PyS60. It seems to suggest that the it can be compiled into native .sis files without the need for an embedded python interpreter. Reading through the documentations I could not find any statements where this is explicitly mentioned. While I am right now downloading the SDKs, Emulators, and the whole bunch of tool chains needed to test the development out on Linux, I thought I would ask here a bit while I am doing that. </p>
9
2008-12-02T17:30:18Z
386,298
<p>Once you've written your code in python, you can convert this to a .sis file using ensymble.</p> <p><a href="http://code.google.com/p/ensymble/">http://code.google.com/p/ensymble/</a></p> <p>This software allows you to make your .py file into a .sis file using the py2sis option - however, it won't be much use on any phone without python installed, so you may also need to use ensymble to merge your newly-created .sis with the .sis file for python, with a command like</p> <p>./ensymble.py mergesis --verbose your-script-name.sis PythonForS60-1-4-5-3rdEd.sis final-app-name.sis</p> <p>the resulting final-app-name.sis file will install both your file and also python.</p>
14
2008-12-22T13:59:10Z
[ "python", "symbian", "s60", "pys60" ]
How to generate a filmstrip image in python from a folder of images?
334,827
<p>I would like to do the equivalent off <a href="http://www.bigdumbdev.com/2007/08/build-better-skimmer-part-2.html" rel="nofollow">this</a> (ruby code) in python for a Django project I am working on. I want to make a <a href="http://designvigilante.com/files/photoSkim/filmStrip.jpg" rel="nofollow">filmstrip image</a> of X number of images in a folder. </p>
3
2008-12-02T17:47:49Z
334,876
<p>Do you mnean something like this? <a href="http://code.activestate.com/recipes/412982/" rel="nofollow">Use PIL to make a "contact sheet" of images</a>?</p> <p>Perhaps there are others here that are closer to what you want: <a href="http://code.activestate.com/recipes/tags/graphics/" rel="nofollow">http://code.activestate.com/recipes/tags/graphics/</a></p>
4
2008-12-02T18:03:27Z
[ "python", "django", "image", "python-imaging-library" ]
How to generate a filmstrip image in python from a folder of images?
334,827
<p>I would like to do the equivalent off <a href="http://www.bigdumbdev.com/2007/08/build-better-skimmer-part-2.html" rel="nofollow">this</a> (ruby code) in python for a Django project I am working on. I want to make a <a href="http://designvigilante.com/files/photoSkim/filmStrip.jpg" rel="nofollow">filmstrip image</a> of X number of images in a folder. </p>
3
2008-12-02T17:47:49Z
335,323
<p>Here is a function that wraps <strong>the contact sheet</strong> function <a href="http://stackoverflow.com/users/10661/slott">S.Lott</a> mentioned.</p> <pre><code>#!/usr/bin/env python import os, os.path from contactsheet import make_contact_sheet def make_film_strip(fnames, (photow,photoh), (marl,mart,marr,marb), padding): return make_contact_sheet(fnames, (1, len(fnames)), (photow,photoh), (marl,mart,marr,marb), padding) </code></pre> <p>It is assuming the <a href="http://code.activestate.com/recipes/412982/" rel="nofollow">recipe</a> is saved as <code>contactsheet.py</code>. Usage is:</p> <pre><code>fstrip = filmstrip.make_film_strip(filmstrip.fnames, (120, 120), (0,0,0,0), 0) fstrip.save('/path/to/file.format') </code></pre> <p>Tested.</p>
1
2008-12-02T20:29:31Z
[ "python", "django", "image", "python-imaging-library" ]
How do I create trivial customized field types in Django models?
334,992
<p>I'm trying to make some types in Django that map to standard Django types. The <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields" rel="nofollow">custom model field documentation</a> goes into complicated cases; I just want to store a basic Django type from a class with a bunch of handy methods.</p> <p>For example, if I were storing playing cards, I want something like:</p> <pre><code>class Card(object): """ A playing card. """ def as_number(self): """ returns a number from 1 (Ace of Clubs) and 52 (King of Spades).""" return self.number + self.suit_rank() * 13 def __unicode(self): ... def is_highest(self, other_cards, trump=None):... def __init__(self, number, suit): ... ... </code></pre> <p>I want my models to have something like:</p> <pre><code>class my_game(models.Model): ante = models.IntegerField() bonus_card = Card() # Really stored as an models.IntegerField() .... </code></pre> <p>I'm expecting the answer will look like inheriting from the correct type, adding some specially named get/store fields for card, and renaming <strong>init</strong>(). Does anyone have sample code or better documentation?</p>
3
2008-12-02T18:41:44Z
335,215
<p>Why can't you do something like the following?</p> <pre><code>class Card(models.Model): """ A playing card. """ self.suit = models.PositiveIntegerField() self.rank = models.PositiveIntegerField( choices=SUIT_CHOICES ) def as_number(self): """ returns a number from 1 (Ace of Clubs) and 52 (King of Spades).""" return self.number + self.suit * 13 def __unicode__(self): return ... def is_highest(self, other_cards, trump=None):... </code></pre> <p>Certainly, this is quite simple, and fits comfortably with what Django does naturally.</p>
1
2008-12-02T19:55:40Z
[ "python", "django", "django-models" ]
How do I create trivial customized field types in Django models?
334,992
<p>I'm trying to make some types in Django that map to standard Django types. The <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields" rel="nofollow">custom model field documentation</a> goes into complicated cases; I just want to store a basic Django type from a class with a bunch of handy methods.</p> <p>For example, if I were storing playing cards, I want something like:</p> <pre><code>class Card(object): """ A playing card. """ def as_number(self): """ returns a number from 1 (Ace of Clubs) and 52 (King of Spades).""" return self.number + self.suit_rank() * 13 def __unicode(self): ... def is_highest(self, other_cards, trump=None):... def __init__(self, number, suit): ... ... </code></pre> <p>I want my models to have something like:</p> <pre><code>class my_game(models.Model): ante = models.IntegerField() bonus_card = Card() # Really stored as an models.IntegerField() .... </code></pre> <p>I'm expecting the answer will look like inheriting from the correct type, adding some specially named get/store fields for card, and renaming <strong>init</strong>(). Does anyone have sample code or better documentation?</p>
3
2008-12-02T18:41:44Z
335,269
<p>Don't be afraid to adapt the model classes in Django to your own needs. There's nothing magical about them. And I guess this is the Right Place for this code: In the model.</p>
0
2008-12-02T20:14:58Z
[ "python", "django", "django-models" ]
How do I create trivial customized field types in Django models?
334,992
<p>I'm trying to make some types in Django that map to standard Django types. The <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields" rel="nofollow">custom model field documentation</a> goes into complicated cases; I just want to store a basic Django type from a class with a bunch of handy methods.</p> <p>For example, if I were storing playing cards, I want something like:</p> <pre><code>class Card(object): """ A playing card. """ def as_number(self): """ returns a number from 1 (Ace of Clubs) and 52 (King of Spades).""" return self.number + self.suit_rank() * 13 def __unicode(self): ... def is_highest(self, other_cards, trump=None):... def __init__(self, number, suit): ... ... </code></pre> <p>I want my models to have something like:</p> <pre><code>class my_game(models.Model): ante = models.IntegerField() bonus_card = Card() # Really stored as an models.IntegerField() .... </code></pre> <p>I'm expecting the answer will look like inheriting from the correct type, adding some specially named get/store fields for card, and renaming <strong>init</strong>(). Does anyone have sample code or better documentation?</p>
3
2008-12-02T18:41:44Z
335,312
<p>I'd do this with a subclass of Django's PositiveIntegerField:</p> <pre><code>from django.db import models class Card(object): """The ``Card`` class you described.""" ... class CardField(models.PositiveIntegerField): __metaclass__ = models.SubfieldBase def get_db_prep_value(self, value): """Return the ``int`` equivalent of ``value``.""" if value is None: return None try: int_value = value.as_number() except AttributeError: int_value = int(value) return int_value def to_python(self, value): """Return the ``Card`` equivalent of ``value``.""" if value is None or isinstance(value, Card): return value return Card(int(value)) </code></pre> <p>The <code>get_db_prep_value</code> method is responsible for converting <code>value</code> into something suitable for interacting with the database, in this case either an <code>int</code> or <code>None</code>.</p> <p>The <code>to_python</code> method does the reverse, converting <code>value</code> into a <code>Card</code>. Just like before, you'll need to handle the possibility of <code>None</code> as a value. Using the <code>SubfieldBase</code> ensures that <code>to_python</code> is called every time a value is assigned to the field.</p>
3
2008-12-02T20:27:56Z
[ "python", "django", "django-models" ]
What's the best way to get the size of a folder and all the files inside from python?
335,078
<p>If there will be a small number of files it should be easy with a recursive function to pass through all the files and add the size but what if there are lots of files, and by lots i really mean lots of files.</p>
6
2008-12-02T19:09:50Z
335,105
<p>You mean something like this?</p> <pre><code>import os for path, dirs, files in os.walk( root ): for f in files: print path, f, os.path.getsize( os.path.join( path, f ) ) </code></pre>
10
2008-12-02T19:17:59Z
[ "python" ]
What's the best way to get the size of a folder and all the files inside from python?
335,078
<p>If there will be a small number of files it should be easy with a recursive function to pass through all the files and add the size but what if there are lots of files, and by lots i really mean lots of files.</p>
6
2008-12-02T19:09:50Z
335,106
<p>There is no other way to compute the size than recursively invoking stat. This is independent of Python; the operating system just provides no other way.</p> <p>The algorithm doesn't have to be recursive; you can use os.walk.</p> <p>There might be two exceptions to make it more efficient:</p> <ol> <li>If all the files you want to measure fill a partition, and the partition has no other files, then you can look at the disk usage of the partition.</li> <li>If you can continuously monitor all files, or are responsible for creating all the files yourself, you can generate an incremental disk usage.</li> </ol>
5
2008-12-02T19:18:28Z
[ "python" ]
What's the best way to get the size of a folder and all the files inside from python?
335,078
<p>If there will be a small number of files it should be easy with a recursive function to pass through all the files and add the size but what if there are lots of files, and by lots i really mean lots of files.</p>
6
2008-12-02T19:09:50Z
335,335
<p>There is a recipe for that problem in the Python Cookbook (O'Reilly). You can read the full solution with an example online:</p> <p><a href="http://safari.oreilly.com/0596001673/pythoncook-CHP-4-SECT-24" rel="nofollow">http://safari.oreilly.com/0596001673/pythoncook-CHP-4-SECT-24</a></p> <p>or here:</p> <p><a href="http://books.google.com/books?id=yhfdQgq8JF4C&amp;pg=PA152&amp;dq=du+command+in+python" rel="nofollow">http://books.google.com/books?id=yhfdQgq8JF4C&amp;pg=PA152&amp;dq=du+command+in+python</a></p>
1
2008-12-02T20:33:00Z
[ "python" ]
What's the best way to get the size of a folder and all the files inside from python?
335,078
<p>If there will be a small number of files it should be easy with a recursive function to pass through all the files and add the size but what if there are lots of files, and by lots i really mean lots of files.</p>
6
2008-12-02T19:09:50Z
9,439,237
<p>If you are on a posix system that provides du, you should be able to use <code>pexpect.run</code> or <code>subprocess</code> to execute <code>du &lt;path to folder&gt;</code> to get the size of the folder and subfiles. Keep in mind it will output a string with each file listed and each folder totaled. (Look at the du manpage to see what you can do to limit that).</p>
0
2012-02-24T22:58:50Z
[ "python" ]
detecting if a module is imported inside the app engine environment
335,399
<p>What I want to do is patch an existing python module that uses urllib2 to run on app engine, but I don't want to break it so it can be used elsewhere. So I'm looking for a quick solution to test if the module is imported in the app engine environment or not. Catching ImportError on urllib2 might not be the best solution.</p>
4
2008-12-02T20:48:08Z
335,464
<p>You could simply use sys.modules to test if a module has been imported (I'm using unicodedata as an example):</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; 'unicodedata' in sys.modules False &gt;&gt;&gt; import unicodedata &gt;&gt;&gt; 'unicodedata' in sys.modules True </code></pre>
11
2008-12-02T21:13:13Z
[ "python", "google-app-engine" ]
detecting if a module is imported inside the app engine environment
335,399
<p>What I want to do is patch an existing python module that uses urllib2 to run on app engine, but I don't want to break it so it can be used elsewhere. So I'm looking for a quick solution to test if the module is imported in the app engine environment or not. Catching ImportError on urllib2 might not be the best solution.</p>
4
2008-12-02T20:48:08Z
17,221,027
<p>You could do a simple check against key environment variables. No telling exactly how reliable this might be, though.</p> <pre><code>import os, logging try: os.environ['APPENGINE_RUNTIME'] except KeyError: logging.warn('We are not in App Engine environment') else: logging.info('We are in the App Engine environment') </code></pre> <p>You can also <a href="https://developers.google.com/appengine/docs/python/config/appconfig#Defining_Environment_Variables" rel="nofollow">define your own custom environment variable in your App Engine configuration file</a> and that will be viewable from <code>os.environ</code> within any module. So, type something like this in your app.yaml file:</p> <pre><code>env_variables: MY_APP_ENGINE_ENVIRONMENT: '982844ed9cbd6ce42318d2804386be29cbc7c35a' </code></pre> <p>... will give you an unambiguous ID to reference.</p> <p>From the development server, here are the environment variables that I get:</p> <pre><code>{'USER_EMAIL': '', 'DATACENTER': 'us1', 'wsgi.version': (1, 0), 'REQUEST_ID_HASH': 'E2C19D51', 'SERVER_NAME': 'mydesktop', 'QUERY_STRING': '', 'HTTP_ACCEPT': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'APPENGINE_RUNTIME': 'python27', 'wsgi.input': &lt;cStringIO.StringI object at 0x2f145d0&gt;, 'SERVER_PROTOCOL': 'HTTP/1.1', 'HTTPS': 'off', 'USER_IS_ADMIN': '0', 'TZ': 'UTC', 'REMOTE_ADDR': '192.168.0.2', 'HTTP_X_APPENGINE_COUNTRY': 'ZZ', 'HTTP_USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36', 'SERVER_SOFTWARE': 'Development/2.0', 'HTTP_CACHE_CONTROL': 'max-age=0', 'DEFAULT_VERSION_HOSTNAME': 'mydesktop:8080', 'SERVER_PORT': '8080', 'wsgi.run_once': False, 'REQUEST_METHOD': 'GET', 'USER_ID': '', 'AUTH_DOMAIN': 'gmail.com', 'USER_NICKNAME': '', 'USER_ORGANIZATION': '', 'wsgi.multiprocess': True, 'INSTANCE_ID': '8a8e02e6efa8d195346ae0c90cfeafce8aa2', 'PATH_INFO': '/', 'HTTP_ACCEPT_LANGUAGE': 'en-US,en;q=0.8', 'HTTP_HOST': 'mydesktop:8080', 'wsgi.errors': &lt;google.appengine.api.logservice.logservice.LogsBuffer object at 0x2f09c30&gt;, 'APPLICATION_ID': 'dev~myapp', 'wsgi.multithread': True, 'CURRENT_VERSION_ID': 'version-1', 'SCRIPT_NAME': '', 'REQUEST_LOG_ID': '4eafbc91ca4ebd5fee53f19eeab2eb26d243d9ddc92b6b9bc0a063eabdc84cfff', 'wsgi.url_scheme': 'http'} </code></pre> <p>Hope that helps.</p>
0
2013-06-20T18:25:29Z
[ "python", "google-app-engine" ]
Python: smtpd (or alternative) for production mail receiving?
335,582
<p>I'm looking to do various processing of email - eg. inspect the headers, and if they meet some criteria (look like spam), drop the connection, or inspect the recipient list and perform special filtering.</p> <p>Looks like Python's smtpd library provides a nice and simple interface for processing the received email. </p> <p>To deal with the message before it's fully processed (eg. to drop the message in case the headers look like spam), should I be using handle_connect? Are the internal APIs (other than process_message) documented somewhere? Example code anywhere?</p> <p>Also, has anyone used smtpd in production? Any thoughts on reliability, etc?</p> <p>Regarding Twisted: I've attempted to embrace Twisted several times and quite like the deferred model, but it's a bit too complex for my current taste. I'll give it another look, but for now I'm more interested in non-Twisted implementations.</p>
3
2008-12-02T21:46:16Z
335,640
<p>You may want to look at the <a href="http://twistedmatrix.com/trac/">twisted</a> implementation as that will give you access to the full range of interaction with the client. I believe (though I have never used it in production) that twisted can be trusted in a production environment.</p>
5
2008-12-02T22:07:10Z
[ "python", "smtp", "smtpd" ]
Python: smtpd (or alternative) for production mail receiving?
335,582
<p>I'm looking to do various processing of email - eg. inspect the headers, and if they meet some criteria (look like spam), drop the connection, or inspect the recipient list and perform special filtering.</p> <p>Looks like Python's smtpd library provides a nice and simple interface for processing the received email. </p> <p>To deal with the message before it's fully processed (eg. to drop the message in case the headers look like spam), should I be using handle_connect? Are the internal APIs (other than process_message) documented somewhere? Example code anywhere?</p> <p>Also, has anyone used smtpd in production? Any thoughts on reliability, etc?</p> <p>Regarding Twisted: I've attempted to embrace Twisted several times and quite like the deferred model, but it's a bit too complex for my current taste. I'll give it another look, but for now I'm more interested in non-Twisted implementations.</p>
3
2008-12-02T21:46:16Z
337,004
<p>Another approach: use <a href="http://www.postfix.org" rel="nofollow">Postfix</a> for receiving email and write a <a href="http://www.postfix.org/SMTPD_POLICY_README.html" rel="nofollow">policy</a> script in Python.</p>
1
2008-12-03T12:57:12Z
[ "python", "smtp", "smtpd" ]
Lists in ConfigParser
335,695
<p>The typical ConfigParser generated file looks like:</p> <pre><code>[Section] bar=foo [Section 2] bar2= baz </code></pre> <p>Now, is there a way to index lists like, for instance:</p> <pre><code>[Section 3] barList={ item1, item2 } </code></pre> <p>Related question: <a href="http://stackoverflow.com/questions/287757/pythons-configparser-unique-keys-per-section">Python’s ConfigParser unique keys per section</a></p> <p>? Thanks in advance</p>
77
2008-12-02T22:29:05Z
335,717
<p>Only primitive types are supported for serialization by config parser. I would use JSON or YAML for that kind of requirement.</p>
2
2008-12-02T22:37:12Z
[ "python", "configparser" ]
Lists in ConfigParser
335,695
<p>The typical ConfigParser generated file looks like:</p> <pre><code>[Section] bar=foo [Section 2] bar2= baz </code></pre> <p>Now, is there a way to index lists like, for instance:</p> <pre><code>[Section 3] barList={ item1, item2 } </code></pre> <p>Related question: <a href="http://stackoverflow.com/questions/287757/pythons-configparser-unique-keys-per-section">Python’s ConfigParser unique keys per section</a></p> <p>? Thanks in advance</p>
77
2008-12-02T22:29:05Z
335,754
<p>There is nothing stopping you from packing the list into a delimited string and then unpacking it once you get the string from the config. If you did it this way your config section would look like:</p> <pre><code>[Section 3] barList=item1,item2 </code></pre> <p>It's not pretty but it's functional for most simple lists.</p>
67
2008-12-02T22:56:44Z
[ "python", "configparser" ]
Lists in ConfigParser
335,695
<p>The typical ConfigParser generated file looks like:</p> <pre><code>[Section] bar=foo [Section 2] bar2= baz </code></pre> <p>Now, is there a way to index lists like, for instance:</p> <pre><code>[Section 3] barList={ item1, item2 } </code></pre> <p>Related question: <a href="http://stackoverflow.com/questions/287757/pythons-configparser-unique-keys-per-section">Python’s ConfigParser unique keys per section</a></p> <p>? Thanks in advance</p>
77
2008-12-02T22:29:05Z
336,545
<p>I faced the same problem in the past. If you need more complex lists, consider creating your own parser by inheriting from ConfigParser. Then you would overwrite the get method with that:</p> <pre><code> def get(self, section, option): """ Get a parameter if the returning value is a list, convert string value to a python list""" value = SafeConfigParser.get(self, section, option) if (value[0] == "[") and (value[-1] == "]"): return eval(value) else: return value </code></pre> <p>With this solution you will also be able to define dictionaries in your config file.</p> <p>But be careful! This is not as safe: this means anyone could run code through your config file. If security is not an issue in your project, I would consider using directly python classes as config files. The following is much more powerful and expendable than a ConfigParser file:</p> <pre><code>class Section bar = foo class Section2 bar2 = baz class Section3 barList=[ item1, item2 ] </code></pre>
2
2008-12-03T08:58:59Z
[ "python", "configparser" ]
Lists in ConfigParser
335,695
<p>The typical ConfigParser generated file looks like:</p> <pre><code>[Section] bar=foo [Section 2] bar2= baz </code></pre> <p>Now, is there a way to index lists like, for instance:</p> <pre><code>[Section 3] barList={ item1, item2 } </code></pre> <p>Related question: <a href="http://stackoverflow.com/questions/287757/pythons-configparser-unique-keys-per-section">Python’s ConfigParser unique keys per section</a></p> <p>? Thanks in advance</p>
77
2008-12-02T22:29:05Z
8,048,529
<p>Coming late to this party, but I recently implemented this with a dedicated section in a config file for a list:</p> <pre><code>[paths] path1 = /some/path/ path2 = /another/path/ ... </code></pre> <p>and using <code>config.items( "paths" )</code> to get an iterable list of path items, like so:</p> <pre><code>path_items = config.items( "paths" ) for key, path in path_items: #do something with path </code></pre> <p>Hope this helps other folk Googling this question ;)</p>
60
2011-11-08T09:50:51Z
[ "python", "configparser" ]
Lists in ConfigParser
335,695
<p>The typical ConfigParser generated file looks like:</p> <pre><code>[Section] bar=foo [Section 2] bar2= baz </code></pre> <p>Now, is there a way to index lists like, for instance:</p> <pre><code>[Section 3] barList={ item1, item2 } </code></pre> <p>Related question: <a href="http://stackoverflow.com/questions/287757/pythons-configparser-unique-keys-per-section">Python’s ConfigParser unique keys per section</a></p> <p>? Thanks in advance</p>
77
2008-12-02T22:29:05Z
9,735,884
<p>Also a bit late, but maybe helpful for some. I am using a combination of ConfigParser and JSON:</p> <pre><code>[Foo] fibs: [1,1,2,3,5,8,13] </code></pre> <p>just read it with:</p> <pre><code>&gt;&gt;&gt; json.loads(config.get("Foo","fibs")) [1, 1, 2, 3, 5, 8, 13] </code></pre> <p>You can even break lines if your list is long (thanks @peter-smit):</p> <pre><code>[Bar] files_to_check = [ "/path/to/file1", "/path/to/file2", "/path/to/another file with space in the name" ] </code></pre> <p>Of course i could just use JSON, but i find config files much more readable, and the [DEFAULT] Section very handy.</p>
91
2012-03-16T10:48:22Z
[ "python", "configparser" ]
Lists in ConfigParser
335,695
<p>The typical ConfigParser generated file looks like:</p> <pre><code>[Section] bar=foo [Section 2] bar2= baz </code></pre> <p>Now, is there a way to index lists like, for instance:</p> <pre><code>[Section 3] barList={ item1, item2 } </code></pre> <p>Related question: <a href="http://stackoverflow.com/questions/287757/pythons-configparser-unique-keys-per-section">Python’s ConfigParser unique keys per section</a></p> <p>? Thanks in advance</p>
77
2008-12-02T22:29:05Z
11,866,695
<p>One thing a lot of people don't know is that multi-line configuration-values are allowed. For example:</p> <pre><code>;test.ini [hello] barlist = item1 item2 </code></pre> <p>The value of <code>config.get('hello','barlist')</code> will now be:</p> <pre><code>"\nitem1\nitem2" </code></pre> <p>Which you easily can split with the splitlines method (don't forget to filter empty items).</p> <p>If we look to a big framework like Pyramid they are using this technique:</p> <pre><code>def aslist_cronly(value): if isinstance(value, string_types): value = filter(None, [x.strip() for x in value.splitlines()]) return list(value) def aslist(value, flatten=True): """ Return a list of strings, separating the input based on newlines and, if flatten=True (the default), also split on spaces within each line.""" values = aslist_cronly(value) if not flatten: return values result = [] for value in values: subvalues = value.split() result.extend(subvalues) return result </code></pre> <p><a href="https://github.com/Pylons/pyramid/blob/1c37b5487d229d1896ec983de1377f3282825739/pyramid/settings.py#L44">Source</a></p> <p>Myself, I would maybe extend the ConfigParser if this is a common thing for you:</p> <pre><code>class MyConfigParser(ConfigParser): def getlist(self,section,option): value = self.get(section,option) return list(filter(None, (x.strip() for x in value.splitlines()))) def getlistint(self,section,option): return [int(x) for x in self.getlist(section,option)] </code></pre> <p>Note that there are a few things to look out for when using this technique</p> <ol> <li>New lines that are items should start with whitespace (e.g. a space or a tab)</li> <li>All following lines that start with whitespace are considered to be part of the previous item. Also if it has an = sign or if it starts with a ; following the whitespace.</li> </ol>
34
2012-08-08T14:26:45Z
[ "python", "configparser" ]
Lists in ConfigParser
335,695
<p>The typical ConfigParser generated file looks like:</p> <pre><code>[Section] bar=foo [Section 2] bar2= baz </code></pre> <p>Now, is there a way to index lists like, for instance:</p> <pre><code>[Section 3] barList={ item1, item2 } </code></pre> <p>Related question: <a href="http://stackoverflow.com/questions/287757/pythons-configparser-unique-keys-per-section">Python’s ConfigParser unique keys per section</a></p> <p>? Thanks in advance</p>
77
2008-12-02T22:29:05Z
13,163,390
<pre><code>import ConfigParser import os class Parser(object): """attributes may need additional manipulation""" def __init__(self, section): """section to retun all options on, formatted as an object transforms all comma-delimited options to lists comma-delimited lists with colons are transformed to dicts dicts will have values expressed as lists, no matter the length """ c = ConfigParser.RawConfigParser() c.read(os.path.join(os.path.dirname(__file__), 'config.cfg')) self.section_name = section self.__dict__.update({k:v for k, v in c.items(section)}) #transform all ',' into lists, all ':' into dicts for key, value in self.__dict__.items(): if value.find(':') &gt; 0: #dict vals = value.split(',') dicts = [{k:v} for k, v in [d.split(':') for d in vals]] merged = {} for d in dicts: for k, v in d.items(): merged.setdefault(k, []).append(v) self.__dict__[key] = merged elif value.find(',') &gt; 0: #list self.__dict__[key] = value.split(',') </code></pre> <p>So now my <code>config.cfg</code> file, which could look like this:</p> <pre><code>[server] credentials=username:admin,password:$3&lt;r3t loggingdirs=/tmp/logs,~/logs,/var/lib/www/logs timeoutwait=15 </code></pre> <p>Can be parsed into fine-grained-enough objects for my small project.</p> <pre><code>&gt;&gt;&gt; import config &gt;&gt;&gt; my_server = config.Parser('server') &gt;&gt;&gt; my_server.credentials {'username': ['admin'], 'password', ['$3&lt;r3t']} &gt;&gt;&gt; my_server.loggingdirs: ['/tmp/logs', '~/logs', '/var/lib/www/logs'] &gt;&gt;&gt; my_server.timeoutwait '15' </code></pre> <p>This is for very quick parsing of simple configs, you lose all ability to fetch ints, bools, and other types of output without either transforming the object returned from <code>Parser</code>, or re-doing the parsing job accomplished by the Parser class elsewhere.</p>
1
2012-10-31T17:20:10Z
[ "python", "configparser" ]
Lists in ConfigParser
335,695
<p>The typical ConfigParser generated file looks like:</p> <pre><code>[Section] bar=foo [Section 2] bar2= baz </code></pre> <p>Now, is there a way to index lists like, for instance:</p> <pre><code>[Section 3] barList={ item1, item2 } </code></pre> <p>Related question: <a href="http://stackoverflow.com/questions/287757/pythons-configparser-unique-keys-per-section">Python’s ConfigParser unique keys per section</a></p> <p>? Thanks in advance</p>
77
2008-12-02T22:29:05Z
22,478,998
<p>If you want to <strong>literally</strong> pass in a list then you can use:</p> <pre><code>ast.literal_eval() </code></pre> <p>For example configuration:</p> <pre><code>[section] option=["item1","item2","item3"] </code></pre> <p>The code is:</p> <pre><code>import ConfigParser import ast my_list = ast.literal_eval(config.get("section", "option")) print(type(my_list)) print(my_list) </code></pre> <p>output:</p> <pre><code>&lt;type'list'&gt; ["item1","item2","item3"] </code></pre>
6
2014-03-18T12:10:56Z
[ "python", "configparser" ]
Lists in ConfigParser
335,695
<p>The typical ConfigParser generated file looks like:</p> <pre><code>[Section] bar=foo [Section 2] bar2= baz </code></pre> <p>Now, is there a way to index lists like, for instance:</p> <pre><code>[Section 3] barList={ item1, item2 } </code></pre> <p>Related question: <a href="http://stackoverflow.com/questions/287757/pythons-configparser-unique-keys-per-section">Python’s ConfigParser unique keys per section</a></p> <p>? Thanks in advance</p>
77
2008-12-02T22:29:05Z
22,675,825
<p>I landed here seeking to consume this...</p> <pre><code>[global] spys = [email protected], [email protected] </code></pre> <p>The answer is to split it on the comma and strip the spaces:</p> <pre><code>SPYS = [e.strip() for e in parser.get('global', 'spys').split(',')] </code></pre> <p>To get a list result:</p> <pre><code>['[email protected]', '[email protected]'] </code></pre> <p>It may not answer the OP's question exactly but might be the simple answer some people are looking for.</p>
8
2014-03-27T00:20:03Z
[ "python", "configparser" ]
Lists in ConfigParser
335,695
<p>The typical ConfigParser generated file looks like:</p> <pre><code>[Section] bar=foo [Section 2] bar2= baz </code></pre> <p>Now, is there a way to index lists like, for instance:</p> <pre><code>[Section 3] barList={ item1, item2 } </code></pre> <p>Related question: <a href="http://stackoverflow.com/questions/287757/pythons-configparser-unique-keys-per-section">Python’s ConfigParser unique keys per section</a></p> <p>? Thanks in advance</p>
77
2008-12-02T22:29:05Z
30,223,001
<p>This is what I use for lists:</p> <p>config file content: </p> <pre><code>[sect] alist = a b c </code></pre> <p>code : </p> <pre><code>l = config.get('sect', 'alist').split('\n') </code></pre> <p>it work for strings</p> <p>in case of numbers </p> <p>config content:</p> <pre><code>nlist = 1 2 3 </code></pre> <p>code:</p> <pre><code>nl = config.get('sect', 'alist').split('\n') l = [int(nl) for x in nl] </code></pre> <p>thanks.</p>
2
2015-05-13T18:50:04Z
[ "python", "configparser" ]
Shell Script doesn't run automatically though it is registered in Mac OS X Login Items
335,891
<p>I have the following shell script registered in my "Login Items" preferences but it does not seem to have any effect. It is meant to launch the moinmoin wiki but only works when it is run by hand from a terminal window, after which it runs until the machine is next shut down.</p> <pre><code>#!/bin/bash cd /Users/stuartcw/Documents/Wiki/moin-1.7.2 /usr/bin/python wikiserver.py &gt;&gt; logs/`date +"%d%b%Y"`.log 2&gt;&amp;1 &amp; </code></pre> <p>I would really like the Wiki to be available after restarting so any help in understanding this would be appreciated.</p>
4
2008-12-03T00:19:58Z
335,906
<p>I don't know much about it, since I don't use login items. Just a suggestion, maybe try with applescript that calls those shell commands, and put that in Login Items.</p>
1
2008-12-03T00:25:51Z
[ "python", "osx", "bash", "launchd", "moinmoin" ]
Shell Script doesn't run automatically though it is registered in Mac OS X Login Items
335,891
<p>I have the following shell script registered in my "Login Items" preferences but it does not seem to have any effect. It is meant to launch the moinmoin wiki but only works when it is run by hand from a terminal window, after which it runs until the machine is next shut down.</p> <pre><code>#!/bin/bash cd /Users/stuartcw/Documents/Wiki/moin-1.7.2 /usr/bin/python wikiserver.py &gt;&gt; logs/`date +"%d%b%Y"`.log 2&gt;&amp;1 &amp; </code></pre> <p>I would really like the Wiki to be available after restarting so any help in understanding this would be appreciated.</p>
4
2008-12-03T00:19:58Z
335,909
<p>Try using launchd. More info at <a href="http://www.macgeekery.com/tips/all_about_launchd_items_and_how_to_make_one_yourself" rel="nofollow">http://www.macgeekery.com/tips/all_about_launchd_items_and_how_to_make_one_yourself</a></p>
4
2008-12-03T00:26:49Z
[ "python", "osx", "bash", "launchd", "moinmoin" ]
Shell Script doesn't run automatically though it is registered in Mac OS X Login Items
335,891
<p>I have the following shell script registered in my "Login Items" preferences but it does not seem to have any effect. It is meant to launch the moinmoin wiki but only works when it is run by hand from a terminal window, after which it runs until the machine is next shut down.</p> <pre><code>#!/bin/bash cd /Users/stuartcw/Documents/Wiki/moin-1.7.2 /usr/bin/python wikiserver.py &gt;&gt; logs/`date +"%d%b%Y"`.log 2&gt;&amp;1 &amp; </code></pre> <p>I would really like the Wiki to be available after restarting so any help in understanding this would be appreciated.</p>
4
2008-12-03T00:19:58Z
335,922
<p>Some helpful links:</p> <p><a href="http://support.apple.com/kb/HT2420" rel="nofollow">Mac OS X: Creating a login hook</a></p> <p><a href="http://www.informit.com/library/content.aspx?b=Mac_OS_X_Unleashed&amp;seqNum=153" rel="nofollow"> Making Shell Scripts Start at Login or System Startup</a></p> <p>See also <a href="http://tuppis.com/lingon/" rel="nofollow">Lingon</a> for a front end, should you decide to use Launchd instead.</p>
3
2008-12-03T00:36:56Z
[ "python", "osx", "bash", "launchd", "moinmoin" ]
Shell Script doesn't run automatically though it is registered in Mac OS X Login Items
335,891
<p>I have the following shell script registered in my "Login Items" preferences but it does not seem to have any effect. It is meant to launch the moinmoin wiki but only works when it is run by hand from a terminal window, after which it runs until the machine is next shut down.</p> <pre><code>#!/bin/bash cd /Users/stuartcw/Documents/Wiki/moin-1.7.2 /usr/bin/python wikiserver.py &gt;&gt; logs/`date +"%d%b%Y"`.log 2&gt;&amp;1 &amp; </code></pre> <p>I would really like the Wiki to be available after restarting so any help in understanding this would be appreciated.</p>
4
2008-12-03T00:19:58Z
336,239
<p>launchd is one of the best parts of MacOS X, and it causes me great pain to not be able to find it on other systems.</p> <p>Edit and place this in <code>/Library/LaunchDaemons</code> as <code>com.you.wiki.plist</code></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"&gt; &lt;plist version="1.0"&gt; &lt;dict&gt; &lt;key&gt;Label&lt;/key&gt; &lt;string&gt;com.you.wiki&lt;/string&gt; &lt;key&gt;LowPriorityIO&lt;/key&gt; &lt;true/&gt; &lt;key&gt;KeepAlive&lt;/key&gt; &lt;true/&gt; &lt;key&gt;RunAtLoad&lt;/key&gt; &lt;true/&gt; &lt;key&gt;Nice&lt;/key&gt; &lt;integer&gt;1&lt;/integer&gt; &lt;key&gt;WorkingDirectory&lt;/key&gt; &lt;string&gt;/Users/stuartcw/Documents/Wiki/moin-1.7.2&lt;/string&gt; &lt;key&gt;UserName&lt;/key&gt; &lt;string&gt;user to run this as&lt;/string&gt; &lt;key&gt;ProgramArguments&lt;/key&gt; &lt;array&gt; &lt;string&gt;/usr/bin/python&lt;/string&gt; &lt;string&gt;wikiserver.py&lt;/string&gt; &lt;/array&gt; &lt;/dict&gt; &lt;/plist&gt; </code></pre>
4
2008-12-03T04:46:19Z
[ "python", "osx", "bash", "launchd", "moinmoin" ]
How to complete this python function to save in the same folder?
335,896
<p>I am trying to write my first real python function that does something real. What i want to accomplish is searching a given folder, and then open all images and merging them together so they make a filmstrip image. Imagine 5 images stacked on top of eachother in one image.</p> <p>I have this code now, which should be pretty much ok, but propably needs some modification:</p> <pre><code>import os import Image def filmstripOfImages(): imgpath = '/path/here/' files = glob.glob(imgpath + '*.jpg') imgwidth = files[0].size[0] imgheight = files[0].size[1] totalheight = imgheight * len(files) filename = 'filmstrip.jpg' filmstrip_url = imgpath + filename # Create the new image. The background doesn't have to be white white = (255,255,255) filmtripimage = Image.new('RGB',(imgwidth, totalheight),white) row = 0 for file in files: img = Image.open(file) left = 0 right = left + imgwidth upper = row*imgheight lower = upper + imgheight box = (left,upper,right,lower) row += 1 filmstripimage.paste(img, box) try: filmstripimage.save(filename, 'jpg', quality=90, optimize=1) except: filmstripimage.save(miniature_filename, 'jpg', quality=90)") </code></pre> <p>How do i modify this so that it saves the new filmstrip.jpg in the same directory as I loaded the images from? And it probably has some things that are missing or wrong, anybody got a clue?</p> <p>Related question: <a href="http://stackoverflow.com/questions/334827/how-to-generate-a-filmstrip-image-in-python-from-a-folder-of-images">How to generate a filmstrip image in python from a folder of images?</a></p>
3
2008-12-03T00:22:27Z
335,916
<p>I think if you change your <code>try</code> section to this:</p> <pre><code>filmstripimage.save(filmstrip_url, 'jpg', quality=90, optimize=1) </code></pre>
1
2008-12-03T00:30:24Z
[ "python", "image-processing", "python-imaging-library" ]
How to complete this python function to save in the same folder?
335,896
<p>I am trying to write my first real python function that does something real. What i want to accomplish is searching a given folder, and then open all images and merging them together so they make a filmstrip image. Imagine 5 images stacked on top of eachother in one image.</p> <p>I have this code now, which should be pretty much ok, but propably needs some modification:</p> <pre><code>import os import Image def filmstripOfImages(): imgpath = '/path/here/' files = glob.glob(imgpath + '*.jpg') imgwidth = files[0].size[0] imgheight = files[0].size[1] totalheight = imgheight * len(files) filename = 'filmstrip.jpg' filmstrip_url = imgpath + filename # Create the new image. The background doesn't have to be white white = (255,255,255) filmtripimage = Image.new('RGB',(imgwidth, totalheight),white) row = 0 for file in files: img = Image.open(file) left = 0 right = left + imgwidth upper = row*imgheight lower = upper + imgheight box = (left,upper,right,lower) row += 1 filmstripimage.paste(img, box) try: filmstripimage.save(filename, 'jpg', quality=90, optimize=1) except: filmstripimage.save(miniature_filename, 'jpg', quality=90)") </code></pre> <p>How do i modify this so that it saves the new filmstrip.jpg in the same directory as I loaded the images from? And it probably has some things that are missing or wrong, anybody got a clue?</p> <p>Related question: <a href="http://stackoverflow.com/questions/334827/how-to-generate-a-filmstrip-image-in-python-from-a-folder-of-images">How to generate a filmstrip image in python from a folder of images?</a></p>
3
2008-12-03T00:22:27Z
335,921
<p>In the case you are not joking there are several problems with your script e.g. <code>glob.glob()</code> returns list of filenames (string objects, not Image objects) therefore <code>files[0].size[0]</code> will not work.</p>
1
2008-12-03T00:35:58Z
[ "python", "image-processing", "python-imaging-library" ]
How to complete this python function to save in the same folder?
335,896
<p>I am trying to write my first real python function that does something real. What i want to accomplish is searching a given folder, and then open all images and merging them together so they make a filmstrip image. Imagine 5 images stacked on top of eachother in one image.</p> <p>I have this code now, which should be pretty much ok, but propably needs some modification:</p> <pre><code>import os import Image def filmstripOfImages(): imgpath = '/path/here/' files = glob.glob(imgpath + '*.jpg') imgwidth = files[0].size[0] imgheight = files[0].size[1] totalheight = imgheight * len(files) filename = 'filmstrip.jpg' filmstrip_url = imgpath + filename # Create the new image. The background doesn't have to be white white = (255,255,255) filmtripimage = Image.new('RGB',(imgwidth, totalheight),white) row = 0 for file in files: img = Image.open(file) left = 0 right = left + imgwidth upper = row*imgheight lower = upper + imgheight box = (left,upper,right,lower) row += 1 filmstripimage.paste(img, box) try: filmstripimage.save(filename, 'jpg', quality=90, optimize=1) except: filmstripimage.save(miniature_filename, 'jpg', quality=90)") </code></pre> <p>How do i modify this so that it saves the new filmstrip.jpg in the same directory as I loaded the images from? And it probably has some things that are missing or wrong, anybody got a clue?</p> <p>Related question: <a href="http://stackoverflow.com/questions/334827/how-to-generate-a-filmstrip-image-in-python-from-a-folder-of-images">How to generate a filmstrip image in python from a folder of images?</a></p>
3
2008-12-03T00:22:27Z
335,935
<p>as J. F. Sebastian mentioned, glob does not return image objects... but also:</p> <p>As it is right now, the script assumes the images in the folder are all the same size and shape. This is not often a safe assumption to make.</p> <p>So for both of those reasons, you'll need to open the images before you can determine their size. Once you open it you should set the width, and scale the images to that width so there is no empty space.</p> <p>Also, you didn't set miniature_filename anywhere in the script.</p>
1
2008-12-03T00:46:17Z
[ "python", "image-processing", "python-imaging-library" ]
How to complete this python function to save in the same folder?
335,896
<p>I am trying to write my first real python function that does something real. What i want to accomplish is searching a given folder, and then open all images and merging them together so they make a filmstrip image. Imagine 5 images stacked on top of eachother in one image.</p> <p>I have this code now, which should be pretty much ok, but propably needs some modification:</p> <pre><code>import os import Image def filmstripOfImages(): imgpath = '/path/here/' files = glob.glob(imgpath + '*.jpg') imgwidth = files[0].size[0] imgheight = files[0].size[1] totalheight = imgheight * len(files) filename = 'filmstrip.jpg' filmstrip_url = imgpath + filename # Create the new image. The background doesn't have to be white white = (255,255,255) filmtripimage = Image.new('RGB',(imgwidth, totalheight),white) row = 0 for file in files: img = Image.open(file) left = 0 right = left + imgwidth upper = row*imgheight lower = upper + imgheight box = (left,upper,right,lower) row += 1 filmstripimage.paste(img, box) try: filmstripimage.save(filename, 'jpg', quality=90, optimize=1) except: filmstripimage.save(miniature_filename, 'jpg', quality=90)") </code></pre> <p>How do i modify this so that it saves the new filmstrip.jpg in the same directory as I loaded the images from? And it probably has some things that are missing or wrong, anybody got a clue?</p> <p>Related question: <a href="http://stackoverflow.com/questions/334827/how-to-generate-a-filmstrip-image-in-python-from-a-folder-of-images">How to generate a filmstrip image in python from a folder of images?</a></p>
3
2008-12-03T00:22:27Z
336,001
<p>It is not an answer to your question, but It might be helpful:</p> <pre><code>#!/usr/bin/env python import Image def makefilmstrip(images, mode='RGB', color='white'): """Return a combined (filmstripped, each on top of the other) image of the images. """ width = max(img.size[0] for img in images) height = sum(img.size[1] for img in images) image = Image.new(mode, (width, height), color) left, upper = 0, 0 for img in images: image.paste(img, (left, upper)) upper += img.size[1] return image if __name__=='__main__': # Here's how it could be used: from glob import glob from optparse import OptionParser # process command-line args parser = OptionParser() parser.add_option("-o", "--output", dest="file", help="write combined image to OUTPUT") options, filepatterns = parser.parse_args() outfilename = options.file filenames = [] for files in map(glob, filepatterns): if files: filenames += files # construct image images = map(Image.open, filenames) img = makefilmstrip(images) img.save(outfilename) </code></pre> <p>Example:</p> <pre><code>$ python filmstrip.py -o output.jpg *.jpg </code></pre>
2
2008-12-03T01:32:45Z
[ "python", "image-processing", "python-imaging-library" ]
How to handle a glade project with many windows
336,013
<p>I'm working on a PyGTK/glade application that currently has 16 windows/dialogs and is about 130KB, and will eventually have around 25 windows/dialogs and be around 200KB. Currently, I'm storing all the windows in one monolithic glade file. When I run a window I call it like...</p> <pre><code>self.wTree = gtk.glade.XML("interface.glade", "WindowXYZ") </code></pre> <p>I wonder if it would be a better idea to split each window into it's own glade file. Instead of one glade file with 25 windows/dialogs I'd have 25 glade files with one window/dialog each and call it like so:</p> <pre><code>self.wTree = gtk.glade.XML("windowxyz.glade") </code></pre> <p>What do you guys think is the best way to do this? Is one method more resource intensive than another? One thing that would be nice about going to individual glade files is that naming widgets would be easier. For example, I name all my OK buttons "windowxyz_ok", but I could change it to simply "ok" instead. Makes things simpler. The downside is that it may be a bit less convenient to make changes to different windows.</p> <p>I'm open to any and all arguments. Thanks!</p>
7
2008-12-03T01:39:50Z
336,735
<p>Did you take some timings to find out whether it makes a difference? </p> <p>The problem is that, as far as I understand it, Glade always creates all widgets when it parses an XML file, so if you open the XML file and only read a single widget, you are wasting a lot of resources.</p> <p>The other problem is that you need to re-read the file if you want to have another instance of that widget.</p> <p>The way I did it before was to put all widgets that were created only once (like the about window, the main window etc) into one glade file, and separate glade files for widgets that needed to be created several times.</p>
2
2008-12-03T10:17:28Z
[ "python", "gtk", "pygtk", "glade" ]
How to handle a glade project with many windows
336,013
<p>I'm working on a PyGTK/glade application that currently has 16 windows/dialogs and is about 130KB, and will eventually have around 25 windows/dialogs and be around 200KB. Currently, I'm storing all the windows in one monolithic glade file. When I run a window I call it like...</p> <pre><code>self.wTree = gtk.glade.XML("interface.glade", "WindowXYZ") </code></pre> <p>I wonder if it would be a better idea to split each window into it's own glade file. Instead of one glade file with 25 windows/dialogs I'd have 25 glade files with one window/dialog each and call it like so:</p> <pre><code>self.wTree = gtk.glade.XML("windowxyz.glade") </code></pre> <p>What do you guys think is the best way to do this? Is one method more resource intensive than another? One thing that would be nice about going to individual glade files is that naming widgets would be easier. For example, I name all my OK buttons "windowxyz_ok", but I could change it to simply "ok" instead. Makes things simpler. The downside is that it may be a bit less convenient to make changes to different windows.</p> <p>I'm open to any and all arguments. Thanks!</p>
7
2008-12-03T01:39:50Z
337,852
<p>I use different glade files for different windows. But I keep dialog associated with a window in the same glade file. As you said, the naming problem is annoying. </p>
0
2008-12-03T16:49:09Z
[ "python", "gtk", "pygtk", "glade" ]
How to handle a glade project with many windows
336,013
<p>I'm working on a PyGTK/glade application that currently has 16 windows/dialogs and is about 130KB, and will eventually have around 25 windows/dialogs and be around 200KB. Currently, I'm storing all the windows in one monolithic glade file. When I run a window I call it like...</p> <pre><code>self.wTree = gtk.glade.XML("interface.glade", "WindowXYZ") </code></pre> <p>I wonder if it would be a better idea to split each window into it's own glade file. Instead of one glade file with 25 windows/dialogs I'd have 25 glade files with one window/dialog each and call it like so:</p> <pre><code>self.wTree = gtk.glade.XML("windowxyz.glade") </code></pre> <p>What do you guys think is the best way to do this? Is one method more resource intensive than another? One thing that would be nice about going to individual glade files is that naming widgets would be easier. For example, I name all my OK buttons "windowxyz_ok", but I could change it to simply "ok" instead. Makes things simpler. The downside is that it may be a bit less convenient to make changes to different windows.</p> <p>I'm open to any and all arguments. Thanks!</p>
7
2008-12-03T01:39:50Z
339,212
<p>In my projects, I always have one window per glade file. I'd recommend the same for your project.</p> <p>The following are the two main reasons:</p> <ul> <li>It will be faster and use less memory, since each call to gtk.glade.XML() parses the whole thing. Sure you can pass in the root argument to avoid creating the widget tree for all windows, but you'd still have to <em>parse</em> all the XML, even if you're not interested in it.</li> <li>Conceptually its easier to understand if have one toplevel per window. You easily know which filename a given dialog/window is in just by looking at the filename.</li> </ul>
9
2008-12-04T00:13:52Z
[ "python", "gtk", "pygtk", "glade" ]
How to handle a glade project with many windows
336,013
<p>I'm working on a PyGTK/glade application that currently has 16 windows/dialogs and is about 130KB, and will eventually have around 25 windows/dialogs and be around 200KB. Currently, I'm storing all the windows in one monolithic glade file. When I run a window I call it like...</p> <pre><code>self.wTree = gtk.glade.XML("interface.glade", "WindowXYZ") </code></pre> <p>I wonder if it would be a better idea to split each window into it's own glade file. Instead of one glade file with 25 windows/dialogs I'd have 25 glade files with one window/dialog each and call it like so:</p> <pre><code>self.wTree = gtk.glade.XML("windowxyz.glade") </code></pre> <p>What do you guys think is the best way to do this? Is one method more resource intensive than another? One thing that would be nice about going to individual glade files is that naming widgets would be easier. For example, I name all my OK buttons "windowxyz_ok", but I could change it to simply "ok" instead. Makes things simpler. The downside is that it may be a bit less convenient to make changes to different windows.</p> <p>I'm open to any and all arguments. Thanks!</p>
7
2008-12-03T01:39:50Z
644,722
<p>I have one glade file with 2 windows. It's about 450kb in size and I have not seen any slowdowns using libglademm with GTKmm.</p>
0
2009-03-13T21:42:47Z
[ "python", "gtk", "pygtk", "glade" ]
Python: Invalid Token
336,181
<p>Some of you may recognize this as Project Euler's problem number 11. The one with the grid.</p> <p>I'm trying to replicate the grid in a large multidimensional array, But it's giving me a syntax error and i'm not sure why</p> <pre><code>grid = [ [ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08 ], [ 49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00 ], [ 81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65 ], ... </code></pre> <p>And I get this error:</p> <pre> File "D:\development\Python\ProjectEuler\p11.py", line 3 [ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91 , 08 ], ^ SyntaxError: invalid token </pre> <p>Why is it throwing an error before the comma?</p>
13
2008-12-03T04:01:12Z
336,189
<p>I think when you start a literal number with a 0, it interprets it as an octal number and you can't have an '8' in an octal number.</p>
35
2008-12-03T04:04:50Z
[ "python", "octal" ]
Python: Invalid Token
336,181
<p>Some of you may recognize this as Project Euler's problem number 11. The one with the grid.</p> <p>I'm trying to replicate the grid in a large multidimensional array, But it's giving me a syntax error and i'm not sure why</p> <pre><code>grid = [ [ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08 ], [ 49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00 ], [ 81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65 ], ... </code></pre> <p>And I get this error:</p> <pre> File "D:\development\Python\ProjectEuler\p11.py", line 3 [ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91 , 08 ], ^ SyntaxError: invalid token </pre> <p>Why is it throwing an error before the comma?</p>
13
2008-12-03T04:01:12Z
336,229
<p>Note that the "^" symbol in the error points exactly to the erroneous column. Together with the line number it points exactly on the digit 8. This can help lead you to what Jeremy suggested.</p>
3
2008-12-03T04:42:41Z
[ "python", "octal" ]
Python: Invalid Token
336,181
<p>Some of you may recognize this as Project Euler's problem number 11. The one with the grid.</p> <p>I'm trying to replicate the grid in a large multidimensional array, But it's giving me a syntax error and i'm not sure why</p> <pre><code>grid = [ [ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91, 08 ], [ 49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 04, 56, 62, 00 ], [ 81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 03, 49, 13, 36, 65 ], ... </code></pre> <p>And I get this error:</p> <pre> File "D:\development\Python\ProjectEuler\p11.py", line 3 [ 08, 02, 22, 97, 38, 15, 00, 40, 00, 75, 04, 05, 07, 78, 52, 12, 50, 77, 91 , 08 ], ^ SyntaxError: invalid token </pre> <p>Why is it throwing an error before the comma?</p>
13
2008-12-03T04:01:12Z
337,697
<p>Just remove leading zeros.</p> <p>First zero makes number octal.</p>
1
2008-12-03T16:14:45Z
[ "python", "octal" ]
How do I handle Microsoft outlook winmail.dat? Any other surprises?
336,517
<p>Ive decided that I really dont like microsoft and their ways. Please could you give me directions on how to handle winmail.dat in emails, is there a jython library or a java library that will allow me to handle this.</p> <p>Ive just completed a email processing program, written in jython 2.2.1 on java 5. During the final load test, I realised that attachments that should have been in a standard MIME email format is now tied up in some blasted winmail.dat, which means many different outlook clients pollute the internet with this winmail.dat, so that means i need to support winmail.dat. Thus my program failed to process the data correctly.</p> <p>Please could you give a short description on what winmail.dat is and why it is here to annoy us.</p> <p>What other surprises can be expected!? what else do I have to watch out for, so far standard MIME emails are catered for. Are there any other jack in the boxes? </p> <p>Thanks so much for your time.</p>
3
2008-12-03T08:41:45Z
336,547
<p>read here:<br> <a href="http://en.wikipedia.org/wiki/TNEF" rel="nofollow">http://en.wikipedia.org/wiki/TNEF</a></p> <p>a package for parsing here:<br> <a href="https://github.com/verdammelt/tnef" rel="nofollow">https://github.com/verdammelt/tnef</a></p>
6
2008-12-03T08:59:53Z
[ "java", "python", "email", "jython", "winmail.dat" ]
How do I handle Microsoft outlook winmail.dat? Any other surprises?
336,517
<p>Ive decided that I really dont like microsoft and their ways. Please could you give me directions on how to handle winmail.dat in emails, is there a jython library or a java library that will allow me to handle this.</p> <p>Ive just completed a email processing program, written in jython 2.2.1 on java 5. During the final load test, I realised that attachments that should have been in a standard MIME email format is now tied up in some blasted winmail.dat, which means many different outlook clients pollute the internet with this winmail.dat, so that means i need to support winmail.dat. Thus my program failed to process the data correctly.</p> <p>Please could you give a short description on what winmail.dat is and why it is here to annoy us.</p> <p>What other surprises can be expected!? what else do I have to watch out for, so far standard MIME emails are catered for. Are there any other jack in the boxes? </p> <p>Thanks so much for your time.</p>
3
2008-12-03T08:41:45Z
336,550
<blockquote> <p>Please could you give a short description on what winmail.dat is and why it is here to annoy us.</p> </blockquote> <p><a href="http://support.microsoft.com/kb/138053" rel="nofollow">kb138053</a></p> <blockquote> <p>When an end user sends mail to the Internet from an Exchange Windows or Outlook client, a file attachment called Winmail.dat may be automatically added to the end of the message if the recipient's client cannot receive messages in Rich Text Format (RTF). The Winmail.dat file contains Exchange Server RTF information for the message, and may appear to the recipient as a binary file. It is not useful to non-Exchange Server recipients.</p> </blockquote> <p>If you read the kb I referenced further it gives instructions on how Exchange administrators can and <strong>should</strong> disable RTF to the internet.</p>
1
2008-12-03T09:01:25Z
[ "java", "python", "email", "jython", "winmail.dat" ]
How do I handle Microsoft outlook winmail.dat? Any other surprises?
336,517
<p>Ive decided that I really dont like microsoft and their ways. Please could you give me directions on how to handle winmail.dat in emails, is there a jython library or a java library that will allow me to handle this.</p> <p>Ive just completed a email processing program, written in jython 2.2.1 on java 5. During the final load test, I realised that attachments that should have been in a standard MIME email format is now tied up in some blasted winmail.dat, which means many different outlook clients pollute the internet with this winmail.dat, so that means i need to support winmail.dat. Thus my program failed to process the data correctly.</p> <p>Please could you give a short description on what winmail.dat is and why it is here to annoy us.</p> <p>What other surprises can be expected!? what else do I have to watch out for, so far standard MIME emails are catered for. Are there any other jack in the boxes? </p> <p>Thanks so much for your time.</p>
3
2008-12-03T08:41:45Z
336,551
<p>so when i see this in email Content-Type: "application/ms-tnef" </p> <p>I use this: <a href="http://www.freeutils.net/source/jtnef/" rel="nofollow">http://www.freeutils.net/source/jtnef/</a></p>
1
2008-12-03T09:01:51Z
[ "java", "python", "email", "jython", "winmail.dat" ]
How do I handle Microsoft outlook winmail.dat? Any other surprises?
336,517
<p>Ive decided that I really dont like microsoft and their ways. Please could you give me directions on how to handle winmail.dat in emails, is there a jython library or a java library that will allow me to handle this.</p> <p>Ive just completed a email processing program, written in jython 2.2.1 on java 5. During the final load test, I realised that attachments that should have been in a standard MIME email format is now tied up in some blasted winmail.dat, which means many different outlook clients pollute the internet with this winmail.dat, so that means i need to support winmail.dat. Thus my program failed to process the data correctly.</p> <p>Please could you give a short description on what winmail.dat is and why it is here to annoy us.</p> <p>What other surprises can be expected!? what else do I have to watch out for, so far standard MIME emails are catered for. Are there any other jack in the boxes? </p> <p>Thanks so much for your time.</p>
3
2008-12-03T08:41:45Z
337,348
<p>I have had good luck with <a href="http://www.biblet.freeserve.co.uk/" rel="nofollow">wmdecode</a> on Windows. Granted, it's an EXE, not a java project. But it could be useful if you run into WINMAIL.DAT files that other solutions can't decode.</p>
0
2008-12-03T14:45:16Z
[ "java", "python", "email", "jython", "winmail.dat" ]
How do I handle Microsoft outlook winmail.dat? Any other surprises?
336,517
<p>Ive decided that I really dont like microsoft and their ways. Please could you give me directions on how to handle winmail.dat in emails, is there a jython library or a java library that will allow me to handle this.</p> <p>Ive just completed a email processing program, written in jython 2.2.1 on java 5. During the final load test, I realised that attachments that should have been in a standard MIME email format is now tied up in some blasted winmail.dat, which means many different outlook clients pollute the internet with this winmail.dat, so that means i need to support winmail.dat. Thus my program failed to process the data correctly.</p> <p>Please could you give a short description on what winmail.dat is and why it is here to annoy us.</p> <p>What other surprises can be expected!? what else do I have to watch out for, so far standard MIME emails are catered for. Are there any other jack in the boxes? </p> <p>Thanks so much for your time.</p>
3
2008-12-03T08:41:45Z
11,262,382
<p>Topic closed, but for future purposes: <a href="http://poi.apache.org/" rel="nofollow">Apache POI</a> project (Java API for Microsoft Documents) is launching a version (3.8) that is capable to decode TNEF files. I tested it and worked very well, even the beta version. You can found it <a href="http://poi.apache.org/hmef/index.html" rel="nofollow">here</a>.</p> <p>To use with maven (june 2016 - might change later when it is no longer in the scratchpad):</p> <pre><code> &lt;dependency&gt; &lt;groupId&gt;org.apache.poi&lt;/groupId&gt; &lt;artifactId&gt;poi-scratchpad&lt;/artifactId&gt; &lt;version&gt;3.14&lt;/version&gt; &lt;/dependency&gt; </code></pre>
3
2012-06-29T13:07:48Z
[ "java", "python", "email", "jython", "winmail.dat" ]
How do I handle Microsoft outlook winmail.dat? Any other surprises?
336,517
<p>Ive decided that I really dont like microsoft and their ways. Please could you give me directions on how to handle winmail.dat in emails, is there a jython library or a java library that will allow me to handle this.</p> <p>Ive just completed a email processing program, written in jython 2.2.1 on java 5. During the final load test, I realised that attachments that should have been in a standard MIME email format is now tied up in some blasted winmail.dat, which means many different outlook clients pollute the internet with this winmail.dat, so that means i need to support winmail.dat. Thus my program failed to process the data correctly.</p> <p>Please could you give a short description on what winmail.dat is and why it is here to annoy us.</p> <p>What other surprises can be expected!? what else do I have to watch out for, so far standard MIME emails are catered for. Are there any other jack in the boxes? </p> <p>Thanks so much for your time.</p>
3
2008-12-03T08:41:45Z
16,732,057
<p>Just a comment about tinnef: Not everything that is called winmail.dat is ordinary TNEF. Meeting inviations sent from Outlook are not, thus most TNEF decoders will fail in this case.<br> On Mac OSX, I found "Letter Opener" to be one of the rare programs that can open such attachments. Funny enough, they can also contain rtf documents. </p> <p><a href="http://www.restoroot.org/LetterOpenerPro" rel="nofollow">http://www.restoroot.org/LetterOpenerPro</a></p>
0
2013-05-24T09:45:49Z
[ "java", "python", "email", "jython", "winmail.dat" ]
Django FormWizard and Admin application
336,753
<p>I have a series of forms that I need a user to complete in sequence, which is perfect for the formwizard app. However, I've some need of the admin application also and would like to set the whole thing up to trigger several forms within the admin app. </p> <p>Is it possible/easy to integrate a 'formwizard' into the admin application?</p> <p>If not, is extending the admin template a viable option and hooking the rest up manually? Opinions? </p> <p>Update: Some clarity in my 'problem'.</p> <p>I wanted to use the admin app as I was thinking I only needed basic modelforms - one perhaps split across many forms, which would have been the role of formwizard.</p> <p>What I have:</p> <p>Form 1: 10 yes/no questions (each yes corresponds to a new form that needs to be filled out)<br /> if yes is ticked, the corresponding forms are put into a formwizard and displayed for the user to complete. </p> <p><hr /></p> <p>However the suggested option (modelforms + styling) would take care of the majority of my concerns I guess - and is the seemingly simpler solution.</p>
3
2008-12-03T10:29:08Z
336,906
<p>You <em>do</em> have the source, and it <em>is</em> Python, so... you can read the admin application source to see what options it has.</p> <p>Look at <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-admin-templates" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/contrib/admin/#overriding-admin-templates</a>.<br /> It appears that you can override templates easily. They even provide step-by-step instructions for adding your own customized admin templates.</p>
-3
2008-12-03T11:59:21Z
[ "python", "django", "forms" ]
Django FormWizard and Admin application
336,753
<p>I have a series of forms that I need a user to complete in sequence, which is perfect for the formwizard app. However, I've some need of the admin application also and would like to set the whole thing up to trigger several forms within the admin app. </p> <p>Is it possible/easy to integrate a 'formwizard' into the admin application?</p> <p>If not, is extending the admin template a viable option and hooking the rest up manually? Opinions? </p> <p>Update: Some clarity in my 'problem'.</p> <p>I wanted to use the admin app as I was thinking I only needed basic modelforms - one perhaps split across many forms, which would have been the role of formwizard.</p> <p>What I have:</p> <p>Form 1: 10 yes/no questions (each yes corresponds to a new form that needs to be filled out)<br /> if yes is ticked, the corresponding forms are put into a formwizard and displayed for the user to complete. </p> <p><hr /></p> <p>However the suggested option (modelforms + styling) would take care of the majority of my concerns I guess - and is the seemingly simpler solution.</p>
3
2008-12-03T10:29:08Z
337,753
<p>There's a <em>lot</em> that you can do, but you'd need to be more specific about what you mean by "integrate a formwizard into the admin app" and "trigger several forms within the admin app."</p> <p>The admin app at its core is basically just a wrapper around a bunch of stock ModelForms, so if you just build a formwizard using ModelForms and slap the admin styling on it, you may be 80% of the way there.</p>
1
2008-12-03T16:27:26Z
[ "python", "django", "forms" ]
How to implement a minimal server for AJAX in Python?
336,866
<p>I want to create a very simple HTML/AJAX based GUI for a Python program. So the frontend is a HTML page which communicates with the program via AJAX. Can you give me a minimal implementation for the server-side using the python <code>SimpleHTTPServer.SimpleHTTPRequestHandler</code>?</p> <p>A simple example would be a textfield and a button. When the button is pressed the content of the field is send to the server which then sends back a corresponding answer. I am aware that there are many powerful solutions for this in Python, but I would like to keep this very simple. I already found some nice examples for such a server (e.g. <a href="http://msdl.cs.mcgill.ca/people/julien/04Ajax">here</a>), but so far I could not come up with a truly minimal one.</p> <p>In case you wonder why I want to implement the GUI in such a way: My focus for this application is to display lots of data in a nice layout with only minimal interaction - so using HTML+CSS seems most convenient (and I have been already using it for non-interactive data display).</p>
35
2008-12-03T11:37:28Z
336,894
<p>Use the <a href="https://docs.python.org/2/library/wsgiref.html#module-wsgiref.simple_server" rel="nofollow">WSGI reference implementation</a>. In the long run, you'll be happier.</p> <pre><code>from wsgiref.simple_server import make_server, demo_app httpd = make_server('', 8000, demo_app) print "Serving HTTP on port 8000..." # Respond to requests until process is killed httpd.serve_forever() </code></pre> <p>The demo_app is relatively easy to write; it handles your Ajax requests.</p>
9
2008-12-03T11:50:13Z
[ "python", "ajax", "user-interface" ]
How to implement a minimal server for AJAX in Python?
336,866
<p>I want to create a very simple HTML/AJAX based GUI for a Python program. So the frontend is a HTML page which communicates with the program via AJAX. Can you give me a minimal implementation for the server-side using the python <code>SimpleHTTPServer.SimpleHTTPRequestHandler</code>?</p> <p>A simple example would be a textfield and a button. When the button is pressed the content of the field is send to the server which then sends back a corresponding answer. I am aware that there are many powerful solutions for this in Python, but I would like to keep this very simple. I already found some nice examples for such a server (e.g. <a href="http://msdl.cs.mcgill.ca/people/julien/04Ajax">here</a>), but so far I could not come up with a truly minimal one.</p> <p>In case you wonder why I want to implement the GUI in such a way: My focus for this application is to display lots of data in a nice layout with only minimal interaction - so using HTML+CSS seems most convenient (and I have been already using it for non-interactive data display).</p>
35
2008-12-03T11:37:28Z
338,519
<p>O.K., I think I can now answer my own question. Here is an example implementation for calculating the square of a number on the server. Please let me know if there are any improvements or misconceptions.</p> <p>the python server file:</p> <pre><code>import threading import webbrowser import BaseHTTPServer import SimpleHTTPServer FILE = 'frontend.html' PORT = 8080 class TestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): """The test example handler.""" def do_POST(self): """Handle a post request by returning the square of the number.""" length = int(self.headers.getheader('content-length')) data_string = self.rfile.read(length) try: result = int(data_string) ** 2 except: result = 'error' self.wfile.write(result) def open_browser(): """Start a browser after waiting for half a second.""" def _open_browser(): webbrowser.open('http://localhost:%s/%s' % (PORT, FILE)) thread = threading.Timer(0.5, _open_browser) thread.start() def start_server(): """Start the server.""" server_address = ("", PORT) server = BaseHTTPServer.HTTPServer(server_address, TestHandler) server.serve_forever() if __name__ == "__main__": open_browser() start_server() </code></pre> <p>...and the HTML file (I call it 'frontend.html', unfortunately the name has to appear in the JavaScript code as well):</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;AJAX test&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;script type="text/javascript"&gt; function xml_http_post(url, data, callback) { var req = false; try { // Firefox, Opera 8.0+, Safari req = new XMLHttpRequest(); } catch (e) { // Internet Explorer try { req = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { req = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { alert("Your browser does not support AJAX!"); return false; } } } req.open("POST", url, true); req.onreadystatechange = function() { if (req.readyState == 4) { callback(req); } } req.send(data); } function test_button() { var data = document.test_form.test_text.value; xml_http_post("frontend.html", data, test_handle) } function test_handle(req) { var elem = document.getElementById('test_result') elem.innerHTML = req.responseText } &lt;/script&gt; &lt;form name=test_form&gt; sqr( &lt;input type="text" name="test_text" value="0" size="4"&gt; ) = &lt;span id="test_result"&gt;0&lt;/span&gt; &lt;input type=button onClick="test_button();" value="start" title="start"&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Of course it would be much more convenient to use <a href="http://api.jquery.com/jQuery.ajax/">jQuery</a> for the XML request, but in the interest of simplicity I'll leave it like that.</p> <p>Finally an alternative implementation using WSGI (unfortunately I didn't see a way to fall back on the standard file-serving handler if the request is not a POST):</p> <pre><code>import threading import webbrowser from wsgiref.simple_server import make_server FILE = 'frontend.html' PORT = 8080 def test_app(environ, start_response): if environ['REQUEST_METHOD'] == 'POST': try: request_body_size = int(environ['CONTENT_LENGTH']) request_body = environ['wsgi.input'].read(request_body_size) except (TypeError, ValueError): request_body = "0" try: response_body = str(int(request_body) ** 2) except: response_body = "error" status = '200 OK' headers = [('Content-type', 'text/plain')] start_response(status, headers) return [response_body] else: response_body = open(FILE).read() status = '200 OK' headers = [('Content-type', 'text/html'), ('Content-Length', str(len(response_body)))] start_response(status, headers) return [response_body] def open_browser(): """Start a browser after waiting for half a second.""" def _open_browser(): webbrowser.open('http://localhost:%s/%s' % (PORT, FILE)) thread = threading.Timer(0.5, _open_browser) thread.start() def start_server(): """Start the server.""" httpd = make_server("", PORT, test_app) httpd.serve_forever() if __name__ == "__main__": open_browser() start_server() </code></pre>
45
2008-12-03T20:01:15Z
[ "python", "ajax", "user-interface" ]
How to implement a minimal server for AJAX in Python?
336,866
<p>I want to create a very simple HTML/AJAX based GUI for a Python program. So the frontend is a HTML page which communicates with the program via AJAX. Can you give me a minimal implementation for the server-side using the python <code>SimpleHTTPServer.SimpleHTTPRequestHandler</code>?</p> <p>A simple example would be a textfield and a button. When the button is pressed the content of the field is send to the server which then sends back a corresponding answer. I am aware that there are many powerful solutions for this in Python, but I would like to keep this very simple. I already found some nice examples for such a server (e.g. <a href="http://msdl.cs.mcgill.ca/people/julien/04Ajax">here</a>), but so far I could not come up with a truly minimal one.</p> <p>In case you wonder why I want to implement the GUI in such a way: My focus for this application is to display lots of data in a nice layout with only minimal interaction - so using HTML+CSS seems most convenient (and I have been already using it for non-interactive data display).</p>
35
2008-12-03T11:37:28Z
26,004,385
<p>Thanks for a very intuitive example @nikow I was trying to follow your example, but did get an error:</p> <p>(process:10281): GLib-CRITICAL **: g_slice_set_config: assertion 'sys_page_size == 0' failed</p> <p>I modified your code to meet my needs.</p> <pre><code>webbrowser.open('file:///home/jon/workspace/webpages/frontend_example/%s' % FILE) // skipped the port part httpd = make_server("", 8080, test_app) // hardcoded it here. </code></pre> <p>does my html file has to be put on the webserver ? I have not put it there yet !.</p>
0
2014-09-23T20:42:27Z
[ "python", "ajax", "user-interface" ]
Python optparse metavar
336,963
<p>I am not sure what <code>optparse</code>'s <code>metavar</code> parameter is used for. I see it is used all around, but I can't see its use.</p> <p>Can someone make it clear to me? Thanks.</p>
21
2008-12-03T12:36:12Z
336,975
<p>metavar seems to be used for generating help : <a href="http://www.python.org/doc/2.5.2/lib/optparse-generating-help.html">http://www.python.org/doc/2.5.2/lib/optparse-generating-help.html</a></p>
5
2008-12-03T12:42:52Z
[ "python", "optparse" ]
Python optparse metavar
336,963
<p>I am not sure what <code>optparse</code>'s <code>metavar</code> parameter is used for. I see it is used all around, but I can't see its use.</p> <p>Can someone make it clear to me? Thanks.</p>
21
2008-12-03T12:36:12Z
336,992
<p>As @<a href="#336975">Guillaume</a> says, it's used for generating help. If you want to have an option that takes an argument, such as a filename, you can add the <code>metavar</code> parameter to the <code>add_option</code> call so your preferred argument name/descriptor is output in the help message. From <a href="http://docs.python.org/library/optparse.html#generating-help">the current module documentation</a>:</p> <pre><code>usage = "usage: %prog [options] arg1 arg2" parser = OptionParser(usage=usage) parser.add_option("-f", "--filename", metavar="FILE", help="write output to FILE"), </code></pre> <p>would produce help like this:</p> <pre><code>usage: &lt;yourscript&gt; [options] arg1 arg2 options: -f FILE, --filename=FILE </code></pre> <p>The "FILE" after the "-f" and the "--filename" comes from the metavar.</p>
25
2008-12-03T12:48:58Z
[ "python", "optparse" ]
Python optparse metavar
336,963
<p>I am not sure what <code>optparse</code>'s <code>metavar</code> parameter is used for. I see it is used all around, but I can't see its use.</p> <p>Can someone make it clear to me? Thanks.</p>
21
2008-12-03T12:36:12Z
3,882,232
<p><code>metavar</code> is a variable used for print in the screen after option. Usually used for suggestion input after option are <code>FILE</code> or <code>INT</code> or <code>STRING</code> to user. Without <code>metavar</code>, <code>optparse</code> will print <code>dest</code> value after option you've been added.</p>
0
2010-10-07T13:43:56Z
[ "python", "optparse" ]
Python optparse metavar
336,963
<p>I am not sure what <code>optparse</code>'s <code>metavar</code> parameter is used for. I see it is used all around, but I can't see its use.</p> <p>Can someone make it clear to me? Thanks.</p>
21
2008-12-03T12:36:12Z
11,416,894
<p>There's another meaningful use of metavar where one desires to use 'dest' as the argument lookup-tag but mask the help message by metavar. (E.g. sometimes handy when using subparsers). (As indicated in the comment of <a href="http://stackoverflow.com/users/10661/s-lott">S.Lott</a>).</p> <pre><code>parser.add_argument( 'my_fancy_tag', help='Specify destination', metavar='helpful_message' ) </code></pre> <p>or equally</p> <pre><code>parser.add_argument( dest='my_fancy_tag', help='Specify destination', metavar='helpful_message' ) </code></pre> <p>Help will show the metavar:</p> <pre><code>./parse.py -h usage: parser [-h] destination positional arguments: helpful_message Specify destination </code></pre> <p>but dest will store the fancy_tag in Namespace:</p> <pre><code>./parse.py test Namespace(my_fancy_tag='test') </code></pre>
0
2012-07-10T15:37:11Z
[ "python", "optparse" ]
Python optparse metavar
336,963
<p>I am not sure what <code>optparse</code>'s <code>metavar</code> parameter is used for. I see it is used all around, but I can't see its use.</p> <p>Can someone make it clear to me? Thanks.</p>
21
2008-12-03T12:36:12Z
26,905,930
<p>It's now preferable to use the <a href="https://docs.python.org/library/argparse.html" rel="nofollow">argparse</a> library instead of optparse.</p> <p>Reasons why are given <a href="http://stackoverflow.com/questions/3217673/why-use-argparse-rather-than-optparse">here</a>.</p>
0
2014-11-13T09:55:29Z
[ "python", "optparse" ]
Python: item for item until stopterm in item?
337,223
<p>Disclaimer: I'm fairly new to python!</p> <p>If I want all the lines of a file until (edit: and including) the line containing some string <code>stopterm</code>, is there a way of using the list syntax for it? I was hoping there would be something like:</p> <pre><code>usefullines = [line for line in file until stopterm in line] </code></pre> <p>For now, I've got</p> <pre><code>usefullines = [] for line in file: usefullines.append(line) if stopterm in line: break </code></pre> <p>It's not the end of the world, but since there rest of Python syntax is so straightforward, I was hoping for a 1 thought->1 Python line mapping.</p>
3
2008-12-03T14:11:57Z
337,247
<h2>Forget this</h2> <p>Leaving the answer, but marking it community. See <a href="http://stackoverflow.com/users/28604/steven-huwig">Stewen Huwig</a>'s answer for the <strong>correct</strong> way to do this.</p> <p><hr /></p> <p>Well, [x for x in enumerable] will run until enumerable doesn't produce data any more, the if-part will simply allow you to filter along the way.</p> <p>What you can do is add a function, and filter your enumerable through it:</p> <pre><code>def enum_until(source, until_criteria): for k in source: if until_criteria(k): break; yield k; def enum_while(source, while_criteria): for k in source: if not while_criteria(k): break; yield k; l1 = [k for k in enum_until(xrange(1, 100000), lambda y: y == 100)]; l2 = [k for k in enum_while(xrange(1, 100000), lambda y: y &lt; 100)]; print l1; print l2; </code></pre> <p>Of course, it doesn't look as nice as what you wanted...</p>
1
2008-12-03T14:20:10Z
[ "python" ]
Python: item for item until stopterm in item?
337,223
<p>Disclaimer: I'm fairly new to python!</p> <p>If I want all the lines of a file until (edit: and including) the line containing some string <code>stopterm</code>, is there a way of using the list syntax for it? I was hoping there would be something like:</p> <pre><code>usefullines = [line for line in file until stopterm in line] </code></pre> <p>For now, I've got</p> <pre><code>usefullines = [] for line in file: usefullines.append(line) if stopterm in line: break </code></pre> <p>It's not the end of the world, but since there rest of Python syntax is so straightforward, I was hoping for a 1 thought->1 Python line mapping.</p>
3
2008-12-03T14:11:57Z
337,279
<p>" I was hoping for a 1 thought->1 Python line mapping." Wouldn't we all love a programming language that somehow mirrored our natural language?</p> <p>You can achieve that, you just need to define your unique thoughts once. Then you have the 1:1 mapping you were hoping for.</p> <pre><code>def usefulLines( aFile ): for line in aFile: yield line if line == stopterm: break </code></pre> <p>Is pretty much it.</p> <pre><code>for line in usefulLines( aFile ): # process a line, knowing it occurs BEFORE stopterm. </code></pre> <p>There are more general approaches. The <code>lassevk</code> answers with <code>enum_while</code> and <code>enum_until</code> are generalizations of this simple design pattern.</p>
5
2008-12-03T14:26:43Z
[ "python" ]
Python: item for item until stopterm in item?
337,223
<p>Disclaimer: I'm fairly new to python!</p> <p>If I want all the lines of a file until (edit: and including) the line containing some string <code>stopterm</code>, is there a way of using the list syntax for it? I was hoping there would be something like:</p> <pre><code>usefullines = [line for line in file until stopterm in line] </code></pre> <p>For now, I've got</p> <pre><code>usefullines = [] for line in file: usefullines.append(line) if stopterm in line: break </code></pre> <p>It's not the end of the world, but since there rest of Python syntax is so straightforward, I was hoping for a 1 thought->1 Python line mapping.</p>
3
2008-12-03T14:11:57Z
337,285
<pre><code>from itertools import takewhile usefullines = takewhile(lambda x: not re.search(stopterm, x), lines) from itertools import takewhile usefullines = takewhile(lambda x: stopterm not in x, lines) </code></pre> <p>Here's a way that keeps the stopterm line:</p> <pre><code>def useful_lines(lines, stopterm): for line in lines: if stopterm in line: yield line break yield line usefullines = useful_lines(lines, stopterm) # or... for line in useful_lines(lines, stopterm): # ... do stuff pass </code></pre>
10
2008-12-03T14:28:58Z
[ "python" ]
Python: item for item until stopterm in item?
337,223
<p>Disclaimer: I'm fairly new to python!</p> <p>If I want all the lines of a file until (edit: and including) the line containing some string <code>stopterm</code>, is there a way of using the list syntax for it? I was hoping there would be something like:</p> <pre><code>usefullines = [line for line in file until stopterm in line] </code></pre> <p>For now, I've got</p> <pre><code>usefullines = [] for line in file: usefullines.append(line) if stopterm in line: break </code></pre> <p>It's not the end of the world, but since there rest of Python syntax is so straightforward, I was hoping for a 1 thought->1 Python line mapping.</p>
3
2008-12-03T14:11:57Z
337,336
<p>I think it's fine to keep it that way. Sophisticated one-liner are not really pythonic, and since Guido had to put a limit somewhere, I guess this is it...</p>
1
2008-12-03T14:42:23Z
[ "python" ]
Python: item for item until stopterm in item?
337,223
<p>Disclaimer: I'm fairly new to python!</p> <p>If I want all the lines of a file until (edit: and including) the line containing some string <code>stopterm</code>, is there a way of using the list syntax for it? I was hoping there would be something like:</p> <pre><code>usefullines = [line for line in file until stopterm in line] </code></pre> <p>For now, I've got</p> <pre><code>usefullines = [] for line in file: usefullines.append(line) if stopterm in line: break </code></pre> <p>It's not the end of the world, but since there rest of Python syntax is so straightforward, I was hoping for a 1 thought->1 Python line mapping.</p>
3
2008-12-03T14:11:57Z
337,586
<p>That itertools solution is neat. I have earlier been amazed by itertools.groupby, one handy tool.</p> <p>But still i was just tinkering if I could do this without itertools. So here it is (There is one assumption and one drawback though: the file is not huge and its goes for one extra complete iteration over the lines, respectively.)</p> <p>I created a sample file named "try":</p> <pre><code>hello world happy day bye </code></pre> <p>once you read the file and have the lines in a variable name lines:</p> <pre><code>lines=open('./try').readlines() </code></pre> <p>then </p> <pre><code> print [each for each in lines if lines.index(each)&lt;=[lines.index(line) for line in lines if 'happy' in line][0]] </code></pre> <p>gives the result:</p> <pre><code>['hello\n', 'world\n', 'happy\n'] </code></pre> <p>and </p> <pre><code>print [each for each in lines if lines.index(each)&lt;=[lines.index(line) for line in lines if 'day' in line][0]] </code></pre> <p>gives the result:</p> <pre><code>['hello\n', 'world\n', 'happy\n', 'day\n'] </code></pre> <p>So you got the last line - the stop term line also included.</p>
2
2008-12-03T15:48:06Z
[ "python" ]
Python: item for item until stopterm in item?
337,223
<p>Disclaimer: I'm fairly new to python!</p> <p>If I want all the lines of a file until (edit: and including) the line containing some string <code>stopterm</code>, is there a way of using the list syntax for it? I was hoping there would be something like:</p> <pre><code>usefullines = [line for line in file until stopterm in line] </code></pre> <p>For now, I've got</p> <pre><code>usefullines = [] for line in file: usefullines.append(line) if stopterm in line: break </code></pre> <p>It's not the end of the world, but since there rest of Python syntax is so straightforward, I was hoping for a 1 thought->1 Python line mapping.</p>
3
2008-12-03T14:11:57Z
337,886
<p>I'd go with <a href="http://stackoverflow.com/questions/337223/python-item-for-item-until-stopterm-in-item#337285">Steven Huwig's</a> or <a href="http://stackoverflow.com/questions/337223/python-item-for-item-until-stopterm-in-item#337279">S.Lott's</a> solutions for real usage, but as a slightly hacky solution, here's one way to obtain this behaviour:</p> <pre><code>def stop(): raise StopIteration() usefullines = list(stop() if stopterm in line else line for line in file) </code></pre> <p>It's slightly abusing the fact that anything that raises StopIteration will abort the current iteration (here the generator expression) and uglier to read than your desired syntax, but will work.</p>
0
2008-12-03T16:57:50Z
[ "python" ]
How to get a row-by-row MySQL ResultSet in python
337,479
<p>MySQL ResultSets are by default retrieved completely from the server before any work can be done. In cases of huge result sets this becomes unusable. I would like instead to actually retrieve the rows one by one from the server.</p> <p>In Java, following the instructions <a href="http://dev.mysql.com/doc/refman/5.1/en/connector-j-reference-implementation-notes.html">here</a> (under "ResultSet"), I create a statement like this:</p> <pre><code>stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY); stmt.setFetchSize(Integer.MIN_VALUE); </code></pre> <p>This works nicely in Java. My question is: is there a way to do the same in python?</p> <p>One thing I tried is to limit the query to a 1000 rows at a time, like this:</p> <pre><code>start_row = 0 while True: cursor = conn.cursor() cursor.execute("SELECT item FROM items LIMIT %d,1000" % start_row) rows = cursor.fetchall() if not rows: break start_row += 1000 # Do something with rows... </code></pre> <p>However, this seems to get slower the higher start_row is.</p> <p>And no, using <code>fetchone()</code> instead of <code>fetchall()</code> doesn't change anything.</p> <h2>Clarification:</h2> <p>The naive code I use to reproduce this problem looks like this:</p> <pre><code>import MySQLdb conn = MySQLdb.connect(user="user", passwd="password", db="mydb") cur = conn.cursor() print "Executing query" cur.execute("SELECT * FROM bigtable"); print "Starting loop" row = cur.fetchone() while row is not None: print ", ".join([str(c) for c in row]) row = cur.fetchone() cur.close() conn.close() </code></pre> <p>On a ~700,000 rows table, this code runs quickly. But on a ~9,000,000 rows table it prints "Executing Query" and then hangs for a long long time. That is why it makes no difference if I use <code>fetchone()</code> or <code>fetchall()</code>.</p>
41
2008-12-03T15:23:49Z
337,560
<p>Did you try this version of fetchone? Or something different?</p> <pre><code>row = cursor.fetchone() while row is not None: # process row = cursor.fetchone() </code></pre> <p>Also, did you try this?</p> <pre><code> row = cursor.fetchmany(size=1) while row is not None: # process row = cursor.fetchmany( size=1 ) </code></pre> <p>Not all drivers support these, so you may have gotten errors or found them too slow.</p> <p><hr /></p> <p>Edit.</p> <p>When it hangs on execute, you're waiting for the database. That's not a row-by-row Python thing; that's a MySQL thing. </p> <p>MySQL prefers to fetch all rows as part of it's own cache management. This is turned off by providing a the fetch_size of Integer.MIN_VALUE (-2147483648L).</p> <p>The question is, what part of the Python DBAPI becomes the equivalent of the JDBC fetch_size?</p> <p>I think it might be the arraysize attribute of the cursor. Try</p> <pre><code>cursor.arraysize=-2**31 </code></pre> <p>And see if that forces MySQL to stream the result set instead of caching it.</p>
6
2008-12-03T15:40:16Z
[ "python", "mysql" ]
How to get a row-by-row MySQL ResultSet in python
337,479
<p>MySQL ResultSets are by default retrieved completely from the server before any work can be done. In cases of huge result sets this becomes unusable. I would like instead to actually retrieve the rows one by one from the server.</p> <p>In Java, following the instructions <a href="http://dev.mysql.com/doc/refman/5.1/en/connector-j-reference-implementation-notes.html">here</a> (under "ResultSet"), I create a statement like this:</p> <pre><code>stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY); stmt.setFetchSize(Integer.MIN_VALUE); </code></pre> <p>This works nicely in Java. My question is: is there a way to do the same in python?</p> <p>One thing I tried is to limit the query to a 1000 rows at a time, like this:</p> <pre><code>start_row = 0 while True: cursor = conn.cursor() cursor.execute("SELECT item FROM items LIMIT %d,1000" % start_row) rows = cursor.fetchall() if not rows: break start_row += 1000 # Do something with rows... </code></pre> <p>However, this seems to get slower the higher start_row is.</p> <p>And no, using <code>fetchone()</code> instead of <code>fetchall()</code> doesn't change anything.</p> <h2>Clarification:</h2> <p>The naive code I use to reproduce this problem looks like this:</p> <pre><code>import MySQLdb conn = MySQLdb.connect(user="user", passwd="password", db="mydb") cur = conn.cursor() print "Executing query" cur.execute("SELECT * FROM bigtable"); print "Starting loop" row = cur.fetchone() while row is not None: print ", ".join([str(c) for c in row]) row = cur.fetchone() cur.close() conn.close() </code></pre> <p>On a ~700,000 rows table, this code runs quickly. But on a ~9,000,000 rows table it prints "Executing Query" and then hangs for a long long time. That is why it makes no difference if I use <code>fetchone()</code> or <code>fetchall()</code>.</p>
41
2008-12-03T15:23:49Z
337,706
<p>I think you have to connect passing <code>cursorclass = MySQLdb.cursors.SSCursor</code>:</p> <pre><code> MySQLdb.connect(user="user", passwd="password", db="mydb", cursorclass = MySQLdb.cursors.SSCursor ) </code></pre> <p>The default cursor fetches all the data at once, even if you don't use <code>fetchall</code>.</p> <p>Edit: <code>SSCursor</code> or any other cursor class that supports server side resultsets - check the module docs on <code>MySQLdb.cursors</code>.</p>
45
2008-12-03T16:17:12Z
[ "python", "mysql" ]
How to get a row-by-row MySQL ResultSet in python
337,479
<p>MySQL ResultSets are by default retrieved completely from the server before any work can be done. In cases of huge result sets this becomes unusable. I would like instead to actually retrieve the rows one by one from the server.</p> <p>In Java, following the instructions <a href="http://dev.mysql.com/doc/refman/5.1/en/connector-j-reference-implementation-notes.html">here</a> (under "ResultSet"), I create a statement like this:</p> <pre><code>stmt = conn.createStatement(java.sql.ResultSet.TYPE_FORWARD_ONLY, java.sql.ResultSet.CONCUR_READ_ONLY); stmt.setFetchSize(Integer.MIN_VALUE); </code></pre> <p>This works nicely in Java. My question is: is there a way to do the same in python?</p> <p>One thing I tried is to limit the query to a 1000 rows at a time, like this:</p> <pre><code>start_row = 0 while True: cursor = conn.cursor() cursor.execute("SELECT item FROM items LIMIT %d,1000" % start_row) rows = cursor.fetchall() if not rows: break start_row += 1000 # Do something with rows... </code></pre> <p>However, this seems to get slower the higher start_row is.</p> <p>And no, using <code>fetchone()</code> instead of <code>fetchall()</code> doesn't change anything.</p> <h2>Clarification:</h2> <p>The naive code I use to reproduce this problem looks like this:</p> <pre><code>import MySQLdb conn = MySQLdb.connect(user="user", passwd="password", db="mydb") cur = conn.cursor() print "Executing query" cur.execute("SELECT * FROM bigtable"); print "Starting loop" row = cur.fetchone() while row is not None: print ", ".join([str(c) for c in row]) row = cur.fetchone() cur.close() conn.close() </code></pre> <p>On a ~700,000 rows table, this code runs quickly. But on a ~9,000,000 rows table it prints "Executing Query" and then hangs for a long long time. That is why it makes no difference if I use <code>fetchone()</code> or <code>fetchall()</code>.</p>
41
2008-12-03T15:23:49Z
337,922
<p>The limit/offset solution runs in quadratic time because mysql has to rescan the rows to find the offset. As you suspected, the default cursor stores the entire result set on the client, which may consume a lot of memory.</p> <p>Instead you can use a server side cursor, which keeps the query running and fetches results as necessary. The cursor class can be customized by supplying a default to the connection call itself, or by supplying a class to the cursor method each time.</p> <pre><code>from MySQLdb import cursors cursor = conn.cursor(cursors.SSCursor) </code></pre> <p>But that's not the whole story. In addition to storing the mysql result, the default client-side cursor actually fetches every row regardless. This behavior is undocumented, and very unfortunate. It means full python objects are created for all rows, which consumes far more memory than the original mysql result.</p> <p>In most cases, a result stored on the client wrapped as an iterator would yield the best speed with reasonable memory usage. But you'll have to roll your own if you want that.</p>
16
2008-12-03T17:09:52Z
[ "python", "mysql" ]