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
web ERP in django where do i start?
2,209,125
<p>I'm a computer science student doing my bachelor's degree. i'm interested in doing an simple application like an ERP in django. I've got about a month of time don't know where do i start. please do give in your opinion.</p>
3
2010-02-05T17:39:19Z
8,255,500
<p>Have a look at <a href="http://code.google.com/p/prometeo-erp/" rel="nofollow">Prometeo ERP</a>. It's based on Django 1.3 and it requires only a few dependencies...</p>
2
2011-11-24T10:23:36Z
[ "python", "django", "web-applications" ]
Using Postgres in a web app: "transaction aborted" errors
2,209,169
<p>Recently I moved a web app I'm developing from MySQL to PostgreSQL for performance reasons (I need functionality PostGIS provides). Now quite often encounter the following error:</p> <p><code>current transaction is aborted, commands ignored until end of transaction block</code></p> <p>The server application uses m...
2
2010-02-05T17:46:48Z
2,209,356
<p>that error is caused because of a precedent error. look at this piece of code:</p> <pre><code>&gt;&gt;&gt; import psycopg2 &gt;&gt;&gt; conn = psycopg2.connect('') &gt;&gt;&gt; cur = conn.cursor() &gt;&gt;&gt; cur.execute('select current _date') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ...
6
2010-02-05T18:17:30Z
[ "python", "postgresql", "concurrency" ]
In Python, how to access a uint16[3] array wrapped by SWIG (i.e. unwrap a PySwigObject)?
2,209,395
<p>This is Python question. I have a variable A</p> <pre><code>&gt;&gt;&gt; A &lt;Swig Object of type 'uint16_t *' at 0x8c66fa0&gt; &gt;&gt;&gt; help(A) class PySwigObject(object) Swig object carries a C/C++ instance pointer </code></pre> <p>The instance referred by A is a contiguous array uint16[3] and the probl...
4
2010-02-05T18:24:11Z
2,215,833
<p>After more reading and trying stuff out, the answers are as follows:</p> <pre> 1. The wrapped pointer in PySwigObject A is available as A.__long__() . 2. A raw pointer can be cast into an indexable type using ctypes as follows import ctypes pA = ctypes.cast( A.__long__(), ctypes.POINTER( ctypes.c_uint16 ) ) </pr...
6
2010-02-07T03:44:30Z
[ "python", "swig", "ctypes" ]
InternalError: current transaction is aborted, commands ignored until end of transaction block
2,209,560
<p>I'm getting this error when doing database calls in a sub process using multiprocessing library.</p> <p>Visit : <a href="http://pastie.org/811424" rel="nofollow">Pastie</a></p> <blockquote> <p>InternalError: current transaction is aborted, commands ignored until end of transaction block</p> </blockquote> <p>t...
3
2010-02-05T18:53:25Z
2,209,958
<p>multiprocessing works (on UNIX systems) by forking the current process. If you have an existing database connection, this will leave the two processes (the current one and the new one) with the same database connection. Trying to use it from both is bad. Create a new database connection in the child process instead....
6
2010-02-05T19:51:05Z
[ "python", "postgresql", "multiprocessing", "psycopg2", "web.py" ]
Python != operation vs "is not"
2,209,755
<p>In a comment on <a href="http://stackoverflow.com/questions/2079786/caching-sitemaps-in-django">this question</a>, I saw a statement that recommended using</p> <pre><code>result is not None </code></pre> <p>vs</p> <pre><code>result != None </code></pre> <p>I was wondering what the difference is, and why one migh...
99
2010-02-05T19:21:45Z
2,209,769
<p><code>None</code> is a singleton, therefore identity comparison will always work, whereas an object can fake the equality comparison via <code>.__eq__()</code>.</p>
11
2010-02-05T19:23:02Z
[ "python", "operators" ]
Python != operation vs "is not"
2,209,755
<p>In a comment on <a href="http://stackoverflow.com/questions/2079786/caching-sitemaps-in-django">this question</a>, I saw a statement that recommended using</p> <pre><code>result is not None </code></pre> <p>vs</p> <pre><code>result != None </code></pre> <p>I was wondering what the difference is, and why one migh...
99
2010-02-05T19:21:45Z
2,209,781
<p><code>==</code> is an <strong>equality test</strong>. It checks whether the right hand side and the left hand side are equal objects (according to their <code>__eq__</code> or <code>__cmp__</code> methods.)</p> <p><code>is</code> is an <strong>identity test</strong>. It checks whether the right hand side and the le...
130
2010-02-05T19:25:05Z
[ "python", "operators" ]
Python != operation vs "is not"
2,209,755
<p>In a comment on <a href="http://stackoverflow.com/questions/2079786/caching-sitemaps-in-django">this question</a>, I saw a statement that recommended using</p> <pre><code>result is not None </code></pre> <p>vs</p> <pre><code>result != None </code></pre> <p>I was wondering what the difference is, and why one migh...
99
2010-02-05T19:21:45Z
2,210,044
<p>Consider the following:</p> <pre><code>class Bad(object): def __eq__(self, other): return True c = Bad() c is None # False, equivalent to id(c) == id(None) c == None # True, equivalent to c.__eq__(None) </code></pre>
15
2010-02-05T20:03:36Z
[ "python", "operators" ]
Python != operation vs "is not"
2,209,755
<p>In a comment on <a href="http://stackoverflow.com/questions/2079786/caching-sitemaps-in-django">this question</a>, I saw a statement that recommended using</p> <pre><code>result is not None </code></pre> <p>vs</p> <pre><code>result != None </code></pre> <p>I was wondering what the difference is, and why one migh...
99
2010-02-05T19:21:45Z
2,210,112
<pre> >>> () is () True >>> 1 is 1 True >>> (1,) == (1,) True >>> (1,) is (1,) False >>> a = (1,) >>> b = a >>> a is b True </pre> <p>Some objects are singletons, and thus <code>is</code> with them is equivalent to <code>==</code>. Most are not.</p>
5
2010-02-05T20:14:59Z
[ "python", "operators" ]
Python != operation vs "is not"
2,209,755
<p>In a comment on <a href="http://stackoverflow.com/questions/2079786/caching-sitemaps-in-django">this question</a>, I saw a statement that recommended using</p> <pre><code>result is not None </code></pre> <p>vs</p> <pre><code>result != None </code></pre> <p>I was wondering what the difference is, and why one migh...
99
2010-02-05T19:21:45Z
2,210,222
<p>First, let me go over a few terms. If you just want your question answered, scroll down to "Answering your question".</p> <h2>Definitions</h2> <p><strong>Object identity</strong>: When you create an object, you can assign it to a variable. You can then also assign it to another variable. And another.</p> <pre><co...
80
2010-02-05T20:32:49Z
[ "python", "operators" ]
Memcached getting null for String set with python and then get from Java
2,209,864
<p>When I try to read a String from memcached that I set in python:</p> <pre><code>import memcache MC_SERVER = "192.168.1.100" MC_PORT = "11211" mc = memcache.Client(['%s:%s' % (MC_SERVER, MC_PORT)], debug=0) mc.set("test_string", "true") print mc.get("test_string") </code></pre> <p>Java tells me is doesn't exist a...
8
2010-02-05T19:37:57Z
2,210,454
<p>Doesn't Java use unicode? If so, I suspect that python is writing to memcache using the ASCII / latin 1 character set. As a result, the keys look very different ("test_string" vs. "t\00e\00s\00t\00_\00s\00t\00r\00i\00n\00g\00").</p> <p>Try using this, and see what happens.</p> <pre><code>import memcache MC_SERVER...
1
2010-02-05T21:11:34Z
[ "java", "python", "memcached" ]
Memcached getting null for String set with python and then get from Java
2,209,864
<p>When I try to read a String from memcached that I set in python:</p> <pre><code>import memcache MC_SERVER = "192.168.1.100" MC_PORT = "11211" mc = memcache.Client(['%s:%s' % (MC_SERVER, MC_PORT)], debug=0) mc.set("test_string", "true") print mc.get("test_string") </code></pre> <p>Java tells me is doesn't exist a...
8
2010-02-05T19:37:57Z
4,576,301
<p>The solution right from documentation:</p> <blockquote> <p>If you need to support multiple clients (i.e. Java, PHP, Perl, etc.) you need to make a few changes when you are setting things up:</p> </blockquote> <pre><code>// use a compatible hashing algorithm pool.setHashingAlg( SockIOPool.NEW_COMPAT_HASH );...
4
2011-01-01T23:30:18Z
[ "java", "python", "memcached" ]
Memcached getting null for String set with python and then get from Java
2,209,864
<p>When I try to read a String from memcached that I set in python:</p> <pre><code>import memcache MC_SERVER = "192.168.1.100" MC_PORT = "11211" mc = memcache.Client(['%s:%s' % (MC_SERVER, MC_PORT)], debug=0) mc.set("test_string", "true") print mc.get("test_string") </code></pre> <p>Java tells me is doesn't exist a...
8
2010-02-05T19:37:57Z
25,935,987
<p>Make sure that <code>memcached</code> service is started , if it is already started then restart the service.</p>
1
2014-09-19T14:12:07Z
[ "java", "python", "memcached" ]
Memcached getting null for String set with python and then get from Java
2,209,864
<p>When I try to read a String from memcached that I set in python:</p> <pre><code>import memcache MC_SERVER = "192.168.1.100" MC_PORT = "11211" mc = memcache.Client(['%s:%s' % (MC_SERVER, MC_PORT)], debug=0) mc.set("test_string", "true") print mc.get("test_string") </code></pre> <p>Java tells me is doesn't exist a...
8
2010-02-05T19:37:57Z
32,926,390
<p>It is bug in your Java client. You should get forked project with fixes: <a href="https://github.com/zmokhtar/Memcached-Java-Client" rel="nofollow">https://github.com/zmokhtar/Memcached-Java-Client</a></p> <p><strong>EDIT</strong></p> <p>I can reproduce problem with gwhalin/Memcached-Java-Client, but everything is...
1
2015-10-03T19:07:05Z
[ "java", "python", "memcached" ]
Memcached getting null for String set with python and then get from Java
2,209,864
<p>When I try to read a String from memcached that I set in python:</p> <pre><code>import memcache MC_SERVER = "192.168.1.100" MC_PORT = "11211" mc = memcache.Client(['%s:%s' % (MC_SERVER, MC_PORT)], debug=0) mc.set("test_string", "true") print mc.get("test_string") </code></pre> <p>Java tells me is doesn't exist a...
8
2010-02-05T19:37:57Z
32,940,076
<p>change to use <code>pylibmc</code> to solve it:</p> <pre><code>import pylibmc mc = pylibmc.Client(["127.0.0.1"], binary=True, behaviors={"tcp_nodelay": True, "ketama": True}) key="someKey" i=0 while True: #mc.set(key, str(i)) value = mc.get(key) print(...
2
2015-10-05T01:19:48Z
[ "java", "python", "memcached" ]
How to use C++ operators within python using boost::python (pyopencv)
2,209,889
<p>I'm using the pyopencv bindings. This python lib uses boost::python to connect to OopenCV. Now I'm trying to use the SURF class but don't know how to handle the class operator in my python code.</p> <p>The C++ class is defined as:</p> <pre><code>void SURF::operator()(const Mat&amp; img, const Mat&amp; mask, ...
1
2010-02-05T19:41:23Z
2,210,209
<p>You just call it as if it was a function. If <code>surf_inst</code> is an instance of the <code>SURF</code> class, you would call:</p> <pre><code>newKeyPoints = surf_inst(img, mask, keypoints) </code></pre> <p>The argument <code>keypoints</code> is expected to be a tuple, and <code>img</code> and <code>mask</code>...
1
2010-02-05T20:30:06Z
[ "c++", "python", "operators", "operator-overloading", "boost-python" ]
How do I generate a table of contents for HTML text in Python?
2,210,265
<p>Assume that I have some HTML code, like this (generated from Markdown or Textile or something):</p> <pre><code>&lt;h1&gt;A header&lt;/h1&gt; &lt;p&gt;Foo&lt;/p&gt; &lt;h2&gt;Another header&lt;/h2&gt; &lt;p&gt;More content&lt;/p&gt; &lt;h2&gt;Different header&lt;/h2&gt; &lt;h1&gt;Another toplevel header &lt;!-- and ...
1
2010-02-05T20:40:11Z
2,210,269
<p>Use an HTML parser such as <a href="http://codespeak.net/lxml/" rel="nofollow">lxml</a> or <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a> to find all header elements.</p>
6
2010-02-05T20:41:09Z
[ "python", "html", "tableofcontents" ]
How do I generate a table of contents for HTML text in Python?
2,210,265
<p>Assume that I have some HTML code, like this (generated from Markdown or Textile or something):</p> <pre><code>&lt;h1&gt;A header&lt;/h1&gt; &lt;p&gt;Foo&lt;/p&gt; &lt;h2&gt;Another header&lt;/h2&gt; &lt;p&gt;More content&lt;/p&gt; &lt;h2&gt;Different header&lt;/h2&gt; &lt;h1&gt;Another toplevel header &lt;!-- and ...
1
2010-02-05T20:40:11Z
2,210,893
<p>Here's an example using lxml and xpath.</p> <pre><code>from lxml import etree doc = etree.parse("test.xml") for node in doc.xpath('//h1|//h2|//h3|//h4|//h5'): print node.tag, node.text </code></pre>
3
2010-02-05T22:26:59Z
[ "python", "html", "tableofcontents" ]
print beautiful value with error
2,210,475
<p>I want to display in a HTML page some datas with errors, for example:</p> <pre> (value, error) -> string (123, 12) -> (12 +- 1) x 10^1 (4234.3, 2) -> (4234 +- 2) (0.02312, 0.003) -> (23 +- 3) x 10^-3 </pre> <p>I've produced this:</p> <pre><code> from math import log10 def format_value_error(value,error): E = ...
0
2010-02-05T21:14:22Z
2,210,511
<p>I'm not sure exactly what you want, but I assume you just want to round the numbers you have to the nearest integer? If so, you can use the built-in function <code>round</code>: </p> <pre><code>&gt;&gt;&gt; int(round(1.5)) 2 </code></pre> <p>Here's the help:</p> <pre><code>&gt;&gt;&gt; help(round) Help on built-i...
3
2010-02-05T21:20:27Z
[ "python", "math", "statistics", "printing" ]
print beautiful value with error
2,210,475
<p>I want to display in a HTML page some datas with errors, for example:</p> <pre> (value, error) -> string (123, 12) -> (12 +- 1) x 10^1 (4234.3, 2) -> (4234 +- 2) (0.02312, 0.003) -> (23 +- 3) x 10^-3 </pre> <p>I've produced this:</p> <pre><code> from math import log10 def format_value_error(value,error): E = ...
0
2010-02-05T21:14:22Z
2,210,588
<p>You could use this in Mark's solution to blank the exponent for <code>10^0</code></p> <pre><code> if E: return "(%d +- %d) x 10^%d" % (val, err, E) else: return "(%d +- %d)" % (val, err) </code></pre>
0
2010-02-05T21:32:42Z
[ "python", "math", "statistics", "printing" ]
Python xml.dom.minidom removeChild whitespace problem
2,210,488
<p>I'm trying to read an xml file into python, pull out certain elements from the xml file and then write the results back to an xml file (so basically it's the original xml file without several elements). When I use .removeChild(source) it removes the individual elements I want to remove but leaves white space in its ...
0
2010-02-05T21:16:47Z
2,210,689
<p>If you have PyXML installed you can use xml.dom.ext.PrettyPrint()</p>
1
2010-02-05T21:46:55Z
[ "python", "xml", "whitespace", "removechild" ]
Python xml.dom.minidom removeChild whitespace problem
2,210,488
<p>I'm trying to read an xml file into python, pull out certain elements from the xml file and then write the results back to an xml file (so basically it's the original xml file without several elements). When I use .removeChild(source) it removes the individual elements I want to remove but leaves white space in its ...
0
2010-02-05T21:16:47Z
2,213,876
<p>I couldn't figure out how to do this using xml.dom.minidom, so I just wrote a quick function to read in the output file and remove all blank lines and then rewrite to a new file:</p> <pre><code>f = open(xmlfile).readlines() w = open('src_model.xml','w') empty=re.compile('^$') for line in open(xmlfile).readlines(): ...
1
2010-02-06T17:05:09Z
[ "python", "xml", "whitespace", "removechild" ]
Python xml.dom.minidom removeChild whitespace problem
2,210,488
<p>I'm trying to read an xml file into python, pull out certain elements from the xml file and then write the results back to an xml file (so basically it's the original xml file without several elements). When I use .removeChild(source) it removes the individual elements I want to remove but leaves white space in its ...
0
2010-02-05T21:16:47Z
3,695,653
<p>… for searching ppl:</p> <p>This funny snippet</p> <pre><code>skey = lambda x: getattr(x, "tagName", None) mainnode.childNodes = sorted( [n for n in mainnode.childNodes if n.nodeType != n.TEXT_NODE], cmp=lambda x, y: cmp(skey(y), skey(x))) </code></pre> <p>removes all text nodes (and, also, reverse sorts t...
0
2010-09-12T16:44:45Z
[ "python", "xml", "whitespace", "removechild" ]
Map List of Tuples into a Dictionary, python
2,210,581
<p>I've got a list of tuples extracted from a table in a DB which looks like (<em>key</em> , <em>foreignkey</em> , <em>value</em>). There is a many to one relationship between the key and foreignkeys and I'd like to convert it into a dict indexed by the foreignkey containing the sum of all values with that foreignkey,...
4
2010-02-05T21:31:32Z
2,210,612
<p>Assuming all your values are <code>int</code>s, you could use a <code>defaultdict</code> to make this easier:</p> <pre><code>from collections import defaultdict myDict = defaultdict(int) for item in myTupleList: myDict[item[1]] += item[2] </code></pre> <p><code>defaultdict</code> is like a dictionary, except...
8
2010-02-05T21:35:51Z
[ "python", "list", "dictionary", "tuples" ]
Map List of Tuples into a Dictionary, python
2,210,581
<p>I've got a list of tuples extracted from a table in a DB which looks like (<em>key</em> , <em>foreignkey</em> , <em>value</em>). There is a many to one relationship between the key and foreignkeys and I'd like to convert it into a dict indexed by the foreignkey containing the sum of all values with that foreignkey,...
4
2010-02-05T21:31:32Z
2,210,620
<p>Maybe not exactly readable but it should work:</p> <pre><code>fks = dict([ (v[1], True) for v in myTupleList ]).keys() myDict = dict([ (fk, sum([ v[2] for v in myTupleList if v[1] == fk ])) for fk in fks ]) </code></pre> <p>The first line finds all unique foreign keys. The second line builds your dictionary by fir...
0
2010-02-05T21:36:52Z
[ "python", "list", "dictionary", "tuples" ]
Map List of Tuples into a Dictionary, python
2,210,581
<p>I've got a list of tuples extracted from a table in a DB which looks like (<em>key</em> , <em>foreignkey</em> , <em>value</em>). There is a many to one relationship between the key and foreignkeys and I'd like to convert it into a dict indexed by the foreignkey containing the sum of all values with that foreignkey,...
4
2010-02-05T21:31:32Z
2,210,622
<p>Look at <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a> and see if that does all the mapping you need and perhaps more</p>
0
2010-02-05T21:36:55Z
[ "python", "list", "dictionary", "tuples" ]
Map List of Tuples into a Dictionary, python
2,210,581
<p>I've got a list of tuples extracted from a table in a DB which looks like (<em>key</em> , <em>foreignkey</em> , <em>value</em>). There is a many to one relationship between the key and foreignkeys and I'd like to convert it into a dict indexed by the foreignkey containing the sum of all values with that foreignkey,...
4
2010-02-05T21:31:32Z
2,210,697
<pre><code>from collections import defaultdict myDict = defaultdict(int) for _, key, value in myTupleList: myDict[key] += value </code></pre>
4
2010-02-05T21:47:48Z
[ "python", "list", "dictionary", "tuples" ]
Map List of Tuples into a Dictionary, python
2,210,581
<p>I've got a list of tuples extracted from a table in a DB which looks like (<em>key</em> , <em>foreignkey</em> , <em>value</em>). There is a many to one relationship between the key and foreignkeys and I'd like to convert it into a dict indexed by the foreignkey containing the sum of all values with that foreignkey,...
4
2010-02-05T21:31:32Z
2,210,813
<p>Here's my (tongue in cheek) answer:</p> <pre><code>myDict = reduce(lambda d, t: (d.__setitem__(t[1], d.get(t[1], 0) + t[2]), d)[1], myTupleList, {}) </code></pre> <p>It is ugly and bad, but here is how it works.</p> <p>The first argument to reduce (because it isn't clear there) is <code>lambda d, t: (d.__setitem_...
4
2010-02-05T22:09:27Z
[ "python", "list", "dictionary", "tuples" ]
Only connect to database when necessary
2,210,646
<p>I'm using Pylons + Python and am trying to figure how how to connect to our central database server only when necessary. </p> <p>I created a class called Central() which I would like to instantiate whenever a connection to the central database server is necessary, e.g.:</p> <pre><code>class Central(): def __init...
1
2010-02-05T21:41:03Z
2,210,666
<p>Can you define "doesn't work"?</p> <p>If you want to use <code>central_db</code> and <code>engine</code> later, you need to store them in the object (use <code>self.central_db</code>, <code>self.engine</code>, you can later access them as <code>c.central_db</code> and <code>c.engine</code>). Now they're just local ...
0
2010-02-05T21:43:55Z
[ "python", "sqlalchemy", "pylons" ]
Only connect to database when necessary
2,210,646
<p>I'm using Pylons + Python and am trying to figure how how to connect to our central database server only when necessary. </p> <p>I created a class called Central() which I would like to instantiate whenever a connection to the central database server is necessary, e.g.:</p> <pre><code>class Central(): def __init...
1
2010-02-05T21:41:03Z
2,287,536
<p>Since I can't tell what's the layout of your code, I can only assume that you've got <code>engine</code> and <code>central_db</code> defined somewhere in the global context. Is that correct? If so you could try something like this:</p> <pre><code>def __init__(self): global engine global central_db engin...
1
2010-02-18T09:32:53Z
[ "python", "sqlalchemy", "pylons" ]
customize filter or property in sqlalchemy
2,210,722
<p>I'm using the SQLAlchemy ORM to work with both MySQL and sqlite. Suppose I have a function that will take input from a column of string type and finally return an integer. The logic of this function may be complicated that can not be implemented by simply using built-in SQL functions provided by back-end database e...
1
2010-02-05T21:53:50Z
15,878,739
<p>@BingJian You can implement this with the help of <a href="http://docs.sqlalchemy.org/en/rel_0_7/orm/extensions/hybrid.html" rel="nofollow"><code>hybrid</code> extension</a>.</p> <p>In hybrid you can define function which will be call when you do filter on that field. You have to handle those operation in functions...
0
2013-04-08T12:12:10Z
[ "python", "sqlalchemy" ]
Dynamically select database based on request
2,210,914
<p>I'm trying to keep my RESTful site DRY, and I can't come up with a good way to factor out the code to dynamically select from each "user's" separate database. We've got a separate database for each client. This comes in as a part of the URL, and is passed into each view as a keyword arg. I want to give each and ever...
1
2010-02-05T22:30:30Z
2,210,977
<p>We do this by the following technique.</p> <ol> <li><p>Apache picks off the first part of the path and routes this to a specific mod_wsgi Daemon.</p></li> <li><p>Each mod_wsgi daemon is a different customer's installation.</p></li> </ol> <p>We have many parallel customers, each with (nearly) identical code, all ba...
1
2010-02-05T22:44:56Z
[ "python", "django" ]
SQLAlchemy Basic Question
2,211,070
<p>To anyone with experience of SQLAlchemy, this will be basic I am sure; But I don't find the docs that helpful and I am sick of scratching my head.</p> <p>Given two classes:</p> <pre><code>class User(Base): __tablename__='users' id = Column(Integer, primary_key=True) name = Column(String(32)) ... c...
3
2010-02-05T23:00:42Z
2,212,891
<p>Maybe you should start with <a href="http://elixir.ematia.de/" rel="nofollow">elixir</a> which provides a simpler interface to sqlalchemy:</p> <pre><code>from elixir import * metadata.bind = 'sqlite:///:memory:' class User(Entity): name = Field(String(32)) posts = OneToMany('Post') class Post(Entity): ...
1
2010-02-06T11:14:17Z
[ "python", "orm", "sqlalchemy" ]
SQLAlchemy Basic Question
2,211,070
<p>To anyone with experience of SQLAlchemy, this will be basic I am sure; But I don't find the docs that helpful and I am sick of scratching my head.</p> <p>Given two classes:</p> <pre><code>class User(Base): __tablename__='users' id = Column(Integer, primary_key=True) name = Column(String(32)) ... c...
3
2010-02-05T23:00:42Z
2,212,936
<p>Why not show how you have configured relation() ? That's probably the part that's not working.</p>
0
2010-02-06T11:35:25Z
[ "python", "orm", "sqlalchemy" ]
SQLAlchemy Basic Question
2,211,070
<p>To anyone with experience of SQLAlchemy, this will be basic I am sure; But I don't find the docs that helpful and I am sick of scratching my head.</p> <p>Given two classes:</p> <pre><code>class User(Base): __tablename__='users' id = Column(Integer, primary_key=True) name = Column(String(32)) ... c...
3
2010-02-05T23:00:42Z
2,256,154
<p>I think you just have the relation definition backwards.</p> <p>Try:</p> <pre><code>class User(Base): __tablename__='users' id = Column(Integer, primary_key=True) name = Column(String(32)) posts = relation("UserPost", backref="poster") class UserPost(Base): __tablename__='posts' id = Colum...
2
2010-02-13T01:34:46Z
[ "python", "orm", "sqlalchemy" ]
Python setuptools import error (Using NetBeans)
2,211,335
<p>I tried to find a question that would answer to this question but wasn't succesful, so I made a new question.</p> <p>I'm trying to compile my old Python Tic Tac Toe game in NetBeans, but I get the error message</p> <pre><code>ImportError: No module named setuptools </code></pre> <p>In my actual code I haven't imp...
17
2010-02-06T00:02:08Z
2,211,348
<p>You need to install either <a href="http://pypi.python.org/pypi/setuptools">setuptools</a> or <a href="http://pypi.python.org/pypi/distribute">Distribute</a> in your Python instance. Follow the directions at either web page.</p>
28
2010-02-06T00:07:05Z
[ "python", "netbeans", "setuptools", "importerror" ]
Python setuptools import error (Using NetBeans)
2,211,335
<p>I tried to find a question that would answer to this question but wasn't succesful, so I made a new question.</p> <p>I'm trying to compile my old Python Tic Tac Toe game in NetBeans, but I get the error message</p> <pre><code>ImportError: No module named setuptools </code></pre> <p>In my actual code I haven't imp...
17
2010-02-06T00:02:08Z
9,927,472
<pre><code>wget http://pypi.python.org/packages/source/s/setuptools/setuptools-0.6c11.tar.gz tar zxvf setuptools-0.6c11.tar.gz cd setuptools-0.6c11 python setup.py build python setup.py install </code></pre>
5
2012-03-29T14:31:14Z
[ "python", "netbeans", "setuptools", "importerror" ]
Python setuptools import error (Using NetBeans)
2,211,335
<p>I tried to find a question that would answer to this question but wasn't succesful, so I made a new question.</p> <p>I'm trying to compile my old Python Tic Tac Toe game in NetBeans, but I get the error message</p> <pre><code>ImportError: No module named setuptools </code></pre> <p>In my actual code I haven't imp...
17
2010-02-06T00:02:08Z
10,908,928
<p>Same answer as Satya, but easier to copy&amp;paste:</p> <pre><code>wget http://pypi.python.org/packages/source/s/setuptools/setuptools-0.6c11.tar.gz tar zxvf setuptools-0.6c11.tar.gz cd setuptools-0.6c11 python setup.py build sudo python setup.py install </code></pre>
0
2012-06-06T06:04:07Z
[ "python", "netbeans", "setuptools", "importerror" ]
Python setuptools import error (Using NetBeans)
2,211,335
<p>I tried to find a question that would answer to this question but wasn't succesful, so I made a new question.</p> <p>I'm trying to compile my old Python Tic Tac Toe game in NetBeans, but I get the error message</p> <pre><code>ImportError: No module named setuptools </code></pre> <p>In my actual code I haven't imp...
17
2010-02-06T00:02:08Z
18,328,039
<p>Same answer as above, but since I dont have comment rights here is the working version which ignores the certificate mismatch for ssl auto-redirect :</p> <pre><code>wget --no-check-certificate http://pypi.python.org/packages/source/s/setuptools/setuptools-0.6c11.tar.gz tar zxvf setuptools-0.6c11.tar.gz cd setuptool...
0
2013-08-20T06:07:38Z
[ "python", "netbeans", "setuptools", "importerror" ]
How to parse xsd:dateTime format?
2,211,362
<p>Values of type xsd:dateTime can have a variety of forms, as <a href="http://books.xmlschemata.org/relaxng/ch19-77049.html" rel="nofollow">described in <em>RELAX NG</em></a>.</p> <p>How can I parse all the forms into either time or datetime objects?</p>
4
2010-02-06T00:11:09Z
2,211,529
<p>It's actually a pretty restricted format, especially compared to all of ISO 8601. Using a regex is mostly the same as using <a href="http://docs.python.org/library/datetime.html#datetime.datetime.strptime" rel="nofollow">strptime</a> plus handling the offset yourself (which strptime doesn't do).</p> <pre><code>imp...
2
2010-02-06T01:06:24Z
[ "python", "xml" ]
How to parse xsd:dateTime format?
2,211,362
<p>Values of type xsd:dateTime can have a variety of forms, as <a href="http://books.xmlschemata.org/relaxng/ch19-77049.html" rel="nofollow">described in <em>RELAX NG</em></a>.</p> <p>How can I parse all the forms into either time or datetime objects?</p>
4
2010-02-06T00:11:09Z
3,870,655
<p>Try the <code>dateutil.parser</code> module from <a href="http://labix.org/python-dateutil#head-a23e8ae0a661d77b89dfb3476f85b26f0b30349c" rel="nofollow">python-dateutil</a>. Or maybe <a href="http://pypi.python.org/pypi/isodate" rel="nofollow">isodate</a> (haven't used the last one yet, but looks interesting (and ma...
1
2010-10-06T08:24:40Z
[ "python", "xml" ]
Python Build Problem on Mac OS 10.6 / Snow Leopard
2,211,387
<p>I'm encountering a build problem for Python 2.6.4 on Snow Leopard.</p> <ul> <li>Mac OS X 10.6</li> <li>Yonah CPU, <strong>32-bit</strong></li> <li>gcc-4.2.1</li> </ul> <hr> <p><strong>Update I</strong></p> <p>Solved by removing all non-standard includes and libraries from CFLAGS (there happened to be a <code>uui...
3
2010-02-06T00:19:43Z
2,211,420
<p>Try adding <code>--universal-archs=32-bit</code> to the <code>configure</code> arguments.</p> <p>EDIT: You may also need to set environment variable <code>MACOSX_DEPLOYMENT_TARGET=10.6</code> and explicitly use the 10.6 SDK:</p> <pre><code>export MACOSX_DEPLOYMENT_TARGET=10.6 ./configure --universal-archs=32-bit -...
4
2010-02-06T00:27:46Z
[ "python", "osx", "gcc", "build", "32-bit" ]
Python Build Problem on Mac OS 10.6 / Snow Leopard
2,211,387
<p>I'm encountering a build problem for Python 2.6.4 on Snow Leopard.</p> <ul> <li>Mac OS X 10.6</li> <li>Yonah CPU, <strong>32-bit</strong></li> <li>gcc-4.2.1</li> </ul> <hr> <p><strong>Update I</strong></p> <p>Solved by removing all non-standard includes and libraries from CFLAGS (there happened to be a <code>uui...
3
2010-02-06T00:19:43Z
2,211,424
<p>It seems that you aren't the only one running into this error:</p> <p>Not sure if this has the same root cause :</p> <p><a href="http://trac.macports.org/ticket/21282" rel="nofollow">http://trac.macports.org/ticket/21282</a></p> <p>Scroll down to the end comments,which seem to indicate a positive outcome. (repeat...
1
2010-02-06T00:29:01Z
[ "python", "osx", "gcc", "build", "32-bit" ]
Python module matrix class that implements Modulo 2 arithmetic?
2,211,405
<p>I'm looking for a pure Python module that implements a matrix class where the underlying matrix operations are computed in modulo 2 arithmetic as in</p> <pre><code>(x+y)%2 </code></pre> <p>I need to do a lot of basic matrix manipulations ( transpose, multiplication, etc. ).</p> <p>Any help appreciated.</p> <p>Th...
1
2010-02-06T00:22:58Z
2,211,425
<p><a href="http://wiki.python.org/moin/NumericAndScientific/Libraries" rel="nofollow">This</a> might help you. Look for the Matrix module on that page. Here is the <a href="http://www.nightmare.com/squirl/python-ext/misc/matrix.py" rel="nofollow">source</a>.</p> <p>cheers</p>
1
2010-02-06T00:29:03Z
[ "python", "matrix", "math" ]
Convention for checking the existence of a Django model?
2,211,530
<p>What is the accepted way of checking a model's existence in a Django app? </p> <p>I've seen this method used:</p> <pre><code>def profile_exists(user): try: UserProfile.objects.get(user = user) return True except: return False </code></pre> <p>Is ther...
2
2010-02-06T01:06:32Z
2,211,558
<p>Bare <code>except</code>s should not be used. Instead the model's <code>DoesNotExist</code> inner exception or <code>django.core.exceptions.ObjectDoesNotExist</code> <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#id5" rel="nofollow">should be caught</a>.</p> <p>Beyond that, either this or using...
2
2010-02-06T01:15:30Z
[ "python", "django", "django-models" ]
Convention for checking the existence of a Django model?
2,211,530
<p>What is the accepted way of checking a model's existence in a Django app? </p> <p>I've seen this method used:</p> <pre><code>def profile_exists(user): try: UserProfile.objects.get(user = user) return True except: return False </code></pre> <p>Is ther...
2
2010-02-06T01:06:32Z
2,211,592
<p>That is suitable until the naked <code>except</code>. You always get more than you bargain for with those!</p> <p>As mentioned by <a href="http://stackoverflow.com/users/20862/ignacio-vazquez-abrams">Ignacio Vazquez-Abrams</a>, one should make use of the built in <code>DoesNotExist</code> exception for the model:<...
1
2010-02-06T01:25:30Z
[ "python", "django", "django-models" ]
Convention for checking the existence of a Django model?
2,211,530
<p>What is the accepted way of checking a model's existence in a Django app? </p> <p>I've seen this method used:</p> <pre><code>def profile_exists(user): try: UserProfile.objects.get(user = user) return True except: return False </code></pre> <p>Is ther...
2
2010-02-06T01:06:32Z
2,211,812
<p>As an additional note, you could make a general purpose function out of it with:</p> <pre><code>def object_exists(model, **kwargs): try: model.objects.get(**kwargs) return True except model.DoesNotExist: return False </code></pre> <p>And then simply call:</p> <...
2
2010-02-06T02:52:10Z
[ "python", "django", "django-models" ]
Convention for checking the existence of a Django model?
2,211,530
<p>What is the accepted way of checking a model's existence in a Django app? </p> <p>I've seen this method used:</p> <pre><code>def profile_exists(user): try: UserProfile.objects.get(user = user) return True except: return False </code></pre> <p>Is ther...
2
2010-02-06T01:06:32Z
2,212,772
<p>There's always <code>get_object_or_404</code>, which as its name implies, either returns the object or raises an HttpNotFound error:</p> <pre><code>from django.shortcuts import get_object_or_404 instance = get_object_or_404(SomeModel, filter_args=whatever) </code></pre>
0
2010-02-06T10:15:11Z
[ "python", "django", "django-models" ]
where does defined the Table 'test.sphinx_test_file'?
2,211,579
<p>look the end line:ProgrammingError: (1146, "Table 'test.sphinx_test_file' doesn't exist")</p> <pre><code>Traceback (most recent call last): File "D:\Python25\Lib\site-packages\django\core\servers\basehttp.py", line 280, in run self.finish_response() File "D:\Python25\Lib\site-packages\django\core\servers\...
0
2010-02-06T01:23:35Z
2,212,393
<p>Did you run <code>syncdb</code> after adding the app (I'm guessing the app is named <code>sphinx</code>) to your settings.py?</p>
0
2010-02-06T07:22:41Z
[ "python", "django" ]
selfClosingTags in BeautifulSoup
2,211,589
<p>Using BeautifulSoup to parse my XML</p> <pre><code>import BeautifulSoup soup = BeautifulSoup.BeautifulStoneSoup( """&lt;alan x="y" /&gt;&lt;anne&gt;hello&lt;/anne&gt;""" ) # selfClosingTags=['alan']) print soup.prettify() </code></pre> <p>This will output:</p> <pre><code>&lt;alan x="y"&gt; &lt;anne&gt; hello...
4
2010-02-06T01:24:52Z
2,211,674
<p>I don't have a "why", but this might be of interest to you. If you use <code>BeautifulSoup</code> (no Stone) to parse XML with a self-closing tag, it works. Sort of:</p> <pre><code>&gt;&gt;&gt; soup = BeautifulSoup.BeautifulSoup( """&lt;alan x="y" /&gt;&lt;anne&gt;hello&lt;/anne&gt;""" ) # selfClosingTags=['alan']...
1
2010-02-06T01:57:36Z
[ "python", "xml", "beautifulsoup" ]
selfClosingTags in BeautifulSoup
2,211,589
<p>Using BeautifulSoup to parse my XML</p> <pre><code>import BeautifulSoup soup = BeautifulSoup.BeautifulStoneSoup( """&lt;alan x="y" /&gt;&lt;anne&gt;hello&lt;/anne&gt;""" ) # selfClosingTags=['alan']) print soup.prettify() </code></pre> <p>This will output:</p> <pre><code>&lt;alan x="y"&gt; &lt;anne&gt; hello...
4
2010-02-06T01:24:52Z
2,211,676
<p>You are asking what was in the mind of an author, after having noted that he gives names like Beautiful[Stone]Soup to classes/modules :-)</p> <p>Here are two more examples of the behaviour of BeautifulStoneSoup:</p> <pre><code>&gt;&gt;&gt; soup = BeautifulSoup.BeautifulStoneSoup( """&lt;alan x="y" &gt;&lt;anne...
3
2010-02-06T01:57:54Z
[ "python", "xml", "beautifulsoup" ]
why my django code can not be a 'Standalone Django scripts'
2,211,624
<p>before you look my code , see <a href="http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/" rel="nofollow">http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/</a></p> <p>i want to be a Standalone Django scripts'</p> <p>this is my code :</p> <pre><code>from django.db import models ...
3
2010-02-06T01:37:32Z
2,211,657
<p>The code that you use to set the django settings module has to come before any django-related code, including the django db imports at the top of the script.</p>
3
2010-02-06T01:48:52Z
[ "python", "django" ]
Django model with filterable attributes
2,211,631
<p>I've got two models. One represents a piece of equipment, the other represents a possible attribute the equipment has. Semantically, this might look like:</p> <ul> <li>Equipment: <code>tractor</code>, Attributes: <code>wheels</code>, <code>towing</code></li> <li>Equipment: <code>lawnmower</code>, Attributes: <code>...
1
2010-02-06T01:39:55Z
2,211,691
<p>Your second example is pretty close, but you need to understand how the <a href="http://docs.djangoproject.com/en/dev/topics/db/queries/#lookups-that-span-relationships" rel="nofollow">QuerySet API works across relationships (i.e. joins)</a>.</p> <pre><code>class Attribute(models.Model): name = models.CharField...
1
2010-02-06T02:02:54Z
[ "python", "sql", "mysql", "django", "django-models" ]
SQL LIKE in Django/Python
2,211,695
<p>I'm trying to run a query like this:</p> <pre><code>SELECT * FROM MyTable WHERE FirstName LIKE '%[user inputted value here]%' OR LastName LIKE '%[that same user inputted value]%' AND UserID = some number </code></pre> <p>When I run the query using cursor.execute(), the inputted valu...
1
2010-02-06T02:03:58Z
2,211,700
<p>Use <code>foo__contains=realvaluehere</code> in your queries.</p>
2
2010-02-06T02:06:09Z
[ "python", "sql", "django" ]
SQL LIKE in Django/Python
2,211,695
<p>I'm trying to run a query like this:</p> <pre><code>SELECT * FROM MyTable WHERE FirstName LIKE '%[user inputted value here]%' OR LastName LIKE '%[that same user inputted value]%' AND UserID = some number </code></pre> <p>When I run the query using cursor.execute(), the inputted valu...
1
2010-02-06T02:03:58Z
2,213,997
<p>Hmm, looks like I overestimated the escapy-ness of the API. This works exactly how I want it to</p> <pre><code># add wildcards to query, these are **not** escaped q = "%" + q + "%" cursor = connection.cursor() cursor.execute("SELECT * FROM MyTable WHERE LastName ...
0
2010-02-06T17:44:16Z
[ "python", "sql", "django" ]
why 'list index out of range' in my django code;
2,211,705
<p>IndexError: list index out of range</p> <p>this is my django code :</p> <pre><code>import os os.environ["DJANGO_SETTINGS_MODULE"] = "sphinx_test.settings" #from django.core.management import setup_environ #from sphinx_test import settings #setup_environ(settings) from django.db import models from djangosphinx....
1
2010-02-06T02:07:19Z
2,211,717
<p>You need to set <a href="http://docs.djangoproject.com/en/dev/ref/models/options/#app-label" rel="nofollow"><code>Meta.app_label</code></a> to something usable.</p>
3
2010-02-06T02:12:52Z
[ "python", "django" ]
why 'list index out of range' in my django code;
2,211,705
<p>IndexError: list index out of range</p> <p>this is my django code :</p> <pre><code>import os os.environ["DJANGO_SETTINGS_MODULE"] = "sphinx_test.settings" #from django.core.management import setup_environ #from sphinx_test import settings #setup_environ(settings) from django.db import models from djangosphinx....
1
2010-02-06T02:07:19Z
2,211,721
<p>That's odd, that part of the code is just supposed to determine your app name. See the section <a href="http://code.djangoproject.com/browser/django/trunk/django/db/models/base.py" rel="nofollow">here</a> starting line 45. What's your app name for this?</p> <p>You may be able to avoid the error by setting app_label...
1
2010-02-06T02:15:14Z
[ "python", "django" ]
Are "not in" and "is not" both operators? If so, are they in any way different than "not x in.." and "not x is.."?
2,211,706
<p>I've always preferred these:</p> <pre><code>not 'x' in 'abc' not 'x' is 'a' </code></pre> <p>(assuming, of course that everyone knows <code>in</code> and <code>is</code> out-prioritize <code>not</code> -- I probably should use parentheses) over the more (English) grammatical:</p> <pre><code>'x' not in 'abc' 'x' i...
1
2010-02-06T02:07:23Z
2,211,727
<p>From the python 2.6.4 docs at: <a href="http://docs.python.org/reference/expressions.html" rel="nofollow">http://docs.python.org/reference/expressions.html</a> ></p> <blockquote> <p>The operator not in is defined to have the inverse true value of in.</p> <p>The operators is and is not test for object ide...
4
2010-02-06T02:18:13Z
[ "python" ]
Are "not in" and "is not" both operators? If so, are they in any way different than "not x in.." and "not x is.."?
2,211,706
<p>I've always preferred these:</p> <pre><code>not 'x' in 'abc' not 'x' is 'a' </code></pre> <p>(assuming, of course that everyone knows <code>in</code> and <code>is</code> out-prioritize <code>not</code> -- I probably should use parentheses) over the more (English) grammatical:</p> <pre><code>'x' not in 'abc' 'x' i...
1
2010-02-06T02:07:23Z
2,211,744
<p>The remainder of your question has been answered above, but I'll address the last question: the Zen of Python bit.</p> <p>"There should only be one way to do it" isn't mean't in a mathematical sense. If it were, there'd be no <code>!=</code> operator, since that's just the inversion of <code>==</code>. Similarly, n...
2
2010-02-06T02:23:58Z
[ "python" ]
Are "not in" and "is not" both operators? If so, are they in any way different than "not x in.." and "not x is.."?
2,211,706
<p>I've always preferred these:</p> <pre><code>not 'x' in 'abc' not 'x' is 'a' </code></pre> <p>(assuming, of course that everyone knows <code>in</code> and <code>is</code> out-prioritize <code>not</code> -- I probably should use parentheses) over the more (English) grammatical:</p> <pre><code>'x' not in 'abc' 'x' i...
1
2010-02-06T02:07:23Z
2,211,745
<p>Your documentation reference is nothing to do with syntax. <a href="http://docs.python.org/reference/expressions.html#notin" rel="nofollow">Try this</a>. Both <code>is not</code> and <code>not in</code> are two-word operators.</p>
2
2010-02-06T02:25:21Z
[ "python" ]
Are "not in" and "is not" both operators? If so, are they in any way different than "not x in.." and "not x is.."?
2,211,706
<p>I've always preferred these:</p> <pre><code>not 'x' in 'abc' not 'x' is 'a' </code></pre> <p>(assuming, of course that everyone knows <code>in</code> and <code>is</code> out-prioritize <code>not</code> -- I probably should use parentheses) over the more (English) grammatical:</p> <pre><code>'x' not in 'abc' 'x' i...
1
2010-02-06T02:07:23Z
2,211,752
<p><code>x in a</code> tests whether the element x is in a (which in this case would probably be a list or a string or some such) and returns <code>True</code> if it is.</p> <p><code>x not in a</code> is similar, but returns <code>False</code> if x is in a.</p> <p>On the other hand, <code>x is not a</code> is analogo...
0
2010-02-06T02:28:15Z
[ "python" ]
Are "not in" and "is not" both operators? If so, are they in any way different than "not x in.." and "not x is.."?
2,211,706
<p>I've always preferred these:</p> <pre><code>not 'x' in 'abc' not 'x' is 'a' </code></pre> <p>(assuming, of course that everyone knows <code>in</code> and <code>is</code> out-prioritize <code>not</code> -- I probably should use parentheses) over the more (English) grammatical:</p> <pre><code>'x' not in 'abc' 'x' i...
1
2010-02-06T02:07:23Z
2,211,948
<p>It's easy to check if there's any difference, with the <a href="http://docs.python.org/library/dis.html?highlight=dis#module-dis" rel="nofollow">dis</a> module:</p> <pre><code>&gt;&gt;&gt; dis.dis(compile('not a in b','','exec')) 1 0 LOAD_NAME 0 (a) 3 LOAD_NAME ...
7
2010-02-06T03:49:57Z
[ "python" ]
what is the simplest way to create a table use django db api ,and base on 'Standalone Django scripts'
2,211,816
<p>we can call this 'Standalone Django table'</p> <p>i am not successful now .</p> <p>can you ???</p> <p>thanks</p> <p>if you don't know 'Standalone Django scripts', look this <a href="http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/" rel="nofollow">http://www.b-list.org/weblog/2007/sep/22/stan...
1
2010-02-06T02:53:27Z
2,211,913
<p>The article you linked is a pretty damn good explanation of the simplest way to do it.</p> <p><strong>Edit:</strong> Re-arranged this for clarity.</p> <p>Starting with a fresh app, create a model, sync the database to create the tables, and then use the <code>setup_environ</code> function from within your standalo...
1
2010-02-06T03:37:01Z
[ "python", "django" ]
Method of Multiple Assignment in Python
2,211,822
<p>I'm trying to prepare for a future in computer science, so I started with ECMAScript and I am now trying to learn more about Python. Coming from ECMAScript, seeing multiple assignments such as <code>a, b, c = 1, 2, 3</code> leaves me bewildered for a moment, until I realize that there are multiple assignments going ...
8
2010-02-06T02:55:58Z
2,211,828
<p>It should not have any effect on performance. The parenthesis do not make it a tuple, the comma's do. So (1,2,3) is exactly the same as 1,2,3</p>
11
2010-02-06T02:59:13Z
[ "python", "syntax", "variable-assignment" ]
Method of Multiple Assignment in Python
2,211,822
<p>I'm trying to prepare for a future in computer science, so I started with ECMAScript and I am now trying to learn more about Python. Coming from ECMAScript, seeing multiple assignments such as <code>a, b, c = 1, 2, 3</code> leaves me bewildered for a moment, until I realize that there are multiple assignments going ...
8
2010-02-06T02:55:58Z
2,211,832
<p>Multiple assignment is implemented as a combination of tuple packing and tuple unpacking, to my knowledge, so it should have the same effect.</p>
1
2010-02-06T03:00:08Z
[ "python", "syntax", "variable-assignment" ]
Method of Multiple Assignment in Python
2,211,822
<p>I'm trying to prepare for a future in computer science, so I started with ECMAScript and I am now trying to learn more about Python. Coming from ECMAScript, seeing multiple assignments such as <code>a, b, c = 1, 2, 3</code> leaves me bewildered for a moment, until I realize that there are multiple assignments going ...
8
2010-02-06T02:55:58Z
2,211,836
<p>It also works for lists:</p> <pre><code>a, b, c = [1, 2, 3] </code></pre> <p>works just as well</p>
2
2010-02-06T03:01:16Z
[ "python", "syntax", "variable-assignment" ]
Method of Multiple Assignment in Python
2,211,822
<p>I'm trying to prepare for a future in computer science, so I started with ECMAScript and I am now trying to learn more about Python. Coming from ECMAScript, seeing multiple assignments such as <code>a, b, c = 1, 2, 3</code> leaves me bewildered for a moment, until I realize that there are multiple assignments going ...
8
2010-02-06T02:55:58Z
2,211,925
<p>It's extremely easy to check, with the <a href="http://docs.python.org/library/dis.html?highlight=dis#module-dis"><code>dis</code></a> module:</p> <pre><code>&gt;&gt;&gt; import dis &gt;&gt;&gt; dis.dis(compile('a,b,c=1,2,3','','exec')) 1 0 LOAD_CONST 4 ((1, 2, 3)) 3 UNPACK_S...
13
2010-02-06T03:40:59Z
[ "python", "syntax", "variable-assignment" ]
How to approach Google groups discussions crawler
2,211,887
<p>as an exercise in RSS I would like to be able to search through pretty much all Unix discussions on this group.</p> <p><a href="http://groups.google.com/group/comp.unix.shell/feeds?hl=en" rel="nofollow">comp.unix.shell</a></p> <p>I know enough Python and understand basic RSS, but I am stuck on ... how do I grab al...
1
2010-02-06T03:24:59Z
2,211,912
<p>For N recent, seems like you could pass parameter <code>?num=50</code> or something in the feed url</p> <p>For example, 50 new messages from comp.unix.shell group</p> <p><a href="http://groups.google.com/group/comp.unix.shell/feed/atom_v1_0_msgs.xml?num=50" rel="nofollow">http://groups.google.com/group/comp.unix.s...
3
2010-02-06T03:36:53Z
[ "python", "web-crawler", "google-groups" ]
How to approach Google groups discussions crawler
2,211,887
<p>as an exercise in RSS I would like to be able to search through pretty much all Unix discussions on this group.</p> <p><a href="http://groups.google.com/group/comp.unix.shell/feeds?hl=en" rel="nofollow">comp.unix.shell</a></p> <p>I know enough Python and understand basic RSS, but I am stuck on ... how do I grab al...
1
2010-02-06T03:24:59Z
2,258,615
<p>Crawling google groups violates the <a href="http://groups-beta.google.com/googlegroups/terms_of_service.html" rel="nofollow">Google's Terms of Service</a>, specifically the phrase:</p> <blockquote> <p>use any robot, spider, site search/retrieval application, or other device to retrieve or index any portion of th...
4
2010-02-13T18:40:41Z
[ "python", "web-crawler", "google-groups" ]
How to approach Google groups discussions crawler
2,211,887
<p>as an exercise in RSS I would like to be able to search through pretty much all Unix discussions on this group.</p> <p><a href="http://groups.google.com/group/comp.unix.shell/feeds?hl=en" rel="nofollow">comp.unix.shell</a></p> <p>I know enough Python and understand basic RSS, but I am stuck on ... how do I grab al...
1
2010-02-06T03:24:59Z
2,260,014
<p>Have you thought about yahoos YQL? It's not too bad and can access a lot of APIs. <a href="http://developer.yahoo.com/yql/" rel="nofollow">http://developer.yahoo.com/yql/</a></p> <p>I don't know if groups is suported but u can access rss feeds. Could be helpful.</p>
1
2010-02-14T03:09:36Z
[ "python", "web-crawler", "google-groups" ]
How to approach Google groups discussions crawler
2,211,887
<p>as an exercise in RSS I would like to be able to search through pretty much all Unix discussions on this group.</p> <p><a href="http://groups.google.com/group/comp.unix.shell/feeds?hl=en" rel="nofollow">comp.unix.shell</a></p> <p>I know enough Python and understand basic RSS, but I am stuck on ... how do I grab al...
1
2010-02-06T03:24:59Z
2,260,493
<p>As Randal mentioned, this violates Google's ToS -- however, as a hypothetical or for use on another site without these restrictions you could pretty easily rig something up with <a href="http://docs.python.org/library/urllib.html" rel="nofollow">urllib</a> and <a href="http://www.crummy.com/software/BeautifulSoup/" ...
1
2010-02-14T08:03:37Z
[ "python", "web-crawler", "google-groups" ]
Python memory usage? loading large dictionaries in memory
2,211,965
<p>hey all, I have a file on disk that's only 168MB. It's just a comma separated list of word,id the word can be 1-5 words long. There's 6.5 million lines. I created a dictionary in python to load this up into memory so I can search incoming text against that list of words. When python loads it up into memory it shows ...
22
2010-02-06T03:56:56Z
2,212,001
<p>convert your data into a dbm (import anydbm, or use berkerley db by import bsddb ...), and then use dbm API to access it.</p> <p>the reason to explode is that python has extra meta information for any objects, and the dict needs to construct a hash table (which would require more memory). you just created so many o...
8
2010-02-06T04:06:47Z
[ "python", "memory" ]
Python memory usage? loading large dictionaries in memory
2,211,965
<p>hey all, I have a file on disk that's only 168MB. It's just a comma separated list of word,id the word can be 1-5 words long. There's 6.5 million lines. I created a dictionary in python to load this up into memory so I can search incoming text against that list of words. When python loads it up into memory it shows ...
22
2010-02-06T03:56:56Z
2,212,005
<p>Take a look (Python 2.6, 32-bit version)...:</p> <pre><code>&gt;&gt;&gt; sys.getsizeof('word,1') 30 &gt;&gt;&gt; sys.getsizeof(('word', '1')) 36 &gt;&gt;&gt; sys.getsizeof(dict(word='1')) 140 </code></pre> <p>The string (taking 6 bytes on disk, clearly) gets an overhead of 24 bytes (no matter how long it is, add 2...
16
2010-02-06T04:07:56Z
[ "python", "memory" ]
Python memory usage? loading large dictionaries in memory
2,211,965
<p>hey all, I have a file on disk that's only 168MB. It's just a comma separated list of word,id the word can be 1-5 words long. There's 6.5 million lines. I created a dictionary in python to load this up into memory so I can search incoming text against that list of words. When python loads it up into memory it shows ...
22
2010-02-06T03:56:56Z
2,212,006
<p>Lots of ideas. However, if you want practical help, edit your question to show ALL of your code. Also tell us what is the "it" that shows memory used, what it shows when you load a file with zero entries, and what platform you are on, and what version of Python.</p> <p>You say that "the word can be 1-5 words long"....
24
2010-02-06T04:09:05Z
[ "python", "memory" ]
Python memory usage? loading large dictionaries in memory
2,211,965
<p>hey all, I have a file on disk that's only 168MB. It's just a comma separated list of word,id the word can be 1-5 words long. There's 6.5 million lines. I created a dictionary in python to load this up into memory so I can search incoming text against that list of words. When python loads it up into memory it shows ...
22
2010-02-06T03:56:56Z
39,766,853
<p>I have the same problem though I'm later. The others has answered this question well. And I offer an <del>easy to use</del>(maybe not so easy :-) ) and rather efficient alternative, that's <code>pandas.DataFrame</code>. It performs well in memory usage when saving large data.</p>
0
2016-09-29T09:43:00Z
[ "python", "memory" ]
Building an Inference Engine in Python
2,211,967
<p>I am seeking direction and attempting to <em>label</em> this problem:</p> <p>I am attempting to build a simple inference engine (is there a better name?) in Python which will take a string and -</p> <p>1 - create a list of tokens by simply creating a list of white space separated values</p> <p>2 - categorise thes...
7
2010-02-06T03:57:19Z
2,212,121
<p>I'm very surprised that step #3 is the one giving you trouble...</p> <p>Assuming you can label/categorize properly each token (and that prior to categorization you can find the proper tokens, as there may be many ambiguous cases...), <strong>the "Step #3" problem seems one that could easily be tackled with a contex...
6
2010-02-06T04:53:30Z
[ "python", "parsing", "rule-engine", "expert-system" ]
Building an Inference Engine in Python
2,211,967
<p>I am seeking direction and attempting to <em>label</em> this problem:</p> <p>I am attempting to build a simple inference engine (is there a better name?) in Python which will take a string and -</p> <p>1 - create a list of tokens by simply creating a list of white space separated values</p> <p>2 - categorise thes...
7
2010-02-06T03:57:19Z
7,619,477
<p>It looks like you search for "grammar inference" (grammar induction) library.</p>
2
2011-10-01T09:49:34Z
[ "python", "parsing", "rule-engine", "expert-system" ]
How to implement an efficient infinite generator of prime numbers in Python?
2,211,990
<p>This is not a homework, I am just curious.</p> <p>INFINITE is the key word here.</p> <p>I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell.</p> <p>So, the answer cannot be as naive as "Just do a Sieve".</p> <p>First of all, you do not know how many consecutive primes wil...
38
2010-02-06T04:04:50Z
2,212,007
<p>This isn't originally my code, however, it's worth posting. The original can be found here: <a href="http://code.activestate.com/recipes/117119/" rel="nofollow">http://code.activestate.com/recipes/117119/</a></p> <pre><code>def gen_primes(): D = {} q = 2 # first integer to test for primality. while True: ...
4
2010-02-06T04:09:18Z
[ "python", "generator", "primes" ]
How to implement an efficient infinite generator of prime numbers in Python?
2,211,990
<p>This is not a homework, I am just curious.</p> <p>INFINITE is the key word here.</p> <p>I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell.</p> <p>So, the answer cannot be as naive as "Just do a Sieve".</p> <p>First of all, you do not know how many consecutive primes wil...
38
2010-02-06T04:04:50Z
2,212,046
<p>Here's a generator that's a little truer to how it's done in Haskell: filtering against composites of known primes, then adding the remaining primes to the list.</p> <pre><code>def gen_primes(): primes = [] i = 2 while True: prime = True for p in primes: if not (i % p): ...
1
2010-02-06T04:22:27Z
[ "python", "generator", "primes" ]
How to implement an efficient infinite generator of prime numbers in Python?
2,211,990
<p>This is not a homework, I am just curious.</p> <p>INFINITE is the key word here.</p> <p>I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell.</p> <p>So, the answer cannot be as naive as "Just do a Sieve".</p> <p>First of all, you do not know how many consecutive primes wil...
38
2010-02-06T04:04:50Z
2,212,090
<p>I still like what I wrote up <a href="http://macdevcenter.com/pub/a/python/excerpt/pythonckbk_chap1/index1.html?page=2">here</a> (a Cookbook recipe with many other authors) -- it shows how a Sieve of Eratosthenes has no intrinsic limits, and the comments and discussion, I believe, make it quite clear. This was rece...
20
2010-02-06T04:41:42Z
[ "python", "generator", "primes" ]
How to implement an efficient infinite generator of prime numbers in Python?
2,211,990
<p>This is not a homework, I am just curious.</p> <p>INFINITE is the key word here.</p> <p>I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell.</p> <p>So, the answer cannot be as naive as "Just do a Sieve".</p> <p>First of all, you do not know how many consecutive primes wil...
38
2010-02-06T04:04:50Z
2,212,842
<p>Do a <em>segmented</em> sieve, where the size of a segment is determined by available memory or the maximal size of a bitset.</p> <p>For each segment represent the numbers in some interval [n; n + segment_size) as a bit set and sieve with all prime numbers below the square root of the upper bound.</p> <p>Using a b...
4
2010-02-06T10:47:48Z
[ "python", "generator", "primes" ]
How to implement an efficient infinite generator of prime numbers in Python?
2,211,990
<p>This is not a homework, I am just curious.</p> <p>INFINITE is the key word here.</p> <p>I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell.</p> <p>So, the answer cannot be as naive as "Just do a Sieve".</p> <p>First of all, you do not know how many consecutive primes wil...
38
2010-02-06T04:04:50Z
2,213,107
<p>I wrote an article about an infinite primes generator some times ago: </p> <p><a href="http://stacktrace.it/2008/01/progetto-eulero-problema-3/" rel="nofollow">http://stacktrace.it/2008/01/progetto-eulero-problema-3/</a></p> <p>It's in Italian but you may have a pesky translation using Google: <a href="http://tiny...
1
2010-02-06T12:43:18Z
[ "python", "generator", "primes" ]
How to implement an efficient infinite generator of prime numbers in Python?
2,211,990
<p>This is not a homework, I am just curious.</p> <p>INFINITE is the key word here.</p> <p>I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell.</p> <p>So, the answer cannot be as naive as "Just do a Sieve".</p> <p>First of all, you do not know how many consecutive primes wil...
38
2010-02-06T04:04:50Z
3,796,442
<h1>“If I have seen further…”</h1> <p>The <code>erat2</code> function from the cookbook can be further sped up (by about 20-25%):</p> <h2>erat2a</h2> <pre><code>import itertools as it def erat2a( ): D = { } yield 2 for q in it.islice(it.count(3), 0, None, 2): p = D.pop(q, None) if ...
57
2010-09-26T03:01:48Z
[ "python", "generator", "primes" ]
How to implement an efficient infinite generator of prime numbers in Python?
2,211,990
<p>This is not a homework, I am just curious.</p> <p>INFINITE is the key word here.</p> <p>I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell.</p> <p>So, the answer cannot be as naive as "Just do a Sieve".</p> <p>First of all, you do not know how many consecutive primes wil...
38
2010-02-06T04:04:50Z
8,386,234
<p>And another answer, more memory-efficient than my <code>erat3</code> answer here:</p> <pre><code>import heapq def heapprimegen(): hp= [] yield 2 yield 3 cn= 3 nn, inc= 3, 6 while 1: while cn &lt; nn: yield cn heapq.heappush(hp, (3*cn, 2*cn)) cn+= ...
2
2011-12-05T13:44:11Z
[ "python", "generator", "primes" ]
How to implement an efficient infinite generator of prime numbers in Python?
2,211,990
<p>This is not a homework, I am just curious.</p> <p>INFINITE is the key word here.</p> <p>I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell.</p> <p>So, the answer cannot be as naive as "Just do a Sieve".</p> <p>First of all, you do not know how many consecutive primes wil...
38
2010-02-06T04:04:50Z
9,151,909
<p>Another way to do it:</p> <pre><code>import itertools def primeseq(): prime = [2] num = 0 yield 2 for i in itertools.count(3, 2): is_prime = True for num in prime: if i % num == 0: is_prime = False break elif num ** 2 &gt; i: ...
1
2012-02-05T18:42:03Z
[ "python", "generator", "primes" ]
How to implement an efficient infinite generator of prime numbers in Python?
2,211,990
<p>This is not a homework, I am just curious.</p> <p>INFINITE is the key word here.</p> <p>I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell.</p> <p>So, the answer cannot be as naive as "Just do a Sieve".</p> <p>First of all, you do not know how many consecutive primes wil...
38
2010-02-06T04:04:50Z
10,733,621
<p>Since the OP asks for an <em>efficient</em> implementation, here's a significant improvement to the <a href="http://code.activestate.com/recipes/117119-sieve-of-eratosthenes/">active state 2002 code</a> by David Eppstein/Alex Martelli (seen here in <a href="http://stackoverflow.com/a/2212090/849891">his answer</a>):...
40
2012-05-24T08:16:32Z
[ "python", "generator", "primes" ]
How to implement an efficient infinite generator of prime numbers in Python?
2,211,990
<p>This is not a homework, I am just curious.</p> <p>INFINITE is the key word here.</p> <p>I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell.</p> <p>So, the answer cannot be as naive as "Just do a Sieve".</p> <p>First of all, you do not know how many consecutive primes wil...
38
2010-02-06T04:04:50Z
11,757,952
<p>This is similar but about 5% faster then erat2a.</p> <pre><code>import itertools as it def erat2b( ): D = { } yield 2 for q in it.islice(it.count(3), 0, None, 2): p = D.pop(q, None) if p is None: D[q*q] = q yield q else: # Only this part is re...
2
2012-08-01T11:08:45Z
[ "python", "generator", "primes" ]
How to implement an efficient infinite generator of prime numbers in Python?
2,211,990
<p>This is not a homework, I am just curious.</p> <p>INFINITE is the key word here.</p> <p>I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell.</p> <p>So, the answer cannot be as naive as "Just do a Sieve".</p> <p>First of all, you do not know how many consecutive primes wil...
38
2010-02-06T04:04:50Z
11,759,692
<p>Here is a simple but not terribly slow one using a heap instead of a dict:</p> <pre><code>import heapq def heap_prime_gen_squares(): yield 2 yield 3 h = [(9, 6)] n = 5 while True: a, b = h[0] while n &lt; a: yield n heapq.heappush(h, (n * n, n &lt;&l...
1
2012-08-01T12:52:24Z
[ "python", "generator", "primes" ]
How to implement an efficient infinite generator of prime numbers in Python?
2,211,990
<p>This is not a homework, I am just curious.</p> <p>INFINITE is the key word here.</p> <p>I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell.</p> <p>So, the answer cannot be as naive as "Just do a Sieve".</p> <p>First of all, you do not know how many consecutive primes wil...
38
2010-02-06T04:04:50Z
11,759,904
<p>Here is a complicated heap-based implementation, which is not much faster than other heap-based implementations (see the speed comparison in another answer of mine), but it uses much less memory.</p> <p>This implementation uses two heaps (tu and wv), which contain the same number elements. Each element is an int pa...
2
2012-08-01T13:03:40Z
[ "python", "generator", "primes" ]
How to implement an efficient infinite generator of prime numbers in Python?
2,211,990
<p>This is not a homework, I am just curious.</p> <p>INFINITE is the key word here.</p> <p>I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell.</p> <p>So, the answer cannot be as naive as "Just do a Sieve".</p> <p>First of all, you do not know how many consecutive primes wil...
38
2010-02-06T04:04:50Z
19,391,111
<p>For posterity, here's a rewrite of Will Ness's beautiful algorithm for Python 3. Some changes are needed (iterators no longer have <code>.next()</code> methods, but there's a new <code>next()</code> builtin function). Other changes are for fun (using the new <code>yield from &lt;iterable&gt;</code> replaces four <...
17
2013-10-15T21:08:31Z
[ "python", "generator", "primes" ]
How to implement an efficient infinite generator of prime numbers in Python?
2,211,990
<p>This is not a homework, I am just curious.</p> <p>INFINITE is the key word here.</p> <p>I wish to use it as for p in primes(). I believe that this is a built-in function in Haskell.</p> <p>So, the answer cannot be as naive as "Just do a Sieve".</p> <p>First of all, you do not know how many consecutive primes wil...
38
2010-02-06T04:04:50Z
33,555,348
<p>Here's a pretty fast infinite generator, written in Python2 but easily adjusted to Python3. To use it to add the primes up to 10**9, use the following:</p> <pre><code>from itertools import takewhile from functools import partial from operator import gt print (sum(takewhile(partial(gt, 10**9), prime_gen_inf()))) </...
0
2015-11-05T21:42:36Z
[ "python", "generator", "primes" ]
optional arguments when calling a function without modifying function definition
2,212,185
<p>I want to know how to call a function, passing a parameter that it <strong>might not</strong> be expecting.</p> <p>I faced this problem a few days ago, and found a way around it. But today, I decided I'd see if what I wanted to do was possible. Unfortunately, I don't remember the context which I used it in. So here...
0
2010-02-06T05:31:39Z
2,212,232
<p>Inspecting the function is the only way to explicitly differentiate between functions with different numbers of arguments without altering or decorating the originals. The only change I would do to your wrapper is to generalize it for any number of arguments:</p> <pre><code>def padArgsWithTrue(func, *args): pas...
1
2010-02-06T05:56:56Z
[ "python", "optional-parameters", "function-calls" ]
optional arguments when calling a function without modifying function definition
2,212,185
<p>I want to know how to call a function, passing a parameter that it <strong>might not</strong> be expecting.</p> <p>I faced this problem a few days ago, and found a way around it. But today, I decided I'd see if what I wanted to do was possible. Unfortunately, I don't remember the context which I used it in. So here...
0
2010-02-06T05:31:39Z
2,212,263
<p>If I understand you, you want to be able to call both func1 and func2 using test.</p> <pre><code>def test(func, arg1, arg2): try: return func(arg1, arg2, flag1=True, flag2=False) except TypeError: return func(arg1, arg2) def func1(a, b, flag1, flag2): ret = a if flag1: ret ...
0
2010-02-06T06:19:48Z
[ "python", "optional-parameters", "function-calls" ]
Python virtualbox API
2,212,286
<p>Please give some suggestions on how to control virtualbox from commandline from a python program using python virtualbox API. If you know any useful website, please give its address </p>
2
2010-02-06T06:30:10Z
2,212,317
<p>Looking into some <a href="http://enomalism.com/api/pyvb/pyvb.vb-pysrc.html" rel="nofollow">PyVB Source</a> and <a href="http://enomalism.com/api/pyvb/" rel="nofollow">API doc</a> would be good idea.</p>
1
2010-02-06T06:44:05Z
[ "python", "virtualbox" ]
Python virtualbox API
2,212,286
<p>Please give some suggestions on how to control virtualbox from commandline from a python program using python virtualbox API. If you know any useful website, please give its address </p>
2
2010-02-06T06:30:10Z
2,212,336
<p>This might sound really snide but: <a href="http://tinyurl.com/yasjlvr" rel="nofollow">Let me Google that for you</a></p> <p>... though I have to admit that I had to try the <a href="http://enomalism.com/api/pyvb/" rel="nofollow">fourth link from my results</a> to find something that looked like it might actually b...
1
2010-02-06T06:51:10Z
[ "python", "virtualbox" ]
Counting the Number of keywords in a dictionary in python
2,212,433
<p>I have a list of words in a dictionary with the value = the repetition of the keyword but I only want a list of distinct words so i wanted to count the number of keywords. Is there a to count the number of keywords or is there another way I should look for distinct words? </p>
67
2010-02-06T07:37:39Z
2,212,437
<p>The number of distinct words (i.e. count of entries in the dictionary) can be found using the <code>len()</code> function.</p> <pre><code>&gt; a = {'foo':42, 'bar':69} &gt; len(a) 2 </code></pre> <p>To get all the distinct words (i.e. the keys), use the <code>.keys()</code> method.</p> <pre><code>&gt; list(a.keys...
10
2010-02-06T07:40:01Z
[ "python", "dictionary", "count", "keyword" ]
Counting the Number of keywords in a dictionary in python
2,212,433
<p>I have a list of words in a dictionary with the value = the repetition of the keyword but I only want a list of distinct words so i wanted to count the number of keywords. Is there a to count the number of keywords or is there another way I should look for distinct words? </p>
67
2010-02-06T07:37:39Z
2,212,442
<pre><code>len(yourdict.keys()) </code></pre> <p>or just</p> <pre><code>len(yourdict) </code></pre> <p>If you like to count unique words in the file, you could just use <a href="http://docs.python.org/library/sets.html#module-sets"><code>set</code></a> and do like</p> <pre><code>len(set(open(yourdictfile).read().sp...
134
2010-02-06T07:41:38Z
[ "python", "dictionary", "count", "keyword" ]
Python recursive folder read
2,212,643
<p>I have a C++/Obj-C background and I am just discovering Python (been writing it for about an hour). I am writing a script to recursively read the contents of text files in a folder structure.</p> <p>The problem I have is the code I have written will only work for one folder deep. I can see why in the code (see <cod...
80
2010-02-06T09:24:39Z
2,212,664
<p>I think the problem is that you're not processing the output of <code>os.walk</code> correctly.</p> <p>Firstly, change:</p> <pre><code>filePath = rootdir + '/' + file </code></pre> <p>to:</p> <pre><code>filePath = root + '/' + file </code></pre> <p><code>rootdir</code> is your fixed starting directory; <code>ro...
0
2010-02-06T09:34:45Z
[ "python", "scripting", "file-io" ]
Python recursive folder read
2,212,643
<p>I have a C++/Obj-C background and I am just discovering Python (been writing it for about an hour). I am writing a script to recursively read the contents of text files in a folder structure.</p> <p>The problem I have is the code I have written will only work for one folder deep. I can see why in the code (see <cod...
80
2010-02-06T09:24:39Z
2,212,672
<p>use <code>os.path.join()</code> to construct your paths - It's neater:</p> <pre><code>import os import sys rootdir = sys.argv[1] for root, subFolders, files in os.walk(rootdir): for folder in subFolders: outfileName = os.path.join(root,folder,"py-outfile.txt") folderOut = open( outfileName, 'w' ...
1
2010-02-06T09:39:08Z
[ "python", "scripting", "file-io" ]
Python recursive folder read
2,212,643
<p>I have a C++/Obj-C background and I am just discovering Python (been writing it for about an hour). I am writing a script to recursively read the contents of text files in a folder structure.</p> <p>The problem I have is the code I have written will only work for one folder deep. I can see why in the code (see <cod...
80
2010-02-06T09:24:39Z
2,212,698
<p>Make sure you understand the three return values of <code>os.walk</code>:</p> <pre><code>for root, subdirs, files in os.walk(rootdir): </code></pre> <p>has the following meaning:</p> <ul> <li><code>root</code>: Current path which is "walked through"</li> <li><code>subdirs</code>: Files in <code>root</code> of typ...
164
2010-02-06T09:48:17Z
[ "python", "scripting", "file-io" ]
Python recursive folder read
2,212,643
<p>I have a C++/Obj-C background and I am just discovering Python (been writing it for about an hour). I am writing a script to recursively read the contents of text files in a folder structure.</p> <p>The problem I have is the code I have written will only work for one folder deep. I can see why in the code (see <cod...
80
2010-02-06T09:24:39Z
2,212,728
<p>Agree with Dave Webb, <code>os.walk</code> will yield an item for each directory in the tree. Fact is, you just don't have to care about <code>subFolders</code>.</p> <p>Code like this should work:</p> <pre><code>import os import sys rootdir = sys.argv[1] for folder, subs, files in os.walk(rootdir): with open...
13
2010-02-06T09:59:58Z
[ "python", "scripting", "file-io" ]