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
list
Redirect print in Python: val = print(arg) to output mixed iterable to file
2,476,931
<p>So lets say I have an incredibly nested iterable of lists/dictionaries. I would like to print them to a file as easily as possible. Why can't I just redirect print to a file?</p> <p><code>val = print(arg)</code> gets a SyntaxError.</p> <p>Is there a way to access stdinput?</p> <p>And why does print take foreve...
2
2010-03-19T11:51:48Z
2,479,307
<p>You don't typically use <code>print</code> for writing to a file (though you technically can). You would use a file object for this.</p> <pre><code>with open(filename, 'w') as f: f.write(repr(your_thingy)) </code></pre> <p>If <code>print</code> is taking forever to display a massive string, it is likely that i...
1
2010-03-19T17:27:17Z
[ "python", "list", "dictionary", "iterable" ]
Redirect print in Python: val = print(arg) to output mixed iterable to file
2,476,931
<p>So lets say I have an incredibly nested iterable of lists/dictionaries. I would like to print them to a file as easily as possible. Why can't I just redirect print to a file?</p> <p><code>val = print(arg)</code> gets a SyntaxError.</p> <p>Is there a way to access stdinput?</p> <p>And why does print take foreve...
2
2010-03-19T11:51:48Z
4,110,683
<p>I tried both examples with no success using python 2.7</p> <p>To begin I created a file in C:\goat.text using notepad</p> <p>Next I tried the following</p> <p><strong>import sys</strong></p> <p><strong>print>>"C:\goat.txt", "test"</strong> error AttributeError: 'str' object has no attribute 'write'</p> <p><stro...
0
2010-11-05T22:38:26Z
[ "python", "list", "dictionary", "iterable" ]
Python utf-8, howto align printout
2,476,953
<p>I have a array containing japanese caracters as well as "normal". How do I align the printout of these?</p> <pre><code>#!/usr/bin/python # coding=utf-8 a1=['する', 'します', 'trazan', 'した', 'しました'] a2=['dipsy', 'laa-laa', 'banarne', 'po', 'tinky winky'] for i,j in zip(a1,a2): print i.ljust(12...
5
2010-03-19T11:54:19Z
2,477,005
<p>Use unicode objects instead of byte strings:</p> <pre><code>#!/usr/bin/python # coding=utf-8 a1=[u'する', u'します', u'trazan', u'した', u'しました'] a2=[u'dipsy', u'laa-laa', u'banarne', u'po', u'tinky winky'] for i,j in zip(a1,a2): print i.ljust(12),':',j print '-'*8 for i,j in zip(a1,a2): ...
2
2010-03-19T12:02:46Z
[ "python", "unicode", "utf-8" ]
Python utf-8, howto align printout
2,476,953
<p>I have a array containing japanese caracters as well as "normal". How do I align the printout of these?</p> <pre><code>#!/usr/bin/python # coding=utf-8 a1=['する', 'します', 'trazan', 'した', 'しました'] a2=['dipsy', 'laa-laa', 'banarne', 'po', 'tinky winky'] for i,j in zip(a1,a2): print i.ljust(12...
5
2010-03-19T11:54:19Z
2,477,043
<p>Using the <code>unicodedata.east_asian_width</code> function, keep track of which characters are narrow and wide when computing the length of the string.</p> <pre><code>#!/usr/bin/python # coding=utf-8 import sys import codecs import unicodedata out = codecs.getwriter('utf-8')(sys.stdout) def width(string): ...
4
2010-03-19T12:08:25Z
[ "python", "unicode", "utf-8" ]
Storing and Retrieving Images from Database using Python
2,477,045
<p>I want to store the images related to a each person's profile in the DB and retrieve them when requested and save it as .jpg file - and display it to the users.</p> <p>How could I render the image data stored in the DB as an image and store it locally??</p>
2
2010-03-19T12:08:27Z
2,477,074
<p>Why don't you simply store the images on the file system, and only store their references on the database. That's a lot more elegant, and won't consume loads of your database.</p> <p>Also, you won't have to use any kind of binary functions to read them from the DB, saving memory and loading time.</p> <p>Is there a...
1
2010-03-19T12:12:44Z
[ "python", "image-manipulation" ]
Storing and Retrieving Images from Database using Python
2,477,045
<p>I want to store the images related to a each person's profile in the DB and retrieve them when requested and save it as .jpg file - and display it to the users.</p> <p>How could I render the image data stored in the DB as an image and store it locally??</p>
2
2010-03-19T12:08:27Z
2,477,148
<p>The standard approach is to convert image to JPG only once, when it is get uploaded. Then save it as a regular file on file system. Use DB just to store relative path to saved image.</p> <p>When you want to render it just use HTML: </p> <pre><code>&lt;img src="/images/relative/path/to/my/image.jpg" /&gt; </code></...
1
2010-03-19T12:21:52Z
[ "python", "image-manipulation" ]
Storing and Retrieving Images from Database using Python
2,477,045
<p>I want to store the images related to a each person's profile in the DB and retrieve them when requested and save it as .jpg file - and display it to the users.</p> <p>How could I render the image data stored in the DB as an image and store it locally??</p>
2
2010-03-19T12:08:27Z
2,477,359
<p>This StackOverflow Question is a good one to start with when figuring out whether to store images in a DB or on a filesystem</p> <p><a href="http://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay">http://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay</a></p> <p>I have also writte...
5
2010-03-19T12:51:30Z
[ "python", "image-manipulation" ]
pip requirements.txt with alternative index
2,477,117
<p>I want to put all the requirements of a repoze Zope2 install in a pip <a href="http://pip.readthedocs.org/en/1.1/requirements.html#the-requirements-file-format" rel="nofollow">requirements file</a>. Most of the repoze packages don't seem to be on PyPi, but there's an alternative PyPi index for them <a href="http://d...
14
2010-03-19T12:17:22Z
2,477,610
<p><code>requirements.txt</code>:</p> <pre><code>-i http://dist.repoze.org/zope2/2.10/simple zopelib </code></pre> <p>Example:</p> <pre><code>$ pip install -r requirements.txt ... Successfully installed zopelib </code></pre>
20
2010-03-19T13:27:47Z
[ "python", "pip", "pypi" ]
Replacing python docstrings
2,477,909
<p>I have written a <a href="http://epydoc.sourceforge.net/epytext.html">epytext</a> to <a href="http://docutils.sourceforge.net/docs/user/rst/quickref.html">reST</a> markup converter, and now I want to convert all the docstrings in my entire library from epytext to reST format.</p> <p>Is there a smart way to read the...
7
2010-03-19T14:12:03Z
2,479,119
<p>Probably the most straightforward just to do it the old-fashioned way. Here's some initial code to get you going. It probably could be prettier but should give the basic idea:</p> <pre><code>def is_docstr_bound(line): return "'''" in line or '"""' in line # XXX: output using the same name to some other folder...
0
2010-03-19T16:59:56Z
[ "python", "documentation", "documentation-generation", "docstring" ]
Replacing python docstrings
2,477,909
<p>I have written a <a href="http://epydoc.sourceforge.net/epytext.html">epytext</a> to <a href="http://docutils.sourceforge.net/docs/user/rst/quickref.html">reST</a> markup converter, and now I want to convert all the docstrings in my entire library from epytext to reST format.</p> <p>Is there a smart way to read the...
7
2010-03-19T14:12:03Z
2,480,364
<p>I wonder about a combination of introspection and source processing. Here's some untested pseudocode:</p> <pre><code>import foo #where foo is your module with open('foo.py',r) as f: src = f.readlines() for pything in dir(foo): #probably better ways to do this... try: docstring = pything.__doc__ ...
0
2010-03-19T20:22:08Z
[ "python", "documentation", "documentation-generation", "docstring" ]
Replacing python docstrings
2,477,909
<p>I have written a <a href="http://epydoc.sourceforge.net/epytext.html">epytext</a> to <a href="http://docutils.sourceforge.net/docs/user/rst/quickref.html">reST</a> markup converter, and now I want to convert all the docstrings in my entire library from epytext to reST format.</p> <p>Is there a smart way to read the...
7
2010-03-19T14:12:03Z
2,487,596
<p>It might be an overkill for this simple usage, but I'd look into using the machinery of <strong>2to3</strong> to do the editing. You just need to write a custom fixer. It's not well-documented, but <em>Developer's Guide to Python 3.0: Python 2.6 and Migrating From 2 to 3: <a href="http://www.devx.com/opensource/Ar...
2
2010-03-21T15:34:04Z
[ "python", "documentation", "documentation-generation", "docstring" ]
Replacing python docstrings
2,477,909
<p>I have written a <a href="http://epydoc.sourceforge.net/epytext.html">epytext</a> to <a href="http://docutils.sourceforge.net/docs/user/rst/quickref.html">reST</a> markup converter, and now I want to convert all the docstrings in my entire library from epytext to reST format.</p> <p>Is there a smart way to read the...
7
2010-03-19T14:12:03Z
24,381,244
<p><a href="https://github.com/dadadel/pyment" rel="nofollow"><strong>Pyment</strong></a> is a tool that can convert Python docstrings and create missing ones skeletons. It can manage <strong>Google</strong>, <strong>Epydoc</strong> (javadoc style), <strong>Numpydoc</strong>, <strong>reStructuredText</strong> (reST, Sp...
4
2014-06-24T07:54:29Z
[ "python", "documentation", "documentation-generation", "docstring" ]
Easy way to find "not enough arguments..." in python logging library
2,477,934
<p>Do you know any easy way to find a logging call that throws "not enough argumenst for format string". On my workstation I've modified <code>logging/__init__.py</code> to print the msg so I can easily find the line in the source.</p> <p>But do you have any idea what to do on the testing environment where you can't ...
7
2010-03-19T14:15:17Z
2,477,973
<p>Generally, the best way to catch an exception (including the one you mention) is to put the suspect code in the <code>try</code> clause of a <code>try</code>/<code>except</code> statement; in the <code>except</code> clause you can use the <code>traceback</code> module or other ways to pinpoint the errant statement.<...
2
2010-03-19T14:22:54Z
[ "python", "debugging" ]
Easy way to find "not enough arguments..." in python logging library
2,477,934
<p>Do you know any easy way to find a logging call that throws "not enough argumenst for format string". On my workstation I've modified <code>logging/__init__.py</code> to print the msg so I can easily find the line in the source.</p> <p>But do you have any idea what to do on the testing environment where you can't ...
7
2010-03-19T14:15:17Z
2,478,016
<p>To find a logging call that throws "not enough argumenst for format string".</p> <p>I grep the source for all logging calls. There aren't that many: <code>.info(</code>, <code>.warn(</code>, <code>.debug(</code>, <code>.error(</code>, <code>.critical(</code>, <code>.exception(</code>, <code>.log(</code>.</p> <p>...
0
2010-03-19T14:28:48Z
[ "python", "debugging" ]
How do I parse a VCard to a Python dictionary?
2,478,027
<p>I'm trying to figure out how to parse a VCard to a Python dictionary using <a href="http://vobject.skyhouseconsulting.com/">VObject</a>.</p> <pre><code>vobj=vobject.readOne(string) print vobj.behavior.knownChildren </code></pre> <p>This is all I get:</p> <pre><code>{'CATEGORIES': (0, None, None), 'ADR': (0, None,...
5
2010-03-19T14:30:06Z
2,478,639
<p>You don't want to look at the behavior, you want to look at <code>vobj</code> itself. The behavior is a data structure describing what children are required/expected, and how to translate those children into appropriate Python data structures.</p> <p>The <code>vobj</code> object is a vobject Component. Its contents...
9
2010-03-19T15:47:07Z
[ "python", "vcard", "vcf" ]
Django/PIL Error - Caught an exception while rendering: The _imagingft C module is not installed
2,478,123
<p>I'm trying to run a webapp/site on my machine, it's running on OSX 10.6.2 and I'm having some problems:</p> <pre><code>Caught an exeption while rending: The _imagingft C module is not installed </code></pre> <p>Doing import _imagingft in python gives me this:</p> <pre><code>&gt;&gt;&gt; import _imagingft Tracebac...
7
2010-03-19T14:43:28Z
2,481,343
<p>With errors like those it's usually because one of PIL dependencies were not compiled to be universal binary.</p> <p>Try this:</p> <ol> <li>Download the framework for Freetype at <a href="http://www.kyngchaos.com/software%3aframeworks" rel="nofollow">this website</a> </li> <li>Download the package for libjpeg8 at ...
1
2010-03-20T00:24:45Z
[ "python", "django", "osx", "python-imaging-library" ]
Django/PIL Error - Caught an exception while rendering: The _imagingft C module is not installed
2,478,123
<p>I'm trying to run a webapp/site on my machine, it's running on OSX 10.6.2 and I'm having some problems:</p> <pre><code>Caught an exeption while rending: The _imagingft C module is not installed </code></pre> <p>Doing import _imagingft in python gives me this:</p> <pre><code>&gt;&gt;&gt; import _imagingft Tracebac...
7
2010-03-19T14:43:28Z
2,779,466
<p>I've had this problem as well. Couldn't resolve it with PIL 1.1.6 nor with PIL 1.1.7. I installed py26-pil from ports and presto, it works.</p> <pre><code>sudo port install py26-pil </code></pre> <p>If you don't have ports, go to <a href="http://www.macports.org/" rel="nofollow">http://www.macports.org/</a></p>
3
2010-05-06T08:06:09Z
[ "python", "django", "osx", "python-imaging-library" ]
Django/PIL Error - Caught an exception while rendering: The _imagingft C module is not installed
2,478,123
<p>I'm trying to run a webapp/site on my machine, it's running on OSX 10.6.2 and I'm having some problems:</p> <pre><code>Caught an exeption while rending: The _imagingft C module is not installed </code></pre> <p>Doing import _imagingft in python gives me this:</p> <pre><code>&gt;&gt;&gt; import _imagingft Tracebac...
7
2010-03-19T14:43:28Z
2,779,501
<p>The environment is not set up correctly to build the OS X PIL\libjpeg binaries using easy_install. This guide should help <a href="http://fightingrabbits.com/archives/266" rel="nofollow">http://fightingrabbits.com/archives/266</a> - It's for installing Python/Django but goes through the necessary PIL setup first and...
0
2010-05-06T08:12:17Z
[ "python", "django", "osx", "python-imaging-library" ]
Django/PIL Error - Caught an exception while rendering: The _imagingft C module is not installed
2,478,123
<p>I'm trying to run a webapp/site on my machine, it's running on OSX 10.6.2 and I'm having some problems:</p> <pre><code>Caught an exeption while rending: The _imagingft C module is not installed </code></pre> <p>Doing import _imagingft in python gives me this:</p> <pre><code>&gt;&gt;&gt; import _imagingft Tracebac...
7
2010-03-19T14:43:28Z
2,930,164
<p>I found the solution for this.</p> <p>First you need to download <strong>Freetype2</strong> <a href="http://freetype.sourceforge.net/index2.html" rel="nofollow">http://freetype.sourceforge.net/index2.html</a> and compile it with these instructions <a href="http://www.libgd.org/DOC_INSTALL_OSX#Building_freetype2" re...
2
2010-05-28T15:10:32Z
[ "python", "django", "osx", "python-imaging-library" ]
Django/PIL Error - Caught an exception while rendering: The _imagingft C module is not installed
2,478,123
<p>I'm trying to run a webapp/site on my machine, it's running on OSX 10.6.2 and I'm having some problems:</p> <pre><code>Caught an exeption while rending: The _imagingft C module is not installed </code></pre> <p>Doing import _imagingft in python gives me this:</p> <pre><code>&gt;&gt;&gt; import _imagingft Tracebac...
7
2010-03-19T14:43:28Z
5,047,537
<p>Before (re)installing PIL add the following sysmlinks to enable freetype on Mac 10.6 Snow Leopard:</p> <pre><code>ln -s /usr/X11/include/freetype2 /usr/local/include/ ln -s /usr/X11/include/ft2build.h /usr/local/include/ ln -s /usr/X11/lib/libfreetype.6.dylib /usr/local/lib/ ln -s /usr/X11/lib/libfreetype.6.dylib /...
9
2011-02-18T23:09:53Z
[ "python", "django", "osx", "python-imaging-library" ]
What does Postgres do when BEGIN is run on a connection in autocommit mode?
2,478,518
<p>I'm trying to better understand the concept of 'autocommit' when working with a Postgres (psycopg) connection. Let's say I have a fresh connection, set its isolation level to ISOLATION_LEVEL_AUTOCOMMIT, then run this SQL directly, without using the cursor begin/rollback methods (as an exercise; not saying I actuall...
1
2010-03-19T15:32:46Z
2,478,614
<p>Autocommit mode means that each statement implicitly begins and ends the transaction.</p> <p>In your case, if autocommit is off:</p> <ul> <li>The client will implicitly start the transaction for the first statement</li> <li>The <code>BEGIN</code> will issue a warning saying that the transaction is already started<...
3
2010-03-19T15:43:44Z
[ "python", "sql", "postgresql", "autocommit", "psycopg" ]
What does Postgres do when BEGIN is run on a connection in autocommit mode?
2,478,518
<p>I'm trying to better understand the concept of 'autocommit' when working with a Postgres (psycopg) connection. Let's say I have a fresh connection, set its isolation level to ISOLATION_LEVEL_AUTOCOMMIT, then run this SQL directly, without using the cursor begin/rollback methods (as an exercise; not saying I actuall...
1
2010-03-19T15:32:46Z
2,484,988
<p>By default, PostgreSQL has autocommit on, meaning that each statement is handled as a transaction. If you explicitly tell it to start a transaction, as in your example, those items are in a new transaction.</p> <p>In your example, A and B would be committed, C and D would be rolled back.</p>
1
2010-03-20T22:12:00Z
[ "python", "sql", "postgresql", "autocommit", "psycopg" ]
What does Postgres do when BEGIN is run on a connection in autocommit mode?
2,478,518
<p>I'm trying to better understand the concept of 'autocommit' when working with a Postgres (psycopg) connection. Let's say I have a fresh connection, set its isolation level to ISOLATION_LEVEL_AUTOCOMMIT, then run this SQL directly, without using the cursor begin/rollback methods (as an exercise; not saying I actuall...
1
2010-03-19T15:32:46Z
4,452,677
<p>When autocommit is on psycopg just sends everything to the PostgreSQL backend without trying to manage the transaction for you. If you don't use BEGIN/COMMIT/ROLLBACK then every .execute() call is immediately executed and committed. You can do your own transaction management by issuing BEGIN/COMMIT/ROLLBACK commands...
1
2010-12-15T17:00:19Z
[ "python", "sql", "postgresql", "autocommit", "psycopg" ]
Segfault in multithreaded python extension in C
2,478,939
<p>I have a very trimmed down example that creates a segfault that I can't seem to get rid of. Python script calls a C function in an extension, which creates a new thread using pthreads. I use PyGILState_Ensure and PyGILState_Release around my python call (PyRun_SimpleString) in the new thread, but perhaps I'm not u...
4
2010-03-19T16:33:53Z
2,479,646
<p>I'm not positive that this will be relevant to your question, but one thing that looks suspicious is the PyEval_ReleaseLock() call in your module initializer function. I doubt that Python expects your module initializer to release the GIL out from underneath it, and a quick look at some example code <a href="http:/...
3
2010-03-19T18:20:23Z
[ "python", "multithreading" ]
ValidationError while running Google adwords client library examples
2,479,395
<p>I get the following error when I try to run sample example of Google adwords</p> <blockquote> <p>[root@some v200909]# python get_related_keywords.py Traceback (most recent call last): File "get_related_keywords.py", line 53, in page = targeting_idea_service.Get(selector)[0] File "../../aw_api/TargetingI...
0
2010-03-19T17:42:41Z
2,508,994
<p>This sounds like an issue with the headers you're providing. The headers must be especially formatted for the sandbox, so make sure that:</p> <p>a) You're formatting the headers as specified in <a href="http://code.google.com/apis/adwords/docs/developer/adwords_api_sandbox.html#requestheaders" rel="nofollow">http:/...
0
2010-03-24T15:34:49Z
[ "python", "google-adwords" ]
Python: Check if all dictionaries in list are empty
2,479,472
<p>I have a list of dictionaries. I need to check if all the dictionaries in that list are empty. I am looking for a simple statement that will do it in one line.</p> <p>Is there a single line way to do the following (not including the print)?</p> <pre><code>l = [{},{},{}] # this list is generated elsewhere... all_em...
8
2010-03-19T17:54:44Z
2,479,487
<pre><code>all(not d for d in l) </code></pre>
19
2010-03-19T17:57:08Z
[ "python" ]
Python: Check if all dictionaries in list are empty
2,479,472
<p>I have a list of dictionaries. I need to check if all the dictionaries in that list are empty. I am looking for a simple statement that will do it in one line.</p> <p>Is there a single line way to do the following (not including the print)?</p> <pre><code>l = [{},{},{}] # this list is generated elsewhere... all_em...
8
2010-03-19T17:54:44Z
2,479,501
<p><code>not any(d for d in l)</code> is equivalent by <a href="http://en.wikipedia.org/wiki/De_Morgan%27s_laws">De Morgan's Law</a> to <code>all(not d for d in l)</code>, but applies just one <code>not</code> operator. The short-circuiting behavior is also equivalent.</p> <p><strong>Edit 1</strong>: the inner genexp...
10
2010-03-19T18:00:09Z
[ "python" ]
Python: Check if all dictionaries in list are empty
2,479,472
<p>I have a list of dictionaries. I need to check if all the dictionaries in that list are empty. I am looking for a simple statement that will do it in one line.</p> <p>Is there a single line way to do the following (not including the print)?</p> <pre><code>l = [{},{},{}] # this list is generated elsewhere... all_em...
8
2010-03-19T17:54:44Z
2,479,536
<p><code>not any(d for d in l)</code> could be shortened to just <code>not any(l)</code> in this case.</p>
10
2010-03-19T18:05:12Z
[ "python" ]
Controlling the fan speed and detecting the inside temperature of the pc with python?
2,479,558
<p>Since my pc's fan is very loud, I'd like to make myself a program to "shut it up" when it's not required to be running at full speed. I want to make it with python, so is there any module that can detect the temperature and/or set the fan speed?</p>
3
2010-03-19T18:07:37Z
2,479,590
<p>You might be able to do it in <a href="http://timgolden.me.uk/python/wmi/index.html" rel="nofollow">WMI</a>. There's a related question <a href="http://stackoverflow.com/questions/786984/how-can-i-control-my-pcs-fan-speed-using-c-in-vista">here</a>. </p>
0
2010-03-19T18:12:44Z
[ "python", "cpu" ]
Controlling the fan speed and detecting the inside temperature of the pc with python?
2,479,558
<p>Since my pc's fan is very loud, I'd like to make myself a program to "shut it up" when it's not required to be running at full speed. I want to make it with python, so is there any module that can detect the temperature and/or set the fan speed?</p>
3
2010-03-19T18:07:37Z
2,503,161
<p>Don't use python, or WMI. </p> <p>If you have Windows, and if you can't use speedfan, this is best done in the BIOS layer, with <a href="http://download.microsoft.com/download/2/c/1/2c16c7e0-96c1-40f5-81fc-3e4bf7b65496/Microsoft_ASL_Compiler-v4-0-0.msi" rel="nofollow">Microsoft's ASL Compiler</a>. Using that, you ...
4
2010-03-23T19:59:11Z
[ "python", "cpu" ]
Inconsistency in modified/created/accessed time on mac
2,479,690
<p>I'm having trouble using <code>os.utime</code> to correctly set the modification time on the mac (Mac OS X 10.6.2, running Python 2.6.1 from <code>/usr/bin/python</code>). It's not consistent with the <code>touch</code> utility, and it's not consistent with the properties displayed in the Finder's "get info" window....
6
2010-03-19T18:28:14Z
2,525,447
<p>Mac OS maintains extra attributes that don't map to posix. </p> <ul> <li>createDate </li> <li>contentModDate </li> <li>attributeModDate</li> <li>accessDate</li> <li>backupDate</li> </ul> <p>You used to be able to access these through the old macfs module, which was long ago deprecated in favor of the Carbon modul...
0
2010-03-26T17:42:33Z
[ "python", "osx", "touch", "stat" ]
Inconsistency in modified/created/accessed time on mac
2,479,690
<p>I'm having trouble using <code>os.utime</code> to correctly set the modification time on the mac (Mac OS X 10.6.2, running Python 2.6.1 from <code>/usr/bin/python</code>). It's not consistent with the <code>touch</code> utility, and it's not consistent with the properties displayed in the Finder's "get info" window....
6
2010-03-19T18:28:14Z
2,525,906
<h1>POSIX <em>atime</em>, <em>mtime</em>, <em>ctime</em></h1> <p>It might help if you included a full script and its actual and expected outputs instead of the REPL fragments.</p> <pre><code>import sys, os, stat, time def get_times(p): s = os.stat(p) return ( os.path.getatime(p), os.path.get...
2
2010-03-26T18:52:30Z
[ "python", "osx", "touch", "stat" ]
Django logs: any tutorial to log to a file
2,479,858
<p>I am working with a django project, I haven't started. The developed working on the project left. During the knowledge transfer, it was told to me that all the events are logged to the database. I don't find the database interface useful to search for logs and sometimes they don't even log(I might be wrong). I want ...
2
2010-03-19T18:55:31Z
2,483,694
<p>If you are talking about the Django admin log (the one that shows on the right side of the main page of the admin interface), you could just enable an admin model for the log itself.</p> <p>Open the <code>admin.py</code> for one of your django apps and add this:</p> <pre><code>from django.contrib.admin.models impo...
4
2010-03-20T15:55:31Z
[ "python", "django", "logging", "mod-python" ]
Does python import all the listed libraries?
2,479,902
<p>I'm just wondering, I often have really long python files and imports tend to stack quite quickly.</p> <p>PEP8 says that the imports should always be written at the beginning of the file.</p> <hr> <p>Do all the imported libraries get imported when calling a function coded in the file? Or do only the necessary lib...
2
2010-03-19T19:01:43Z
2,479,950
<blockquote> <p>Does it make sense to worry about this?</p> </blockquote> <p>No</p> <p>There no reason to import libraries within the functions or classes that need them. It's just slow because the <code>import</code> statement has to check to see if it's been imported once, and realize that it has been imported....
1
2010-03-19T19:09:58Z
[ "python", "import", "libraries", "pep8" ]
Does python import all the listed libraries?
2,479,902
<p>I'm just wondering, I often have really long python files and imports tend to stack quite quickly.</p> <p>PEP8 says that the imports should always be written at the beginning of the file.</p> <hr> <p>Do all the imported libraries get imported when calling a function coded in the file? Or do only the necessary lib...
2
2010-03-19T19:01:43Z
2,479,960
<p>Imports happen when the module that contains the imports gets executed or imported, not when the functions are called.</p> <p>Ordinarily, I wouldn't worry about it. If you are encountering slowdowns, you might profile to see if your problem is related to this. If it is, you can check to see if your module can div...
0
2010-03-19T19:11:10Z
[ "python", "import", "libraries", "pep8" ]
Does python import all the listed libraries?
2,479,902
<p>I'm just wondering, I often have really long python files and imports tend to stack quite quickly.</p> <p>PEP8 says that the imports should always be written at the beginning of the file.</p> <hr> <p>Do all the imported libraries get imported when calling a function coded in the file? Or do only the necessary lib...
2
2010-03-19T19:01:43Z
2,479,976
<p>Every time Python hits an import statement, it checks to see if that module has already been imported, and if not, imports it. So the imports at the top of your file will happen as soon as your file is run or imported by another module.</p> <p>There is some <a href="http://wiki.python.org/moin/PythonSpeed/Performan...
3
2010-03-19T19:13:02Z
[ "python", "import", "libraries", "pep8" ]
Does python import all the listed libraries?
2,479,902
<p>I'm just wondering, I often have really long python files and imports tend to stack quite quickly.</p> <p>PEP8 says that the imports should always be written at the beginning of the file.</p> <hr> <p>Do all the imported libraries get imported when calling a function coded in the file? Or do only the necessary lib...
2
2010-03-19T19:01:43Z
2,479,982
<p>The best place for imports is at the top of your file. That documents the dependencies in one place and makes errors from their absence appear earlier. The import itself actually occurs at the time of the <code>import</code> statement, but this seldom matters much.</p> <p>It is not typical that you have anything to...
2
2010-03-19T19:14:47Z
[ "python", "import", "libraries", "pep8" ]
Does python import all the listed libraries?
2,479,902
<p>I'm just wondering, I often have really long python files and imports tend to stack quite quickly.</p> <p>PEP8 says that the imports should always be written at the beginning of the file.</p> <hr> <p>Do all the imported libraries get imported when calling a function coded in the file? Or do only the necessary lib...
2
2010-03-19T19:01:43Z
2,480,037
<p>If a function inside a module is the only one to import a given other module (say you have a function sending tweets, only if some configuration option is on), then it makes sense to import that specific module in the function.</p> <p>Unless I see some profiling data proving otherwise, my guess is that <em>the over...
0
2010-03-19T19:24:38Z
[ "python", "import", "libraries", "pep8" ]
ctypes buffer modification
2,480,197
<p>I need to call a c library from my python code. The c library does a lot of image manipulation, so I am passing it image buffers allocated using create_string_buffer.</p> <p>The problem is that I also need to manipulate and change these buffers. What is the best way to reach in and twiddle individual values in my...
2
2010-03-19T19:55:08Z
2,480,348
<p>You mean, something like...:</p> <pre><code>&gt;&gt;&gt; import ctypes &gt;&gt;&gt; x = ctypes.create_string_buffer('howdy!') &gt;&gt;&gt; x.value 'howdy!' &gt;&gt;&gt; x[0] = 'C' &gt;&gt;&gt; x.value 'Cowdy!' </code></pre> <p>...?</p>
2
2010-03-19T20:20:16Z
[ "python", "ctypes" ]
ctypes buffer modification
2,480,197
<p>I need to call a c library from my python code. The c library does a lot of image manipulation, so I am passing it image buffers allocated using create_string_buffer.</p> <p>The problem is that I also need to manipulate and change these buffers. What is the best way to reach in and twiddle individual values in my...
2
2010-03-19T19:55:08Z
2,481,043
<p>You may find that <a href="http://www.cython.org/" rel="nofollow">Cython</a> is a lot nicer then the ctypes module for melding C libraries with Python code.</p>
1
2010-03-19T22:55:44Z
[ "python", "ctypes" ]
Python Daemon Subprocess not working at boot
2,480,339
<p>I am attempting to write a python daemon that will launch at boot. The goal of the script is to receive a job from our gearman load balancing server and complete the job. I am using the python-daemon module from pypi (http://pypi.python.org/pypi/python-daemon/). The nature of the job that it is completing is conve...
0
2010-03-19T20:18:41Z
2,492,759
<p>The issue is not related to python but rather related to the ubuntu init.d daemon. I assumed that the python script was being as a user turns out that it is not. To remedy the problem I added a sudo command to the init.d script and the subprocess starts successfully now.</p>
0
2010-03-22T14:02:15Z
[ "python", "imagemagick", "daemon", "gearman" ]
How do I go about setting up an application so that it has a persistent process in memory and does not have to re-initialize to run?
2,480,363
<p>I'm not sure what's the appropriate terminology here, but I'd like to have an application running passively that is ready to accept commands without having to reinitialize the whole thing.</p> <p>The precise application is a machine learning system written in Python that takes a somewhat long time to train a classi...
2
2010-03-19T20:22:07Z
2,480,380
<p>Depending on your implementation this is known as a server process, a <a href="http://en.wikipedia.org/wiki/Daemon_%28computer_software%29" rel="nofollow">daemon</a>, a <a href="http://en.wikipedia.org/wiki/Windows_service" rel="nofollow">Windows service</a> etc.</p> <p>A typical implementation will run and accept ...
2
2010-03-19T20:25:22Z
[ "php", "python", "command-line", "asynchronous", "machine-learning" ]
Resulting .exe from PyInstaller with wxPython crashing
2,480,480
<p>I'm trying to compile a very simple wxPython script into an executable by using PyInstaller on Windows Vista.</p> <p>The Python script is nothing but a Hello World in wxPython. I'm trying to get that up and running as a Windows executable before I add any of the features that the program needs to have. But I'm alre...
1
2010-03-19T20:46:43Z
2,483,667
<p>On windows I have found Py2exe to be more stable and easier to use, have you tried that. </p>
0
2010-03-20T15:49:36Z
[ "python", "wxpython", "pyinstaller" ]
Resulting .exe from PyInstaller with wxPython crashing
2,480,480
<p>I'm trying to compile a very simple wxPython script into an executable by using PyInstaller on Windows Vista.</p> <p>The Python script is nothing but a Hello World in wxPython. I'm trying to get that up and running as a Windows executable before I add any of the features that the program needs to have. But I'm alre...
1
2010-03-19T20:46:43Z
2,493,804
<p>I found the solution to this problem on the PyInstaller mailing list, and it's remarkably simple, only undocumented.</p> <p>PyInstaller doesn't yet support Python 2.6. The solution is to get a patch from a page which can now be found in the compilation process that I was trying, if one tries to compile using Python...
0
2010-03-22T16:10:38Z
[ "python", "wxpython", "pyinstaller" ]
Directory layout for a Python project with C extension modules
2,480,565
<p>We have numerous projects in our organization that are mixed Python/C. Currently we're trying to standardize on a directory layout for our projects and are trying to come up with a convenient scheme. One point of contention is where to put C extension modules in the tree.</p> <p>We're tossing around a couple of opt...
5
2010-03-19T21:03:37Z
2,480,684
<p>I think the layout of the Python standard library is a reasonable example: under <a href="http://svn.python.org/view/python/trunk/" rel="nofollow">trunk</a>, which is basically the root for the SVN repo (net of branches &amp;c), the <code>Modules</code> directory has a lot of <code>.c</code> and <code>.h</code> file...
1
2010-03-19T21:28:00Z
[ "python", "c", "module" ]
How can I optimize this code?
2,480,729
<p>I'm developing a logger daemon to squid to grab the logs on a mongodb database. But I'm experiencing too much cpu utilization. How can I optimize this code?</p> <pre><code> from sys import stdin from pymongo import Connection connection = Connection() db = connection.squid logs = db.logs buffer = [] a = 'timestam...
0
2010-03-19T21:36:02Z
2,480,776
<p>I'd suspect it might actually be readline() causing cpu utilization. Try running the same code with the readline replaced with just looking at some constant buffer provided by you. And try running with the database inserts commented out. Establish which one of these is the culprit. </p>
0
2010-03-19T21:44:14Z
[ "python", "mongodb" ]
How can I optimize this code?
2,480,729
<p>I'm developing a logger daemon to squid to grab the logs on a mongodb database. But I'm experiencing too much cpu utilization. How can I optimize this code?</p> <pre><code> from sys import stdin from pymongo import Connection connection = Connection() db = connection.squid logs = db.logs buffer = [] a = 'timestam...
0
2010-03-19T21:36:02Z
2,480,805
<p>This might be a better question for a python profiler. There's a few builtin Python profiling modules such as cProfile; you can read more about it <a href="http://docs.python.org/library/profile.html" rel="nofollow">here</a>.</p>
1
2010-03-19T21:50:55Z
[ "python", "mongodb" ]
How can I optimize this code?
2,480,729
<p>I'm developing a logger daemon to squid to grab the logs on a mongodb database. But I'm experiencing too much cpu utilization. How can I optimize this code?</p> <pre><code> from sys import stdin from pymongo import Connection connection = Connection() db = connection.squid logs = db.logs buffer = [] a = 'timestam...
0
2010-03-19T21:36:02Z
2,480,855
<p>The cpu usage is given by that active loop While True. How many lines / minute do you have? put the</p> <pre><code>if len(buffer) == 1000: logs.insert(buffer) buffer = [] </code></pre> <p>check after the buffer.append</p> <p>I will tell you more after you tell me how many insertions you get so far</p...
0
2010-03-19T22:01:47Z
[ "python", "mongodb" ]
Search backward through a string using a regex (in Python)?
2,480,808
<p><strong>Context</strong><br> I'm parsing some code and want to match the doxygen comments before a function. However, because I want to match for a specific function name, getting only the immediately previous comment is giving me problems.</p> <p><strong>Current Approach</strong> </p> <pre><code>import re func...
1
2010-03-19T21:52:23Z
2,480,825
<p>You can do look-behind assertions with <code>(?&lt;=...)</code> or <code>(?&lt;!...)</code>, but in general you can only match forwards.</p>
0
2010-03-19T21:55:40Z
[ "python", "regex" ]
Search backward through a string using a regex (in Python)?
2,480,808
<p><strong>Context</strong><br> I'm parsing some code and want to match the doxygen comments before a function. However, because I want to match for a specific function name, getting only the immediately previous comment is giving me problems.</p> <p><strong>Current Approach</strong> </p> <pre><code>import re func...
1
2010-03-19T21:52:23Z
2,480,845
<p>The question is why are these comments not inside the function, so you can use <strong>doc</strong>.</p> <p>But there is no easy way with regex.</p>
0
2010-03-19T21:59:18Z
[ "python", "regex" ]
Search backward through a string using a regex (in Python)?
2,480,808
<p><strong>Context</strong><br> I'm parsing some code and want to match the doxygen comments before a function. However, because I want to match for a specific function name, getting only the immediately previous comment is giving me problems.</p> <p><strong>Current Approach</strong> </p> <pre><code>import re func...
1
2010-03-19T21:52:23Z
2,480,848
<p>simplest way is to just use a group, you don't need to go backwards...</p> <pre><code> (commentRegex)functionRegex </code></pre> <p>Then just extract group 1. You will need to run in multi-line mode to get it working, i don't know python so i can't be more helpful.</p> <p>It's also possible with lookahead asserti...
2
2010-03-19T21:59:44Z
[ "python", "regex" ]
Search backward through a string using a regex (in Python)?
2,480,808
<p><strong>Context</strong><br> I'm parsing some code and want to match the doxygen comments before a function. However, because I want to match for a specific function name, getting only the immediately previous comment is giving me problems.</p> <p><strong>Current Approach</strong> </p> <pre><code>import re func...
1
2010-03-19T21:52:23Z
2,480,865
<p>I think you should use a regex that only matches doxymentation that's immediately before the function. Maybe something like this (simplified example):</p> <pre><code>import re test = """ /** @doxygen comment */ void function() { } """ doxygenRegex = r"(?P&lt;comment&gt;/\*\*(?:[^/]|/(?!\*\*))*\*/)" function...
2
2010-03-19T22:05:03Z
[ "python", "regex" ]
Search backward through a string using a regex (in Python)?
2,480,808
<p><strong>Context</strong><br> I'm parsing some code and want to match the doxygen comments before a function. However, because I want to match for a specific function name, getting only the immediately previous comment is giving me problems.</p> <p><strong>Current Approach</strong> </p> <pre><code>import re func...
1
2010-03-19T21:52:23Z
2,481,520
<p>Note that C isn't a regular language, so it cannot be parsed by regular expressions. Have you considered leveraging doxygen itself to parse this file?</p>
1
2010-03-20T01:23:21Z
[ "python", "regex" ]
Search backward through a string using a regex (in Python)?
2,480,808
<p><strong>Context</strong><br> I'm parsing some code and want to match the doxygen comments before a function. However, because I want to match for a specific function name, getting only the immediately previous comment is giving me problems.</p> <p><strong>Current Approach</strong> </p> <pre><code>import re func...
1
2010-03-19T21:52:23Z
2,481,619
<p>here's a non regex approach, split on <code>*/</code> and find if the function you are looking for is at the next item. eg</p> <pre><code>test = """ /** @doxygen comment */ void function() { } """ t=test.split("*/") for n,comm in enumerate(t): try: if "void" in t[n+1]: print t[n] ...
0
2010-03-20T02:05:29Z
[ "python", "regex" ]
Search backward through a string using a regex (in Python)?
2,480,808
<p><strong>Context</strong><br> I'm parsing some code and want to match the doxygen comments before a function. However, because I want to match for a specific function name, getting only the immediately previous comment is giving me problems.</p> <p><strong>Current Approach</strong> </p> <pre><code>import re func...
1
2010-03-19T21:52:23Z
2,482,415
<p>This can be achived using a single reg-ex.</p> <p>The key is to capture the comment just before the desired function. The easy way to do this is to use non-greedy qualifier. For example: <code>/\*\*(.*?)\*/</code> with MULTILINE flag; however, in Python, non-greedy and MULTILINE do not work together (at least on my...
2
2010-03-20T08:32:02Z
[ "python", "regex" ]
In Python, how do I do a string replacement AND retrive the replaced substring?
2,480,841
<p>In Perl, I would write:</p> <pre><code>$x = "abbbc"; $x =~ s/(b+)/z/; print "Replaced $1 and ended up with $x\n"; # "Replaced bbb and ended up with azc" </code></pre> <p>How do I do this in Python -- do a regular-expression string replacement <em>and</em> record what it was that got replaced?</p>
1
2010-03-19T21:58:07Z
2,480,873
<p>Python does not simultaneously return a match and a substitution. Calling <code>group(0)</code> on a returned Match object will find the matched substring:</p> <pre><code>&gt;&gt;&gt; r=re.compile('(b+)') &gt;&gt;&gt; r.search('abbbc') &lt;_sre.SRE_Match object at 0x7f04af497af8&gt; &gt;&gt;&gt; r.search('abbbc').g...
6
2010-03-19T22:06:28Z
[ "python", "regex" ]
Creating temporary user accounts - Django
2,480,862
<p>I need to setup temporary User models for each visitors, where the visitors are obviously tied by session data.</p> <p>I might not be aware of it, but does Django support attaching data to Anonymous users?</p> <hr> <p>The only way, I am currently aware of, is to use the session dictionary part of the request obje...
6
2010-03-19T22:04:54Z
2,481,015
<p>Have a look at <a href="http://github.com/danfairs/django-lazysignup">django-lazysignup</a></p> <blockquote> <p><code>django-lazysignup</code> is a package designed to allow users to interact with a site as if they were authenticated users, but without signing up. At any time, they can convert their temporary use...
11
2010-03-19T22:46:04Z
[ "python", "django", "session" ]
Python: Creating directories
2,480,936
<p>I want to create a directory (named 'downloaded') on in my desktop directory; isn't this working?:</p> <pre><code>import os os.mkdir('~/Desktop/downloaded/') </code></pre>
6
2010-03-19T22:23:12Z
2,480,953
<p>You can't simply use <code>~</code> You must use <a href="http://docs.python.org/library/os.path.html#os.path.expanduser">os.path.expanduser</a> to replace the <code>~</code> with a proper path.</p>
14
2010-03-19T22:27:09Z
[ "python" ]
Python: Creating directories
2,480,936
<p>I want to create a directory (named 'downloaded') on in my desktop directory; isn't this working?:</p> <pre><code>import os os.mkdir('~/Desktop/downloaded/') </code></pre>
6
2010-03-19T22:23:12Z
2,481,333
<p>Use</p> <pre><code>import os os.mkdir(os.path.expanduser("~/Desktop/downloaded")) </code></pre> <p>The <code>~</code> character is a POSIX shell convention that represents the contents of the HOME environment variable. So, when you type in a shell:</p> <pre><code>$ mkdir ~/Desktop/downloaded </code></pre> <p>it'...
8
2010-03-20T00:23:04Z
[ "python" ]
Python: Creating directories
2,480,936
<p>I want to create a directory (named 'downloaded') on in my desktop directory; isn't this working?:</p> <pre><code>import os os.mkdir('~/Desktop/downloaded/') </code></pre>
6
2010-03-19T22:23:12Z
2,481,360
<p>another way, use <code>os.environ</code></p> <pre><code>import os home=os.environ["HOME"] path=os.path.join(home,"Desktop","download") try: os.mkdir(path) except IOError,e: print e else: print "Successful" </code></pre>
1
2010-03-20T00:29:54Z
[ "python" ]
Is it inefficient to access a python class member container in a loop statement?
2,481,254
<p>I'm trying to adopt some best practices to keep my python code efficient. I've heard that accessing a member variable inside of a loop can incur a dictionary lookup for every iteration of the loop, so I cache these in local variables to use inside the loop.</p> <p>My question is about the loop statement itself... i...
1
2010-03-19T23:56:59Z
2,481,286
<p>An iterator is created from <code>self.myList</code>, and that iterator is used. No other extra lookups are done on <code>self</code> for the iteration.</p>
6
2010-03-20T00:06:27Z
[ "python", "performance", "language-features" ]
How do I install boto?
2,481,287
<p>So that I am able to work with it within my python scripts?</p>
33
2010-03-20T00:06:28Z
2,481,306
<p>switch to the <code>boto-*</code> directory and type <code>python setup.py install</code>.</p>
4
2010-03-20T00:15:19Z
[ "python", "installation", "boto" ]
How do I install boto?
2,481,287
<p>So that I am able to work with it within my python scripts?</p>
33
2010-03-20T00:06:28Z
2,481,346
<pre><code>$ easy_install boto </code></pre> <p>Edit: pip is now by far the preferred way to install packages</p>
13
2010-03-20T00:26:28Z
[ "python", "installation", "boto" ]
How do I install boto?
2,481,287
<p>So that I am able to work with it within my python scripts?</p>
33
2010-03-20T00:06:28Z
3,603,001
<p>Installing Boto depends on the Operating system. For e.g in Ubuntu you can use the aptitude command:</p> <pre><code>sudo apt-get install python-boto </code></pre> <p>Or you can download the boto code from their site and move into the unzipped directory to run </p> <pre><code>python setup.py install </code></pre>...
30
2010-08-30T18:08:24Z
[ "python", "installation", "boto" ]
How do I install boto?
2,481,287
<p>So that I am able to work with it within my python scripts?</p>
33
2010-03-20T00:06:28Z
8,191,581
<ol> <li><p>If necessary, install pip:</p> <p><code>sudo apt-get install python-pip</code></p></li> <li><p>Then install boto:</p> <p><code>pip install -U boto</code></p></li> </ol>
49
2011-11-19T03:08:19Z
[ "python", "installation", "boto" ]
How do I install boto?
2,481,287
<p>So that I am able to work with it within my python scripts?</p>
33
2010-03-20T00:06:28Z
13,243,424
<p>Best way to install boto in my opinion is to use:</p> <pre><code>pip install boto-1.6 </code></pre> <p>This ensures you'll have the boto glacier code. </p>
1
2012-11-06T02:19:35Z
[ "python", "installation", "boto" ]
How do I install boto?
2,481,287
<p>So that I am able to work with it within my python scripts?</p>
33
2010-03-20T00:06:28Z
23,692,475
<ol> <li><p>install pip: <a href="https://pip.pypa.io/en/latest/installing.html" rel="nofollow">https://pip.pypa.io/en/latest/installing.html</a></p></li> <li><p>insatll boto: <a href="https://github.com/boto/boto" rel="nofollow">https://github.com/boto/boto</a></p> <p>$ git clone git://github.com/boto/boto.git<br> $ ...
1
2014-05-16T04:06:54Z
[ "python", "installation", "boto" ]
Why does socket.inet_ntoa returns packed format in python
2,481,413
<p>Why does socket.inet_aton returns packed format in python? </p> <p>If I am storing the IP as integer in Database (mysql), do I have to always extract the integer value or is there any easier way out?</p>
1
2010-03-20T00:49:24Z
2,481,666
<p><a href="http://docs.python.org/library/socket.html?highlight=inet_aton#socket.inet_aton" rel="nofollow">inet_aton</a> is clearly documented to perform exactly this task, and the "why" is even very explicitly explained...:</p> <blockquote> <p>Convert an IPv4 address from dotted-quad string format (for example...
1
2010-03-20T02:28:00Z
[ "python", "ip-address" ]
Problem importing modul2s from boto
2,481,417
<p>I have installed boto like so: python setup.py install; and then when I launch my python script (that imports moduls from boto) on shell, an error like this shows up: ImportError: No module named boto.s3.connection</p> <p>How to settle the matter?</p>
1
2010-03-20T00:50:46Z
2,481,420
<p>This can happen if the Python script does not use your default <code>python</code> executable. Check the shebang on the first line of the script (on *nix) or the .py file association (on Windows) and run that against setup.py instead.</p>
2
2010-03-20T00:53:19Z
[ "python", "boto" ]
Problem importing modul2s from boto
2,481,417
<p>I have installed boto like so: python setup.py install; and then when I launch my python script (that imports moduls from boto) on shell, an error like this shows up: ImportError: No module named boto.s3.connection</p> <p>How to settle the matter?</p>
1
2010-03-20T00:50:46Z
6,861,411
<p>I fixed same problem at Ubuntu using <code>apt-get install python-boto</code></p>
4
2011-07-28T15:19:34Z
[ "python", "boto" ]
difference between len() and .__len__()?
2,481,421
<p>Is there any difference between calling <code>len([1,2,3])</code> or <code>[1,2,3].__len__()</code>? If there is no visible difference what is done differently behind the scenes?</p>
43
2010-03-20T00:53:24Z
2,481,433
<p><code>len</code> is a function to get the length of a collection. It works by calling an object's <code>__len__</code> method. <code>__something__</code> attributes are special and usually more than meets the eye, and generally should not be called directly.</p> <p>It was decided at some point long ago getting the ...
45
2010-03-20T00:57:01Z
[ "python" ]
difference between len() and .__len__()?
2,481,421
<p>Is there any difference between calling <code>len([1,2,3])</code> or <code>[1,2,3].__len__()</code>? If there is no visible difference what is done differently behind the scenes?</p>
43
2010-03-20T00:53:24Z
2,481,445
<p>You can think of len() as being roughly equivalent to</p> <pre><code>def len(x): return x.__len__() </code></pre> <p>One advantage is that it allows you to write things like</p> <pre><code>map(len, somelist) </code></pre> <p>instead of</p> <pre><code>map(list.__len__, somelist) </code></pre> <p>or</p> <p...
12
2010-03-20T01:02:19Z
[ "python" ]
difference between len() and .__len__()?
2,481,421
<p>Is there any difference between calling <code>len([1,2,3])</code> or <code>[1,2,3].__len__()</code>? If there is no visible difference what is done differently behind the scenes?</p>
43
2010-03-20T00:53:24Z
2,481,631
<p>It's often the case that the "typical" behavior of a built-in or operator is to call (with different and nicer syntax) suitable magic methods (ones with names like <code>__whatever__</code>) on the objects involved. Often the built-in or operator has "added value" (it's able to take different paths depending on the...
45
2010-03-20T02:09:51Z
[ "python" ]
difference between len() and .__len__()?
2,481,421
<p>Is there any difference between calling <code>len([1,2,3])</code> or <code>[1,2,3].__len__()</code>? If there is no visible difference what is done differently behind the scenes?</p>
43
2010-03-20T00:53:24Z
28,579,925
<p>You can check <a href="https://docs.python.org/release/2.7.3/reference/datamodel.html#special-method-lookup-for-new-style-classes" rel="nofollow">Pythond docs</a>:</p> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><...
1
2015-02-18T09:23:48Z
[ "python" ]
Mocking ImportError in Python
2,481,511
<p>I'm trying this for almost two hours now, without any luck.</p> <p>I have a module that looks like this:</p> <pre><code>try: from zope.component import queryUtility # and things like this except ImportError: # do some fallback operations &lt;-- how to test this? </code></pre> <p>Later in the code:</p> <...
5
2010-03-20T01:21:51Z
2,481,588
<p>Just monkeypatch into the <code>builtins</code> your own version of <code>__import__</code> -- it can raise whatever you wish when it recognizes it's being called on the specific modules for which you want to mock up errors. See <a href="http://docs.python.org/library/functions.html?highlight=__import__#__import__"...
8
2010-03-20T01:50:03Z
[ "python", "unit-testing", "mocking", "doctest", "zope.component" ]
Mocking ImportError in Python
2,481,511
<p>I'm trying this for almost two hours now, without any luck.</p> <p>I have a module that looks like this:</p> <pre><code>try: from zope.component import queryUtility # and things like this except ImportError: # do some fallback operations &lt;-- how to test this? </code></pre> <p>Later in the code:</p> <...
5
2010-03-20T01:21:51Z
2,484,402
<p>This is what I justed in my unittests.</p> <p>It uses <a href="http://docs.python.org/release/2.3.5/whatsnew/section-pep302.html" rel="nofollow">PEP-302 "New Import Hooks"</a>. (Warning: the PEP-302 document and the more concise release notes I linked aren't exactly <em>accurate</em>.)</p> <p>I use <code>meta_path...
2
2010-03-20T19:27:48Z
[ "python", "unit-testing", "mocking", "doctest", "zope.component" ]
Mocking ImportError in Python
2,481,511
<p>I'm trying this for almost two hours now, without any luck.</p> <p>I have a module that looks like this:</p> <pre><code>try: from zope.component import queryUtility # and things like this except ImportError: # do some fallback operations &lt;-- how to test this? </code></pre> <p>Later in the code:</p> <...
5
2010-03-20T01:21:51Z
31,191,549
<p>If you don't mind changing your program itself, you could also put the import call in a function and patch that in your tests.</p>
0
2015-07-02T18:01:33Z
[ "python", "unit-testing", "mocking", "doctest", "zope.component" ]
Start Python from Twisted
2,481,779
<p>I have learnt Python for about a month as a one year's PHPer.And I started from Twisted as I'm working in a corporation supplying webservice.I have finished some simple application such as data transferring service,page images-fetch service etc.But the problem is ,I don't understand the struture of codes I wrote in ...
1
2010-03-20T03:24:50Z
2,481,802
<p>Just "remembering" the code structure isn't all that much extra value with respect to simply looking it up (just make yourself a handy repository of the examples you're using) -- rote memorization, while once a popular thing to force students to do, isn't all that useful.</p> <p>Understanding is, of course, much be...
3
2010-03-20T03:34:08Z
[ "python", "twisted" ]
Is it bad practice to extend the MongoEngine User document?
2,481,811
<p>I'm integrating MongoDB using MongoEngine. It provides auth and session support that a standard pymongo setup would lack.</p> <p>In regular django auth, it's considered bad practice to extend the User model since there's no guarantee it will be used correctly everywhere. Is this the case with <code>mongoengine.dj...
3
2010-03-20T03:38:54Z
2,909,978
<p>We just <strong>extended</strong> the User class.</p> <pre><code>class User(MongoEngineUser): def __eq__(self, other): if type(other) is User: return other.id == self.id return False def __ne__(self, other): return not self.__eq__(other) def create_profile(self, *ar...
4
2010-05-26T03:38:30Z
[ "python", "django", "mongodb", "nosql", "mongoengine" ]
Is it bad practice to extend the MongoEngine User document?
2,481,811
<p>I'm integrating MongoDB using MongoEngine. It provides auth and session support that a standard pymongo setup would lack.</p> <p>In regular django auth, it's considered bad practice to extend the User model since there's no guarantee it will be used correctly everywhere. Is this the case with <code>mongoengine.dj...
3
2010-03-20T03:38:54Z
12,082,114
<p>MongoEngine now supports <code>AUTH_PROFILE_MODULE</code></p> <p><a href="https://github.com/ruandao/mongoengine_django_contrib_auth/blob/master/models.py#L134-163" rel="nofollow">https://github.com/ruandao/mongoengine_django_contrib_auth/blob/master/models.py#L134-163</a></p>
2
2012-08-22T22:07:36Z
[ "python", "django", "mongodb", "nosql", "mongoengine" ]
Is it bad practice to extend the MongoEngine User document?
2,481,811
<p>I'm integrating MongoDB using MongoEngine. It provides auth and session support that a standard pymongo setup would lack.</p> <p>In regular django auth, it's considered bad practice to extend the User model since there's no guarantee it will be used correctly everywhere. Is this the case with <code>mongoengine.dj...
3
2010-03-20T03:38:54Z
13,385,747
<p>In Django 1.5 you can now use a configurable user object, so that's a great reason to not use a separate object and I think it's safe to say that it is no longer considered bad practice to extend the User model if you are on Django &lt;1.5 but expecting to upgrade at some point. In Django 1.5, the configurable user ...
0
2012-11-14T19:18:21Z
[ "python", "django", "mongodb", "nosql", "mongoengine" ]
Aggregation over a few models - Django
2,481,839
<p>I'm trying to compute the average of a field over various subsets of a queryset.</p> <pre><code>Player.objects.order_by('-score').filter(sex='male').aggregate(Avg('level')) </code></pre> <p>This works perfectly! </p> <hr> <p><strong>But...</strong> if I try to compute it for the <strong>top 50 players</strong> i...
2
2010-03-20T03:52:23Z
2,481,880
<pre><code>topfifty = Player.objects.order_by('-score')[:50] Player.objects.filter(sex='male',pk__in=topfifty).aggregate(avglevel=Avg('level')) </code></pre> <p>edit: i haven't tested this, but i think you get the idea of where i'm going.</p> <pre><code>topfifty = Player.objects.order_by('-score')[:50] ids = [] for t...
3
2010-03-20T04:09:22Z
[ "python", "database", "django", "django-models" ]
Aggregation over a few models - Django
2,481,839
<p>I'm trying to compute the average of a field over various subsets of a queryset.</p> <pre><code>Player.objects.order_by('-score').filter(sex='male').aggregate(Avg('level')) </code></pre> <p>This works perfectly! </p> <hr> <p><strong>But...</strong> if I try to compute it for the <strong>top 50 players</strong> i...
2
2010-03-20T03:52:23Z
2,481,931
<p>Hmm. The docs say</p> <p>"Slicing. As explained in Limiting QuerySets, a QuerySet can be sliced, using Python's array-slicing syntax. Usually slicing a QuerySet returns another (unevaluated) QuerySet, but Django will execute the database query if you use the "step" parameter of slice syntax." <a href="http://docs.d...
0
2010-03-20T04:34:21Z
[ "python", "database", "django", "django-models" ]
Aggregation over a few models - Django
2,481,839
<p>I'm trying to compute the average of a field over various subsets of a queryset.</p> <pre><code>Player.objects.order_by('-score').filter(sex='male').aggregate(Avg('level')) </code></pre> <p>This works perfectly! </p> <hr> <p><strong>But...</strong> if I try to compute it for the <strong>top 50 players</strong> i...
2
2010-03-20T03:52:23Z
2,484,904
<p>Break the problem up into two logical steps; figure out the target set, perform the aggregate calculation.</p> <pre><code>top50_male_players = Player.objects.filter(sex='male').order_by('-score')[:50] result = Player.objects.filter(pk__in=top50_male_players).aggregate(Avg('level')) </code></pre> <p>Thanks to lazy ...
3
2010-03-20T21:46:10Z
[ "python", "database", "django", "django-models" ]
How to create instances of related models in Django
2,481,860
<p>I'm working on a CMSy app for which I've implemented a set of models which allow for creation of custom Template instances, made up of a number of Fields and tied to a specific Customer. The end-goal is that one or more templates with a set of custom fields can be defined through the Admin interface and associated t...
3
2010-03-20T04:00:10Z
2,482,626
<p>It would just be:</p> <pre><code>my_customer.templates.add(my_template) </code></pre> <p>where <code>my_customer</code> and <code>my_template</code> are instances of <code>Customer</code> and <code>Template</code> respectively.</p> <p>See <a href="http://docs.djangoproject.com/en/1.1/ref/models/relations/" rel="n...
0
2010-03-20T10:20:18Z
[ "python", "django", "models" ]
How to create instances of related models in Django
2,481,860
<p>I'm working on a CMSy app for which I've implemented a set of models which allow for creation of custom Template instances, made up of a number of Fields and tied to a specific Customer. The end-goal is that one or more templates with a set of custom fields can be defined through the Admin interface and associated t...
3
2010-03-20T04:00:10Z
2,482,870
<p>Sorry if I wasn't clear. The problem is how to create instances based on a template, not how to create the templates. </p> <p>My Template class is used to define what Fields a given template contains and what Customers can use it. My ContentObject class is intended to define a content record based on a Template. </...
0
2010-03-20T11:47:26Z
[ "python", "django", "models" ]
How to create instances of related models in Django
2,481,860
<p>I'm working on a CMSy app for which I've implemented a set of models which allow for creation of custom Template instances, made up of a number of Fields and tied to a specific Customer. The end-goal is that one or more templates with a set of custom fields can be defined through the Admin interface and associated t...
3
2010-03-20T04:00:10Z
2,482,919
<p>If you want to stick with this model architecture, you need to add another field to the ContentObject class that will serve to store the actual content. It could be something like:</p> <pre><code>ContentObject(models.Model): ... fields_content = models.ManyToManyField(Field, through=FieldContent) ... </...
1
2010-03-20T12:05:10Z
[ "python", "django", "models" ]
How to create instances of related models in Django
2,481,860
<p>I'm working on a CMSy app for which I've implemented a set of models which allow for creation of custom Template instances, made up of a number of Fields and tied to a specific Customer. The end-goal is that one or more templates with a set of custom fields can be defined through the Admin interface and associated t...
3
2010-03-20T04:00:10Z
2,545,514
<p>To expand on pawartur's answer there are a couple of ways you can handle multiple (possibly complex) data types for the fields. One way you could try is to use model inheritance, maybe something like this:</p> <pre><code>class FieldContent(models.Model): field = models.ForeignKey(Field) content_object = mod...
0
2010-03-30T13:27:01Z
[ "python", "django", "models" ]
How to read line by line in pdf file using PyPdf?
2,481,945
<p>I have some code to read from a pdf file. Is there a way to read line by line from the pdf file (not pages) using Pypdf, Python 2.6, on Windows?</p> <p>Here is the code for reading the pdf pages:</p> <pre><code>import pyPdf def getPDFContent(path): content = "" num_pages = 10 p = file(path, "rb") ...
16
2010-03-20T04:39:04Z
2,482,054
<p>Looks like what you have is a large chunk of text data that you want to interpret line-by-line.</p> <p>You can use the StringIO class to wrap that content as a seekable file-like object:</p> <pre><code>&gt;&gt;&gt; import StringIO &gt;&gt;&gt; content = 'big\nugly\ncontents\nof\nmultiple\npdf files' &gt;&gt;&gt; b...
6
2010-03-20T05:24:55Z
[ "python", "pdf", "pypdf" ]
How to read line by line in pdf file using PyPdf?
2,481,945
<p>I have some code to read from a pdf file. Is there a way to read line by line from the pdf file (not pages) using Pypdf, Python 2.6, on Windows?</p> <p>Here is the code for reading the pdf pages:</p> <pre><code>import pyPdf def getPDFContent(path): content = "" num_pages = 10 p = file(path, "rb") ...
16
2010-03-20T04:39:04Z
5,895,960
<pre><code>import pyPdf def getPDFContent(path): content = "" num_pages = 10 p = file(path, "rb") pdf = pyPdf.PdfFileReader(p) for i in range(0, num_pages): content += pdf.getPage(i).extractText() + "\n" content = " ".join(content.replace(u"\xa0", " ").strip().split()) return ...
5
2011-05-05T10:09:00Z
[ "python", "pdf", "pypdf" ]
How to read line by line in pdf file using PyPdf?
2,481,945
<p>I have some code to read from a pdf file. Is there a way to read line by line from the pdf file (not pages) using Pypdf, Python 2.6, on Windows?</p> <p>Here is the code for reading the pdf pages:</p> <pre><code>import pyPdf def getPDFContent(path): content = "" num_pages = 10 p = file(path, "rb") ...
16
2010-03-20T04:39:04Z
38,149,957
<p>Using <code>yield</code> and <a href="http://pybrary.net/pyPdf/pythondoc-pyPdf.pdf.html#pyPdf.pdf.PdfFileReader.pages-attribute" rel="nofollow"><code>PdfFileReader.pages</code></a> can simplify things,</p> <pre><code>from pyPdf import PdfFileReader def get_pdf_content_lines(pdf_file_path): with open(pdf_file_p...
0
2016-07-01T16:18:47Z
[ "python", "pdf", "pypdf" ]
How do I use py2exe with paver?
2,481,971
<p>I'm using paver to build my Python application, and I'd like to create an executable using py2exe. I've got the following in my pavement.py:</p> <pre><code>from paver.setuputils import setup from distutils.core import setup import py2exe import paver paver.setuputils.install_distutils_tasks() </code></pre> <p>.....
1
2010-03-20T04:49:45Z
2,493,787
<p>From the <a href="http://www.py2exe.org/index.cgi/Tutorial" rel="nofollow">tutorial</a>, you just pass your "main" python script to the <code>setup</code> command:</p> <pre><code>from distutils.core import setup import py2exe setup(console=['hello.py']) </code></pre> <p>Have you tried building your execuable this...
0
2010-03-22T16:08:19Z
[ "python", "py2exe", "paver" ]
How do I use py2exe with paver?
2,481,971
<p>I'm using paver to build my Python application, and I'd like to create an executable using py2exe. I've got the following in my pavement.py:</p> <pre><code>from paver.setuputils import setup from distutils.core import setup import py2exe import paver paver.setuputils.install_distutils_tasks() </code></pre> <p>.....
1
2010-03-20T04:49:45Z
4,422,447
<p>You are overwriting paver's setup with distutils one.</p> <p>Also, calling <code>paver.setuputils.install_distutils_tasks()</code> is not needed; just call setup in same was as You do in <code>setup.py</code>. </p>
0
2010-12-12T15:46:02Z
[ "python", "py2exe", "paver" ]
How do I use py2exe with paver?
2,481,971
<p>I'm using paver to build my Python application, and I'd like to create an executable using py2exe. I've got the following in my pavement.py:</p> <pre><code>from paver.setuputils import setup from distutils.core import setup import py2exe import paver paver.setuputils.install_distutils_tasks() </code></pre> <p>.....
1
2010-03-20T04:49:45Z
6,494,233
<p>I too am trying to use py2exe from paver. However, I ran into <a href="http://groups.google.com/group/paver/browse_thread/thread/5eb90f12298edc5a/1e14403b32152f42" rel="nofollow">the problem described here</a> and from that (and some other googling around) my conclusion is that the two aren't integrated and that th...
0
2011-06-27T14:14:25Z
[ "python", "py2exe", "paver" ]
Convert the mysql table details to an Excel (.xls) or comma separated file (.csv) using Python
2,482,024
<p>I want to convert the mysql database table contents to an Excel(.xls) or comma separated file(csv) using python script... Is it possible? Any one can help me?</p> <p>Thanks in advance, Nimmy</p>
0
2010-03-20T05:11:58Z
2,482,041
<p>With third-party project <a href="http://sourceforge.net/projects/mysql-python/" rel="nofollow">mysqldb</a> installed you can easily read that table, e.g:</p> <pre><code>import MySQLdb conn = MySQLdb.connect (host = "localhost", user = "testuser", passwd = "testpass",...
1
2010-03-20T05:18:14Z
[ "python", "mysql", "file", "csv", "xlwt" ]
python metaprogramming
2,482,060
<p>I'm trying to archive a task which turns out to be a bit complicated since I'm not very good at Python metaprogramming.</p> <p>I want to have a module <code>locations</code> with function <code>get_location(name)</code>, which returns a class defined in a folder locations/ in the file with the name passed to functi...
3
2010-03-20T05:26:27Z
2,482,066
<p>I think you're looking for:</p> <pre><code>location = __import__('first') </code></pre>
1
2010-03-20T05:30:32Z
[ "python", "metaprogramming", "python-module" ]
python metaprogramming
2,482,060
<p>I'm trying to archive a task which turns out to be a bit complicated since I'm not very good at Python metaprogramming.</p> <p>I want to have a module <code>locations</code> with function <code>get_location(name)</code>, which returns a class defined in a folder locations/ in the file with the name passed to functi...
3
2010-03-20T05:26:27Z
2,482,074
<p>You do need to <code>__import__</code> the module; after that, getting an attr from it is not hard.</p> <pre><code>import sys def get_location(name): fullpath = 'locations.' + name package = __import__(fullpath) module = sys.modules[fullpath] return getattr(module, name.title() + 'Location') </code...
6
2010-03-20T05:32:22Z
[ "python", "metaprogramming", "python-module" ]
GetLastInputInfo equivalent in Linux to detect last input time
2,482,103
<p>Is there a <a href="http://www.geekpedia.com/tutorial210_Retrieving-the-Operating-System-Idle-Time-Uptime-and-Last-Input-Time.html" rel="nofollow">GetLastInputInfo</a>() equivalent that can be used in Linux?</p> <p>The intention is to detect the last input time (keyboard or mouse) of the user. Am using python to sc...
2
2010-03-20T05:47:53Z
2,482,175
<p><code>XScreenSaverQueryInfo</code></p> <blockquote> <p>The idle field specifies the number of milliseconds since the last input was received from the user on any of the input devices. The event-mask field specifies which, if any, screen saver events this client has requested using ScreenSaverSelectInput.</p> </...
3
2010-03-20T06:20:13Z
[ "python", "linux", "time", "input" ]
Send an email using python script
2,482,160
<p>Today I needed to send email from a Python script. As always I searched Google and found the following script that fits to my need.</p> <pre><code>import smtplib SERVER = "localhost" FROM = "sender@example.com" TO = ["user@example.com"] # must be a list SUBJECT = "Hello!" TEXT = "This message was sent with Pyth...
9
2010-03-20T06:13:18Z
2,482,173
<p>Did you name your script <code>email.py</code>?</p> <p>If so, rename to something else and the naming conflict you're encountering should be solved.</p>
5
2010-03-20T06:18:47Z
[ "python", "email" ]
Send an email using python script
2,482,160
<p>Today I needed to send email from a Python script. As always I searched Google and found the following script that fits to my need.</p> <pre><code>import smtplib SERVER = "localhost" FROM = "sender@example.com" TO = ["user@example.com"] # must be a list SUBJECT = "Hello!" TEXT = "This message was sent with Pyth...
9
2010-03-20T06:13:18Z
2,482,176
<p>You've named your module the same as one of Python's internal modules. When you import <code>smtplib</code>, it tries to import <code>email</code>, and finds your module instead of the internal one. When two modules import one another, only the variables in each module visible before the both import statements wil...
14
2010-03-20T06:20:23Z
[ "python", "email" ]