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
Threading TCP Server as proxy between connected user and unix socket
833,962
<p>I'm writing web application where I need to push data from server to the connected clients. This data can be send from any other script from web application. For example one user make some changes on the server and other users should be notified about that. </p> <p>So my idea is to use unix socket (path to socket based on user #ID) to send data for corresponding user (web app scripts will connect to this socket and write data). The second part is ThreadingTCPServer which will accept user connections and push data from unix socket to user over TCP socket connection.</p> <p>Here is the workflow:</p> <ol> <li>Used connect to the TCP Server</li> <li>Django script open unixsocket and write data to it.</li> <li>TCP Server read data from unix socket and send it to open connection with user.</li> </ol> <p>I hope you understand my idea :)</p> <p>So, I have 2 questions:</p> <p>1.What do you think about my idea in general? Is it good or bad solution? Any recommendations are welcome.</p> <p>2.Here is my code.</p> <pre><code>import SocketServer import socket import netstring import sys, os, os.path import string import time class MyRequestHandler(SocketServer.BaseRequestHandler): def handle(self): try: print "Connected:", self.client_address user = self.request.recv(1024).strip().split(":")[1] user = int(user) self.request.send('Welcome #%s' % user) self.usocket_path = '/tmp/u%s.sock' % user if os.path.exists(self.usocket_path): os.remove(self.usocket_path) self.usocket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) self.usocket.bind(self.usocket_path) self.usocket.listen(1) while 1: usocket_conn, addr = self.usocket.accept() while 1: data = usocket_conn.recv(1024) if not data: break self.request.send(data) break usocket_conn.close() time.sleep(0.1) except KeyboardInterrupt: self.request.send('close') self.request.close() myServer = SocketServer.ThreadingTCPServer(('', 8081), MyRequestHandler) myServer.serve_forever() </code></pre> <p>and I got an exception</p> <pre><code> File "server1.py", line 23, in handle self.usocket.listen(1) File "&lt;string&gt;", line 1, in listen error: (102, 'Operation not supported on socket') </code></pre>
0
2009-05-07T10:46:21Z
1,005,054
<p>You should use Twisted, or, more specifically, <a href="http://orbited.org/" rel="nofollow">Orbited</a>, to push data to your clients. The sample code you posted has a number of potential problems, and it would be a lot harder to figure out what they all are than for you to just use a pre-built piece of code to do what you need.</p>
0
2009-06-17T03:56:57Z
[ "python", "multithreading", "sockets", "tcp" ]
How to install python-igraph on Ubuntu 8.04 LTS 64-Bit?
834,076
<p>Apparently <code>libigraph</code> and <code>python-igraph</code> are the only packages on earth that can't be installed via <code>apt-get</code> or <code>easy_install</code> under Ubuntu 8.04 LTS 64-bit.</p> <p>Installing both from source from source on seems to go smoothly...until I try to use them.</p> <p>When I run python I get:</p> <pre><code>&gt;&gt;&gt; import igraph Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "igraph/__init__.py", line 30, in &lt;module&gt; from igraph.core import * ImportError: No module named core </code></pre> <p>or (if I use the easy_install version of python-igraph) </p> <pre><code>&gt;&gt;&gt; import igraph Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "build/bdist.linux-x86_64/egg/igraph/__init__.py", line 30, in &lt;module&gt; File "build/bdist.linux-x86_64/egg/igraph/core.py", line 7, in &lt;module&gt; File "build/bdist.linux-x86_64/egg/igraph/core.py", line 6, in __bootstrap__ ImportError: libigraph.so.0: cannot open shared object file: No such file or directory </code></pre> <p>I grabbed the source from here</p> <p>igraph 0.5.2 = <a href="http://igraph.sourceforge.net/download.html" rel="nofollow">http://igraph.sourceforge.net/download.html</a></p> <p>python-igraph 0.5.2 = <a href="http://pypi.python.org/pypi/python-igraph/0.5.2" rel="nofollow">http://pypi.python.org/pypi/python-igraph/0.5.2</a></p> <p>Can anybody point me in the right direction?</p>
4
2009-05-07T11:13:10Z
834,098
<p>Where is libigraph.so.0 ? It doesn't seem to be in a location that python looks for such as /usr/lib , /usr/local/lib etc.</p>
0
2009-05-07T11:18:36Z
[ "python", "64bit", "ubuntu-8.04", "igraph" ]
How to install python-igraph on Ubuntu 8.04 LTS 64-Bit?
834,076
<p>Apparently <code>libigraph</code> and <code>python-igraph</code> are the only packages on earth that can't be installed via <code>apt-get</code> or <code>easy_install</code> under Ubuntu 8.04 LTS 64-bit.</p> <p>Installing both from source from source on seems to go smoothly...until I try to use them.</p> <p>When I run python I get:</p> <pre><code>&gt;&gt;&gt; import igraph Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "igraph/__init__.py", line 30, in &lt;module&gt; from igraph.core import * ImportError: No module named core </code></pre> <p>or (if I use the easy_install version of python-igraph) </p> <pre><code>&gt;&gt;&gt; import igraph Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "build/bdist.linux-x86_64/egg/igraph/__init__.py", line 30, in &lt;module&gt; File "build/bdist.linux-x86_64/egg/igraph/core.py", line 7, in &lt;module&gt; File "build/bdist.linux-x86_64/egg/igraph/core.py", line 6, in __bootstrap__ ImportError: libigraph.so.0: cannot open shared object file: No such file or directory </code></pre> <p>I grabbed the source from here</p> <p>igraph 0.5.2 = <a href="http://igraph.sourceforge.net/download.html" rel="nofollow">http://igraph.sourceforge.net/download.html</a></p> <p>python-igraph 0.5.2 = <a href="http://pypi.python.org/pypi/python-igraph/0.5.2" rel="nofollow">http://pypi.python.org/pypi/python-igraph/0.5.2</a></p> <p>Can anybody point me in the right direction?</p>
4
2009-05-07T11:13:10Z
836,948
<p>How did you compile? Did you do a make install (if there was any).</p> <p>As for the 'library not found' error in the easy_install version, i'd try the following:</p> <ol> <li>'<code>sudo updatedb</code>' (to update the locate database)</li> <li>'<code>locate libigraph.so.0</code>' (to find where this file is on your system. If you did a make install it could have went to /usr/local/lib ... or is it in the python lib dir?)</li> <li>Find out if the directory where this file is in is missing from your current LD_LIBRARY_PATH ('<code>echo $LD_LIBRARY_PATH</code>').</li> <li>If this directory is not in here, add it try '<code>export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/yourdirhere</code>' (make it permanent by adding it to /etc/ld.so.conf) / '<code>ldconfig -n /yourdirhere</code>'</li> </ol>
11
2009-05-07T20:48:20Z
[ "python", "64bit", "ubuntu-8.04", "igraph" ]
How to install python-igraph on Ubuntu 8.04 LTS 64-Bit?
834,076
<p>Apparently <code>libigraph</code> and <code>python-igraph</code> are the only packages on earth that can't be installed via <code>apt-get</code> or <code>easy_install</code> under Ubuntu 8.04 LTS 64-bit.</p> <p>Installing both from source from source on seems to go smoothly...until I try to use them.</p> <p>When I run python I get:</p> <pre><code>&gt;&gt;&gt; import igraph Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "igraph/__init__.py", line 30, in &lt;module&gt; from igraph.core import * ImportError: No module named core </code></pre> <p>or (if I use the easy_install version of python-igraph) </p> <pre><code>&gt;&gt;&gt; import igraph Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "build/bdist.linux-x86_64/egg/igraph/__init__.py", line 30, in &lt;module&gt; File "build/bdist.linux-x86_64/egg/igraph/core.py", line 7, in &lt;module&gt; File "build/bdist.linux-x86_64/egg/igraph/core.py", line 6, in __bootstrap__ ImportError: libigraph.so.0: cannot open shared object file: No such file or directory </code></pre> <p>I grabbed the source from here</p> <p>igraph 0.5.2 = <a href="http://igraph.sourceforge.net/download.html" rel="nofollow">http://igraph.sourceforge.net/download.html</a></p> <p>python-igraph 0.5.2 = <a href="http://pypi.python.org/pypi/python-igraph/0.5.2" rel="nofollow">http://pypi.python.org/pypi/python-igraph/0.5.2</a></p> <p>Can anybody point me in the right direction?</p>
4
2009-05-07T11:13:10Z
1,648,339
<p>I followed the steps in <a href="http://socialsynergyweb.org/network/blog/install-python-igraph-ubuntu-904-64-bit" rel="nofollow">http://socialsynergyweb.org/network/blog/install-python-igraph-ubuntu-904-64-bit</a>. Also to run the actual igraph , i used the script python-igraph-0.5.2/scripts/igraph. Now i am able to use the igraph . If I dont use the scripts/igraph script i get the same error you are getting.</p>
0
2009-10-30T06:38:41Z
[ "python", "64bit", "ubuntu-8.04", "igraph" ]
How to install python-igraph on Ubuntu 8.04 LTS 64-Bit?
834,076
<p>Apparently <code>libigraph</code> and <code>python-igraph</code> are the only packages on earth that can't be installed via <code>apt-get</code> or <code>easy_install</code> under Ubuntu 8.04 LTS 64-bit.</p> <p>Installing both from source from source on seems to go smoothly...until I try to use them.</p> <p>When I run python I get:</p> <pre><code>&gt;&gt;&gt; import igraph Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "igraph/__init__.py", line 30, in &lt;module&gt; from igraph.core import * ImportError: No module named core </code></pre> <p>or (if I use the easy_install version of python-igraph) </p> <pre><code>&gt;&gt;&gt; import igraph Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "build/bdist.linux-x86_64/egg/igraph/__init__.py", line 30, in &lt;module&gt; File "build/bdist.linux-x86_64/egg/igraph/core.py", line 7, in &lt;module&gt; File "build/bdist.linux-x86_64/egg/igraph/core.py", line 6, in __bootstrap__ ImportError: libigraph.so.0: cannot open shared object file: No such file or directory </code></pre> <p>I grabbed the source from here</p> <p>igraph 0.5.2 = <a href="http://igraph.sourceforge.net/download.html" rel="nofollow">http://igraph.sourceforge.net/download.html</a></p> <p>python-igraph 0.5.2 = <a href="http://pypi.python.org/pypi/python-igraph/0.5.2" rel="nofollow">http://pypi.python.org/pypi/python-igraph/0.5.2</a></p> <p>Can anybody point me in the right direction?</p>
4
2009-05-07T11:13:10Z
1,762,839
<p>Note that there are official Ubuntu packages for igraph available from Launchpad as of 8 Nov 2009. See the corresponding <a href="https://launchpad.net/~igraph/+archive/ppa" rel="nofollow">page</a> on Launchpad for instructions. Unlike the earlier Debian package repository, this should work on both 32-bit and 64-bit architectures.</p>
2
2009-11-19T12:05:35Z
[ "python", "64bit", "ubuntu-8.04", "igraph" ]
Python ASCII Graph Drawing
834,395
<p>I'm looking for a library to draw ASCII graphs (for use in a console) with Python. The graph is quite simple: it's only a flow chart for pipelines.</p> <p>I saw NetworkX and igraph, but didn't see a way to output to ascii.</p> <p>Do you have experience in this?</p> <p>Thanks a lot!</p> <p>Patrick</p> <p>EDIT 1: I actually found a library doing what I need, but it's in perl <a href="http://bloodgate.com/perl/graph/manual/output.html">Graph::Easy</a> . I could call the code from python but I don't like the idea too much... still looking for a python solution :)</p>
17
2009-05-07T12:33:34Z
834,433
<p>It's not directly Python based, but you should take a look into the artist-mode of emacs</p> <ul> <li><a href="http://www.youtube.com/watch?v=LDbi56U5qRw" rel="nofollow">artist-mode video</a></li> <li><a href="http://www.lysator.liu.se/~tab/artist/" rel="nofollow">artist-mode site</a></li> </ul> <p>You can control emacs from python with <a href="http://www.lysator.liu.se/~tab/artist/" rel="nofollow">pymacs</a>, or you can take a look at the lisp code and draw some inspiration.</p>
1
2009-05-07T12:41:18Z
[ "python", "graph", "ascii" ]
Python ASCII Graph Drawing
834,395
<p>I'm looking for a library to draw ASCII graphs (for use in a console) with Python. The graph is quite simple: it's only a flow chart for pipelines.</p> <p>I saw NetworkX and igraph, but didn't see a way to output to ascii.</p> <p>Do you have experience in this?</p> <p>Thanks a lot!</p> <p>Patrick</p> <p>EDIT 1: I actually found a library doing what I need, but it's in perl <a href="http://bloodgate.com/perl/graph/manual/output.html">Graph::Easy</a> . I could call the code from python but I don't like the idea too much... still looking for a python solution :)</p>
17
2009-05-07T12:33:34Z
834,578
<p>When you say 'simple network graph in ascii', do you mean something like this?</p> <pre><code>.===. .===. .===. .===. | a |---| b |---| c |---| d | '===' '===' '---' '===' </code></pre> <p>I suspect there are probably better ways to display whatever information it is that you have than to try and draw it on the console. If it's just a pipeline, why not just print out:</p> <pre><code>a-b-c-d </code></pre> <p>If you're sure this is the route, one thing you could try would be to generate a decent graph using <a href="http://matplotlib.sourceforge.net" rel="nofollow">Matplotlib</a> and then post the contents to one of <a href="https://www.ohloh.net/tags/ascii/python" rel="nofollow">the many image-to-ascii converters</a> you can find on the web.</p>
0
2009-05-07T13:12:33Z
[ "python", "graph", "ascii" ]
Python ASCII Graph Drawing
834,395
<p>I'm looking for a library to draw ASCII graphs (for use in a console) with Python. The graph is quite simple: it's only a flow chart for pipelines.</p> <p>I saw NetworkX and igraph, but didn't see a way to output to ascii.</p> <p>Do you have experience in this?</p> <p>Thanks a lot!</p> <p>Patrick</p> <p>EDIT 1: I actually found a library doing what I need, but it's in perl <a href="http://bloodgate.com/perl/graph/manual/output.html">Graph::Easy</a> . I could call the code from python but I don't like the idea too much... still looking for a python solution :)</p>
17
2009-05-07T12:33:34Z
834,736
<p>To draw networks, <a href="http://dkbza.org/pydot.html" rel="nofollow">pydot</a> might be a more convenient solution than matplotlib. It is based on graphviz (<a href="http://www.graphviz.org/Gallery.php" rel="nofollow">gallery</a>).</p>
0
2009-05-07T13:47:08Z
[ "python", "graph", "ascii" ]
Python ASCII Graph Drawing
834,395
<p>I'm looking for a library to draw ASCII graphs (for use in a console) with Python. The graph is quite simple: it's only a flow chart for pipelines.</p> <p>I saw NetworkX and igraph, but didn't see a way to output to ascii.</p> <p>Do you have experience in this?</p> <p>Thanks a lot!</p> <p>Patrick</p> <p>EDIT 1: I actually found a library doing what I need, but it's in perl <a href="http://bloodgate.com/perl/graph/manual/output.html">Graph::Easy</a> . I could call the code from python but I don't like the idea too much... still looking for a python solution :)</p>
17
2009-05-07T12:33:34Z
1,983,374
<p><a href="http://www.algorithm.co.il/blogs/index.php/ascii-plotter/" rel="nofollow">ascii-plotter</a> might do what you want...</p>
2
2009-12-31T00:47:32Z
[ "python", "graph", "ascii" ]
How to do fuzzy string search without a heavy database?
834,570
<p>I have a mapping of catalog numbers to product names:</p> <pre><code>35 cozy comforter 35 warm blanket 67 pillow </code></pre> <p>and <strong>need a search that would find misspelled, mixed names like "warm cmfrter"</strong>.</p> <p>We have code using edit-distance (difflib), but it probably won't scale to the 18000 names.</p> <p>I achieved something similar with Lucene, but as <a href="http://lucene.apache.org/pylucene/">PyLucene</a> only wraps Java that would complicate deployment to end-users.</p> <p>SQLite doesn't usually have full-text or scoring compiled in.</p> <p>The <a href="http://www.xapian.org/docs/bindings/python/">Xapian bindings</a> are like C++ and have some learning curve.</p> <p><a href="http://whoosh.ca/">Whoosh</a> is not yet well-documented but includes an abusable spell-checker.</p> <p>What else is there?</p>
6
2009-05-07T13:11:30Z
834,656
<p><a href="http://nucular.sourceforge.net" rel="nofollow">Nucular</a> has full text search, but it doesn't support misspelled matches out-of-the box. You could try adding an additional field to each entry which indexes the <a href="http://code.activestate.com/recipes/52213/" rel="nofollow">SOUNDEX</a> translation of the terms and then search using the soundex translation of the user input. I really don't know how well this would work...</p> <p>Take a look at advas <a href="http://advas.sourceforge.net/news.php" rel="nofollow">http://advas.sourceforge.net/news.php</a> which has a nice demo comparing various soundex-alike methods:</p> <pre><code>advas/examples Aaron$ python phonetic_algorithms.py soundex metaphone nyiis caverphone ==================================================================================================== schmidt : S253 sxmtt sssnad SKMT111111 schmid : S253 sxmt sssnad SKMT111111 schmitt : S253 sxmt sssnatt SKMT111111 smith : S530 sm0h snatt SMT1111111 smythe : S530 smy0h snatt SMT1111111 schmied : S253 sxmt sssnaad SKMT111111 mayer : M600 myr naaar MA11111111 meier : M600 mr naaar MA11111111 .... </code></pre> <p>I don't know if any of them is good for your unnamed language...</p>
2
2009-05-07T13:30:32Z
[ "python", "database", "full-text-search", "fuzzy-search" ]
How to do fuzzy string search without a heavy database?
834,570
<p>I have a mapping of catalog numbers to product names:</p> <pre><code>35 cozy comforter 35 warm blanket 67 pillow </code></pre> <p>and <strong>need a search that would find misspelled, mixed names like "warm cmfrter"</strong>.</p> <p>We have code using edit-distance (difflib), but it probably won't scale to the 18000 names.</p> <p>I achieved something similar with Lucene, but as <a href="http://lucene.apache.org/pylucene/">PyLucene</a> only wraps Java that would complicate deployment to end-users.</p> <p>SQLite doesn't usually have full-text or scoring compiled in.</p> <p>The <a href="http://www.xapian.org/docs/bindings/python/">Xapian bindings</a> are like C++ and have some learning curve.</p> <p><a href="http://whoosh.ca/">Whoosh</a> is not yet well-documented but includes an abusable spell-checker.</p> <p>What else is there?</p>
6
2009-05-07T13:11:30Z
834,941
<p>You will get too many false positives with the SOUNDEX implementation. There are only 26,000 (at most) possible SOUNDEX codes.</p> <p>Though the Metaphone algorithim was designed for English surnames, it works pretty well for misspellings; I used it once in a branch locator and it was quite successful. </p> <p>Add a field with the Metaphone translation and match against it if no exact match is found. You will still get false positives, but fewer that with other algorithims.</p>
2
2009-05-07T14:23:58Z
[ "python", "database", "full-text-search", "fuzzy-search" ]
How to do fuzzy string search without a heavy database?
834,570
<p>I have a mapping of catalog numbers to product names:</p> <pre><code>35 cozy comforter 35 warm blanket 67 pillow </code></pre> <p>and <strong>need a search that would find misspelled, mixed names like "warm cmfrter"</strong>.</p> <p>We have code using edit-distance (difflib), but it probably won't scale to the 18000 names.</p> <p>I achieved something similar with Lucene, but as <a href="http://lucene.apache.org/pylucene/">PyLucene</a> only wraps Java that would complicate deployment to end-users.</p> <p>SQLite doesn't usually have full-text or scoring compiled in.</p> <p>The <a href="http://www.xapian.org/docs/bindings/python/">Xapian bindings</a> are like C++ and have some learning curve.</p> <p><a href="http://whoosh.ca/">Whoosh</a> is not yet well-documented but includes an abusable spell-checker.</p> <p>What else is there?</p>
6
2009-05-07T13:11:30Z
838,768
<p>The usual way of computing the edit-distance between two strings is a rather expensive algorithm (if I remember correctly, its time complexity is quadratic). Maybe if you used a different string similarity metric then your problem would go away.</p> <p>One of my favorite methods for fuzzy string matching is [trigrams matching]. Comparing two strings using this method has a linear time complexity, which is much better than the mentioned edit-distance. You can find my Python implementation on [Github]. There's also a PostgreSQL [contrib module] exactly for that. It shouldn't be too difficult to adapt it to work with SQLite3.</p>
1
2009-05-08T08:20:32Z
[ "python", "database", "full-text-search", "fuzzy-search" ]
How to do fuzzy string search without a heavy database?
834,570
<p>I have a mapping of catalog numbers to product names:</p> <pre><code>35 cozy comforter 35 warm blanket 67 pillow </code></pre> <p>and <strong>need a search that would find misspelled, mixed names like "warm cmfrter"</strong>.</p> <p>We have code using edit-distance (difflib), but it probably won't scale to the 18000 names.</p> <p>I achieved something similar with Lucene, but as <a href="http://lucene.apache.org/pylucene/">PyLucene</a> only wraps Java that would complicate deployment to end-users.</p> <p>SQLite doesn't usually have full-text or scoring compiled in.</p> <p>The <a href="http://www.xapian.org/docs/bindings/python/">Xapian bindings</a> are like C++ and have some learning curve.</p> <p><a href="http://whoosh.ca/">Whoosh</a> is not yet well-documented but includes an abusable spell-checker.</p> <p>What else is there?</p>
6
2009-05-07T13:11:30Z
869,212
<p><a href="http://www.sybase.com/products/databasemanagement/sqlanywhere" rel="nofollow">Sybase SQL Anywhere</a> has a free Web edition/Developer Edition and comes with full text indexing/search and a FUZZY operator (and some implementation constraints). </p> <p>To quote from the documentation:</p> <pre><code>Specifying 'FUZZY "500 main street"' is equivalent to '500 OR mai OR ain OR str OR tre OR ree OR eet'. </code></pre> <p>An other approach would be to use scoring on full-text searches.</p>
1
2009-05-15T15:02:52Z
[ "python", "database", "full-text-search", "fuzzy-search" ]
How to do fuzzy string search without a heavy database?
834,570
<p>I have a mapping of catalog numbers to product names:</p> <pre><code>35 cozy comforter 35 warm blanket 67 pillow </code></pre> <p>and <strong>need a search that would find misspelled, mixed names like "warm cmfrter"</strong>.</p> <p>We have code using edit-distance (difflib), but it probably won't scale to the 18000 names.</p> <p>I achieved something similar with Lucene, but as <a href="http://lucene.apache.org/pylucene/">PyLucene</a> only wraps Java that would complicate deployment to end-users.</p> <p>SQLite doesn't usually have full-text or scoring compiled in.</p> <p>The <a href="http://www.xapian.org/docs/bindings/python/">Xapian bindings</a> are like C++ and have some learning curve.</p> <p><a href="http://whoosh.ca/">Whoosh</a> is not yet well-documented but includes an abusable spell-checker.</p> <p>What else is there?</p>
6
2009-05-07T13:11:30Z
1,080,769
<p>Apparently the only way to make fuzzy comparisons fast is to do less of them ;)</p> <p>Instead of writing another n-gram search or improving the one in Whoosh we now keep a word index, retrieve all entries that have at least one (correctly spelled) word in common with the query, and use difflib to rank those. Works well enough in this case.</p>
4
2009-07-03T20:46:04Z
[ "python", "database", "full-text-search", "fuzzy-search" ]
How to do fuzzy string search without a heavy database?
834,570
<p>I have a mapping of catalog numbers to product names:</p> <pre><code>35 cozy comforter 35 warm blanket 67 pillow </code></pre> <p>and <strong>need a search that would find misspelled, mixed names like "warm cmfrter"</strong>.</p> <p>We have code using edit-distance (difflib), but it probably won't scale to the 18000 names.</p> <p>I achieved something similar with Lucene, but as <a href="http://lucene.apache.org/pylucene/">PyLucene</a> only wraps Java that would complicate deployment to end-users.</p> <p>SQLite doesn't usually have full-text or scoring compiled in.</p> <p>The <a href="http://www.xapian.org/docs/bindings/python/">Xapian bindings</a> are like C++ and have some learning curve.</p> <p><a href="http://whoosh.ca/">Whoosh</a> is not yet well-documented but includes an abusable spell-checker.</p> <p>What else is there?</p>
6
2009-05-07T13:11:30Z
8,161,560
<p>sqlite3 supports python callback functions. Matthew Barnett's regex (http://code.google.com/p/mrab-regex-hg/) now supports approximate matching.</p> <p>So, like this:</p> <pre><code>try: import regex except ImportError: sys.stderr.write("Can't import mrab-regex; see http://pypi.python.org/pypi/regex\n") sys.exit(1) def _sqlite3_regex(expr, item): return (not (not regex.search(expr, item))) def main(): ... database = sqlite3.connect(dbfile) database.create_function("regexp", 2, _sqlite3_regex) pattern = '(?:%s){e&lt;=%d}' % (queriedname, distance) print [x for x in database.cursor().execute( "SELECT * FROM products WHERE (productname regexp '%s')" % pattern)] </code></pre>
1
2011-11-17T02:58:38Z
[ "python", "database", "full-text-search", "fuzzy-search" ]
Mapping a database table to an attribute of an object
834,722
<p>I've come across a place in my current project where I have created several classes for storing a complicated data structure in memory and a completed SQL schema for storing the same data in a database. I've decided to use SQLAlchemy as an ORM layer as it seems the most flexible solution that I can tailor to my needs. </p> <p>My problem is that I now need to map an entire table to just an array attribute in memory and am struggling to find out if this is possible and, if it is, how to do it with SQLAlchemy. It is still possible for me to change the data structures in code (although less than ideal) if not, but I would prefer not to.</p> <p>The table in question is created using the following SQL:</p> <pre><code>CREATE TABLE `works` ( `id` BIGINT NOT NULL auto_increment, `uniform_title` VARCHAR(255) NOT NULL, `created_date` DATE NOT NULL, `context` TEXT, `distinguishing_characteristics` TEXT, PRIMARY KEY (`id`), INDEX (`uniform_title` ASC), INDEX (`uniform_title` DESC) ) ENGINE = InnoDB DEFAULT CHARSET = utf8 ; CREATE TABLE `variant_work_titles` ( `id` BIGINT NOT NULL auto_increment, `work_id` BIGINT NOT NULL, `title` VARCHAR(255) NOT NULL, PRIMARY KEY(`id`), INDEX (`work_id`), INDEX (`title` ASC), INDEX (`title` DESC), FOREIGN KEY (`work_id`) REFERENCES `works` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ; </code></pre> <p>This is just a small part of the complete database and the same thing is going to be required in several places.</p>
0
2009-05-07T13:43:41Z
835,231
<p>It seems you want something like</p> <pre><code>work_instance.variants = [&lt;some iterable of variants&gt;] </code></pre> <p>If not please clarify in your question.</p> <p>Ideally you should have 2 mappings to these 2 tables. It doesn't matter if you won't access the second mapping anywhere else. <code>work</code> mapping should have a one-to-many relationship to <code>variant</code> mapping. This would give you a list of <code>variant</code> instances associated with a particular <code>work</code> on whichever attribute you define your relationship.</p>
1
2009-05-07T15:07:41Z
[ "python", "database", "orm", "sqlalchemy" ]
Python's FTPLib too slow?
834,840
<p>I have been playing around with Python's FTP library and am starting to think that it is too slow as compared to using a script file in DOS? I run sessions where I download thousands of data files (I think I have over 8 million right now). My observation is that the download process seems to take five to ten times as long in Python than it does as compared to using the ftp commands in the DOS shell.</p> <p>Since I don't want anyone to fix my code I have not included any. I am more interested in understanding if my observation is valid or if I need to tinker more with the arguments.</p>
1
2009-05-07T14:05:11Z
834,923
<p>FTPlib may not be the cleanest Python API, I don't think it so bad that it run ten times slower than a DOS shell script.</p> <p>Unless you do not provide any code to compare, e.g you shell and you python snippet to batch dl 5000 files, I can't see how we can help you.</p>
2
2009-05-07T14:20:38Z
[ "python", "ftp", "performance", "dos" ]
Python's FTPLib too slow?
834,840
<p>I have been playing around with Python's FTP library and am starting to think that it is too slow as compared to using a script file in DOS? I run sessions where I download thousands of data files (I think I have over 8 million right now). My observation is that the download process seems to take five to ten times as long in Python than it does as compared to using the ftp commands in the DOS shell.</p> <p>Since I don't want anyone to fix my code I have not included any. I am more interested in understanding if my observation is valid or if I need to tinker more with the arguments.</p>
1
2009-05-07T14:05:11Z
835,026
<p>FTPLib is implemented in Python whereas your "DOS Script" is actually a script which calls a compiled command. Executing this command is probably faster than interpreting Python code. If it is too slow for you, I suggest to call the DOS command from Python using the <a href="http://docs.python.org/library/subprocess.html" rel="nofollow">subprocess module</a>.</p>
2
2009-05-07T14:35:34Z
[ "python", "ftp", "performance", "dos" ]
Python's FTPLib too slow?
834,840
<p>I have been playing around with Python's FTP library and am starting to think that it is too slow as compared to using a script file in DOS? I run sessions where I download thousands of data files (I think I have over 8 million right now). My observation is that the download process seems to take five to ten times as long in Python than it does as compared to using the ftp commands in the DOS shell.</p> <p>Since I don't want anyone to fix my code I have not included any. I am more interested in understanding if my observation is valid or if I need to tinker more with the arguments.</p>
1
2009-05-07T14:05:11Z
835,474
<p>The speed problem is probably in your code. FTPlib is not 10 times slower.</p>
2
2009-05-07T15:51:09Z
[ "python", "ftp", "performance", "dos" ]
Python's FTPLib too slow?
834,840
<p>I have been playing around with Python's FTP library and am starting to think that it is too slow as compared to using a script file in DOS? I run sessions where I download thousands of data files (I think I have over 8 million right now). My observation is that the download process seems to take five to ten times as long in Python than it does as compared to using the ftp commands in the DOS shell.</p> <p>Since I don't want anyone to fix my code I have not included any. I am more interested in understanding if my observation is valid or if I need to tinker more with the arguments.</p>
1
2009-05-07T14:05:11Z
4,941,599
<pre><code>import ftplib import time ftp = ftplib.FTP("localhost", "mph") t0 = time.time() with open('big.gz.sav', 'wb') as f: ftp.retrbinary('RETR ' + '/Temp/big.gz', f.write) t1 = time.time() ftp.close() ftp = ftplib.FTP("localhost", "mph") t2 = time.time() ftp.retrbinary('RETR ' + '/Temp/big.gz', lambda x: x) t3 = time.time() print "saving file: %f to %f: %f delta" % (t0, t1, t1 - t0) print "not saving file: %f to %f: %f delta" % (t2, t3, t3 - t2) </code></pre> <p>So, maybe not 10x. But my runs of this saving a file are all above 160s on a laptop with a core 1.8Ghz core i7 and 8GB of ram (should be overkill) running Windows 7. A native client does it at 100s. Without the file save I'm just under 70s.</p> <p>I came to this question because I've seen slow performance with ftplib on a mac (I'll rerun this test again once I have access to that machine again). While going async with the writes might be a good idea in this case, on a real network I suspect that would be far less of a gain.</p>
1
2011-02-09T05:22:27Z
[ "python", "ftp", "performance", "dos" ]
Python's FTPLib too slow?
834,840
<p>I have been playing around with Python's FTP library and am starting to think that it is too slow as compared to using a script file in DOS? I run sessions where I download thousands of data files (I think I have over 8 million right now). My observation is that the download process seems to take five to ten times as long in Python than it does as compared to using the ftp commands in the DOS shell.</p> <p>Since I don't want anyone to fix my code I have not included any. I am more interested in understanding if my observation is valid or if I need to tinker more with the arguments.</p>
1
2009-05-07T14:05:11Z
23,777,541
<p>disable ftplib and execute ftp via Msdos</p> <pre><code>os.system('FTP -v -i -s:C:\\ndfd\\wgrib2\\ftpscript.txt') </code></pre> <p>inside ftpscript.txt</p> <pre><code>open example.com username password !:--- FTP commands below here --- lcd c:\MyLocalDirectory cd public_html/MyRemoteDirectory binary mput "*.*" disconnect bye </code></pre>
1
2014-05-21T08:09:38Z
[ "python", "ftp", "performance", "dos" ]
Python's FTPLib too slow?
834,840
<p>I have been playing around with Python's FTP library and am starting to think that it is too slow as compared to using a script file in DOS? I run sessions where I download thousands of data files (I think I have over 8 million right now). My observation is that the download process seems to take five to ten times as long in Python than it does as compared to using the ftp commands in the DOS shell.</p> <p>Since I don't want anyone to fix my code I have not included any. I am more interested in understanding if my observation is valid or if I need to tinker more with the arguments.</p>
1
2009-05-07T14:05:11Z
26,314,086
<p>define blocksize along with storbinary of ftp connection,so you will get 1.5-3.0x more faster connection than FTP Filezilla :)</p> <pre><code>from ftplib import FTP USER = "Your_user_id" PASS = "Your_password" PORT = 21 SERVER = 'ftp.billionuploads.com' #use FTP server name here ftp = FTP() ftp.connect(SERVER, PORT) ftp.login(USER, PASS) try: file = open(r'C:\Python27\1.jpg','rb') ftp.storbinary('STOR ' + '1.jpg', file,102400) #here we store file in 100kb blocksize ftp.quit() file.close() print "File transfered" except: print "Error in File transfering" </code></pre>
1
2014-10-11T11:23:22Z
[ "python", "ftp", "performance", "dos" ]
Python's FTPLib too slow?
834,840
<p>I have been playing around with Python's FTP library and am starting to think that it is too slow as compared to using a script file in DOS? I run sessions where I download thousands of data files (I think I have over 8 million right now). My observation is that the download process seems to take five to ten times as long in Python than it does as compared to using the ftp commands in the DOS shell.</p> <p>Since I don't want anyone to fix my code I have not included any. I am more interested in understanding if my observation is valid or if I need to tinker more with the arguments.</p>
1
2009-05-07T14:05:11Z
33,668,081
<p>Bigger blocksize is not always the optimum. For example uploading the same 167 MB file through wired network to same FTP server I got following times in seconds for various blocksizes:</p> <pre><code>Blocksize Time 102400 40 51200 30 25600 28 32768 30 24576 31 19200 34 16384 61 12800 144 </code></pre> <p>In this configuration the optimum was around 32768 (4x8192).</p> <p>But if I used wireless instead, I got these times:</p> <pre><code>Blocksize Time 204800 78 102400 76 51200 79 25600 76 32768 89 24576 86 19200 75 16384 166 12800 178 default 223 </code></pre> <p>In this case there were several optimum blocksize values, all different from 32768.</p>
0
2015-11-12T09:25:07Z
[ "python", "ftp", "performance", "dos" ]
authentication method
834,932
<p>I am writing a server-client application to receive user message and publish it.</p> <p>Thinking about authentication method.</p> <ol> <li>Asymmetric encryption, probably RSA.</li> <li>Hash (salt+password+'msg'+'userid'), SHA256</li> <li>HMAC, SHA256. seems to be more secured than the method 2. Also involve hashing the password and msg data.</li> <li>Symmetric Encryption of the 'msg' with static password stored on both sides, probably AES.</li> </ol> <p>There is no need for encryption as the msg would be publish online anyway. So I am more lean to the HMAC or PKI method.</p> <p>I'm using java to send the request (including whatever authentication method to be implemented) www.mysite.com/foo?userid=12345&amp;msg=hello&amp;token=abc1234</p> <p>python on the server side to receive request and make sure the request is from the valid user.</p> <p>The problems are in integration and make sure both sides understand each other's authentication token. It is a big factor for me. And the availability of the libraries available on both language are taken into account as well.</p> <p>Or I can choose to rewrite the server side into java. (Why not python? The client side application need to be in java)</p> <p>What do you think?</p> <p><hr /></p> <p>EDIT: I would not treat this as a web application. The application does not serve any webpage. Most of the operations are not related to the web. Just the client-server communication go through internet. And sending POST/GET via HTTP is what I thought of as the simpler albeit insecure way to do it. Feel free to suggest me any other alternative. </p> <p>SSL is a secure way for encryption. But it does not prevent attacker from sending message to the server impose as the user. Anyone can initiate a HTTPS connection. And the content of the communication does not need to be encrypted. It will be published online by the server anyway. What I need is a way to authenticate the message and sender.</p> <p>For now I am lean to HMAC algorithm. RSA would be more secure but it comes with more developer efforts as well. Will see how it goes.</p> <p>Thank you.</p>
0
2009-05-07T14:22:25Z
835,136
<p>OK, firstly, an option to consider is just going down the "enterprise solution" route and buying into the standard PKI market: buy yourself a certificate from Veri$ign etc and use boring old HTTPS (or at least TLS, the underlying protocol). Then sending the data from the client is (more or less) a doddle, and there'll be a standard library in whatever langauge you choose to interpret things at the other end. I actually think HTTPS/TLS and the whole certificate infrastructure is a complicated waste of space for applications where you know what server you're talking to and you know what encryption system you want to use. But the availability of libraries "out of the box" means it <em>might</em> get you up and running quickly, so it's definitely worth considering one way or the other.</p> <p>In principle, you don't need a PKI-issued certificate to use HTTPS/TLS. But in practice, it may be easier to just spend the few dollars than try and persuade a standard library to accept a self-issued certificate. (In general, using HTTPS libraries may just mean you end up turning the 2-day "programming my encryption system" problem into a 2-day "why isn't this black box accepting my certificate" problem-- it also kind of depends on what problem you fancy solving...)</p> <p>Even if you don't use HTTPS/TLS, you may want to read through the spec, to understand how it overcomes certain security threats (and what those threats are).</p> <p>OK, so then taking your points:</p> <ul> <li>Just to be clear, you DON'T need a certificate or PKI to use RSA or other asymmetric encryption. A PKI (attemptedly) solves the problem of a client needing to talk to a "mystery" server that it can't trust when that server says "here is my public key". If you're writing a dedicated client and you know in advance which server you're talking to, then you can just distribute the public key with your client. The client knows it's talking to the right server, because if it wasn't, that server wouldn't understand things that it encrypted with that public key.</li> <li>The main thing you need to be careful of when using "raw" hashes is that they're vulnerable to extension attacks. So if you send "a|b|c" plus the hash code for that data, an attacker can work out the hash code for "a|b|c|d" (so in your example (2), they could substitute "userid" for "useridX" and work out a new hash code for this, based on the hash code you supplied for "a|b|c"). HMAC schemes get round this problem.</li> <li>In any case, if you go for using "raw" encryption tools, still use standard libraries, because they'll have thought about some security issues. For example, with RSA, you have to be careful to use padding (see some info I've written on <a href="http://www.javamex.com/tutorials/cryptography/rsa%5Fencryption.shtml" rel="nofollow">RSA encryption in Java</a> and the cryptography section it's in-- that might be interesting for you). And when generating any encryption key, you need to be careful about "where the random data is coming from".</li> <li>You don't have to base the AES encryption key on the password (if you do, read up on password-based encryption schemes: password generally have little entropy, so you need to take extra measures to try and protect against this). But I would go for the more standard approach of using the password to <em>authenticate</em> the connection, and as part of the authentication, negotiate a random AES key.</li> <li>Make sure that you're addressing the issue of <strong>replay attacks</strong> in your scheme (generally, the client and server should each send each other a random "nonce" at the start of the communication, and authentication and future communication over that connection will depend on the nonce).</li> </ul>
1
2009-05-07T14:53:48Z
[ "java", "python", "authentication", "encryption", "hash" ]
authentication method
834,932
<p>I am writing a server-client application to receive user message and publish it.</p> <p>Thinking about authentication method.</p> <ol> <li>Asymmetric encryption, probably RSA.</li> <li>Hash (salt+password+'msg'+'userid'), SHA256</li> <li>HMAC, SHA256. seems to be more secured than the method 2. Also involve hashing the password and msg data.</li> <li>Symmetric Encryption of the 'msg' with static password stored on both sides, probably AES.</li> </ol> <p>There is no need for encryption as the msg would be publish online anyway. So I am more lean to the HMAC or PKI method.</p> <p>I'm using java to send the request (including whatever authentication method to be implemented) www.mysite.com/foo?userid=12345&amp;msg=hello&amp;token=abc1234</p> <p>python on the server side to receive request and make sure the request is from the valid user.</p> <p>The problems are in integration and make sure both sides understand each other's authentication token. It is a big factor for me. And the availability of the libraries available on both language are taken into account as well.</p> <p>Or I can choose to rewrite the server side into java. (Why not python? The client side application need to be in java)</p> <p>What do you think?</p> <p><hr /></p> <p>EDIT: I would not treat this as a web application. The application does not serve any webpage. Most of the operations are not related to the web. Just the client-server communication go through internet. And sending POST/GET via HTTP is what I thought of as the simpler albeit insecure way to do it. Feel free to suggest me any other alternative. </p> <p>SSL is a secure way for encryption. But it does not prevent attacker from sending message to the server impose as the user. Anyone can initiate a HTTPS connection. And the content of the communication does not need to be encrypted. It will be published online by the server anyway. What I need is a way to authenticate the message and sender.</p> <p>For now I am lean to HMAC algorithm. RSA would be more secure but it comes with more developer efforts as well. Will see how it goes.</p> <p>Thank you.</p>
0
2009-05-07T14:22:25Z
836,074
<p>Can't you just use standard SSL sockets to secure the connection, validate the user with a password, and then send the message to be published? If there won't be many clients, you can even use a self-signed certificate and put it in a KeyStore in the client app, that way you won't need to buy a certificate from Verisign or anyone else.</p> <p>If you are storing the user's password hash on the server (as I think you should otherwise how are you going to validate the user's password), then you can first reproduce that hash on the client side (let's assume you hash user+pass) and then append that to the message and hash the result. You send the user id, hash and message to the server.</p> <p>On the server side you receive a request with a user id, you retrieve the user's password (the server only has stored the hash of user+pass), you append that to the message and hash it again, and compare it against the hash in the request. If it matches, the user can publish the message.</p> <p>Oh and you should use HTTP POST, instead of sending data on the URL. The server should not accept data on the URL for the publish request.</p>
2
2009-05-07T17:44:14Z
[ "java", "python", "authentication", "encryption", "hash" ]
authentication method
834,932
<p>I am writing a server-client application to receive user message and publish it.</p> <p>Thinking about authentication method.</p> <ol> <li>Asymmetric encryption, probably RSA.</li> <li>Hash (salt+password+'msg'+'userid'), SHA256</li> <li>HMAC, SHA256. seems to be more secured than the method 2. Also involve hashing the password and msg data.</li> <li>Symmetric Encryption of the 'msg' with static password stored on both sides, probably AES.</li> </ol> <p>There is no need for encryption as the msg would be publish online anyway. So I am more lean to the HMAC or PKI method.</p> <p>I'm using java to send the request (including whatever authentication method to be implemented) www.mysite.com/foo?userid=12345&amp;msg=hello&amp;token=abc1234</p> <p>python on the server side to receive request and make sure the request is from the valid user.</p> <p>The problems are in integration and make sure both sides understand each other's authentication token. It is a big factor for me. And the availability of the libraries available on both language are taken into account as well.</p> <p>Or I can choose to rewrite the server side into java. (Why not python? The client side application need to be in java)</p> <p>What do you think?</p> <p><hr /></p> <p>EDIT: I would not treat this as a web application. The application does not serve any webpage. Most of the operations are not related to the web. Just the client-server communication go through internet. And sending POST/GET via HTTP is what I thought of as the simpler albeit insecure way to do it. Feel free to suggest me any other alternative. </p> <p>SSL is a secure way for encryption. But it does not prevent attacker from sending message to the server impose as the user. Anyone can initiate a HTTPS connection. And the content of the communication does not need to be encrypted. It will be published online by the server anyway. What I need is a way to authenticate the message and sender.</p> <p>For now I am lean to HMAC algorithm. RSA would be more secure but it comes with more developer efforts as well. Will see how it goes.</p> <p>Thank you.</p>
0
2009-05-07T14:22:25Z
837,532
<p>RSA protocol is generally used to setup a key exchange for a faster encryption means. That's how SSL works. </p> <p>If the security requirements for your applications are so sensitive that you require PKI, then it should be said (without any intent to be harsh) that if you need to ask about it on SO, then its probably something you shouldn't attempt to do (given that generally successful attacks on secure channels attack weakpoints of the implementation).</p> <p>As Chochos has suggested, what's wrong with simply using the existing SSL infrastructure in Java and your server to set up a secure https connection and then simply pass the user password from client to the server?</p>
0
2009-05-07T23:20:15Z
[ "java", "python", "authentication", "encryption", "hash" ]
authentication method
834,932
<p>I am writing a server-client application to receive user message and publish it.</p> <p>Thinking about authentication method.</p> <ol> <li>Asymmetric encryption, probably RSA.</li> <li>Hash (salt+password+'msg'+'userid'), SHA256</li> <li>HMAC, SHA256. seems to be more secured than the method 2. Also involve hashing the password and msg data.</li> <li>Symmetric Encryption of the 'msg' with static password stored on both sides, probably AES.</li> </ol> <p>There is no need for encryption as the msg would be publish online anyway. So I am more lean to the HMAC or PKI method.</p> <p>I'm using java to send the request (including whatever authentication method to be implemented) www.mysite.com/foo?userid=12345&amp;msg=hello&amp;token=abc1234</p> <p>python on the server side to receive request and make sure the request is from the valid user.</p> <p>The problems are in integration and make sure both sides understand each other's authentication token. It is a big factor for me. And the availability of the libraries available on both language are taken into account as well.</p> <p>Or I can choose to rewrite the server side into java. (Why not python? The client side application need to be in java)</p> <p>What do you think?</p> <p><hr /></p> <p>EDIT: I would not treat this as a web application. The application does not serve any webpage. Most of the operations are not related to the web. Just the client-server communication go through internet. And sending POST/GET via HTTP is what I thought of as the simpler albeit insecure way to do it. Feel free to suggest me any other alternative. </p> <p>SSL is a secure way for encryption. But it does not prevent attacker from sending message to the server impose as the user. Anyone can initiate a HTTPS connection. And the content of the communication does not need to be encrypted. It will be published online by the server anyway. What I need is a way to authenticate the message and sender.</p> <p>For now I am lean to HMAC algorithm. RSA would be more secure but it comes with more developer efforts as well. Will see how it goes.</p> <p>Thank you.</p>
0
2009-05-07T14:22:25Z
840,803
<p>Let me just add a few random thoughts/comments to your proposals.</p> <ol> <li>RSA: Since you are mainly interested in authentication, I assume you'd want to use RSA signatures. This would imply that each user needs his own privat key. To me that sounds a little bit like overkill, especially when user and server already share common secrets (i.e., passwords).</li> <li>Using SHA256 is a good approach. I have some problems to understand why you include a salt, since a salt is commonly use to avoid that an attacker precomputes hashes of dictionaries. To be clear: dicitionary attacks are a problem here. An attacker could try to hash messages with all passwords from a dictionary. Just he has to reapeat this attack for each user and can't reuse precomputed values. One way to make such an attack a little more difficult is called key strengthening, e.g. by reapeatedly hashing the result n times and hence forcing an attacker to perform more work during a dictionary attack.</li> <li>I completely agree that HMAC is better than just SHA-256. After all HMAC was designed for authentication. I'm not sure why you want to hash the message before computing the HMAC. HMAC does that for you.</li> <li>Encryption does not always provide authentication. This is specially in cases when the attacker learns the plaintext, as he does in your case. He might be able to exploit properties of the encryption mode to manipulate the ciphertext an know exactly how the resulting plaintext will look like (E.g. the CBC mode allows these kind of manipulations). Your previous proposal (HMAC) is preferable.</li> </ol> <p>Finally, if you can setup an SSL connection between user and server, as others suggest: this would be a much safer solution, since not even the dicionary attack mentioned above would be possible.</p>
1
2009-05-08T16:52:37Z
[ "java", "python", "authentication", "encryption", "hash" ]
Python dictionary: are keys() and values() always the same order?
835,092
<p>It looks like the lists returned by <code>keys()</code> and <code>values()</code> methods of a dictionary are always a 1-to-1 mapping (assuming the dictionary is not altered between calling the 2 methods).</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'one':1, 'two': 2, 'three': 3} &gt;&gt;&gt; k, v = d.keys(), d.values() &gt;&gt;&gt; for i in range(len(k)): print d[k[i]] == v[i] True True True </code></pre> <p>If you do not alter the dictionary between calling <code>keys()</code> and calling <code>values()</code>, is it wrong to assume the above for-loop will always print True? I could not find any documentation confirming this.</p>
132
2009-05-07T14:46:13Z
835,111
<p>Yes, what you observed is indeed a guaranteed property -- keys(), values() and items() return lists in congruent order if the dict is not altered. iterkeys() &amp;c also iterate in the same order as the corresponding lists.</p>
59
2009-05-07T14:49:34Z
[ "python" ]
Python dictionary: are keys() and values() always the same order?
835,092
<p>It looks like the lists returned by <code>keys()</code> and <code>values()</code> methods of a dictionary are always a 1-to-1 mapping (assuming the dictionary is not altered between calling the 2 methods).</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'one':1, 'two': 2, 'three': 3} &gt;&gt;&gt; k, v = d.keys(), d.values() &gt;&gt;&gt; for i in range(len(k)): print d[k[i]] == v[i] True True True </code></pre> <p>If you do not alter the dictionary between calling <code>keys()</code> and calling <code>values()</code>, is it wrong to assume the above for-loop will always print True? I could not find any documentation confirming this.</p>
132
2009-05-07T14:46:13Z
835,255
<p>According to <a href="http://docs.python.org/dev/py3k/library/stdtypes.html#dictionary-view-objects">http://docs.python.org/dev/py3k/library/stdtypes.html#dictionary-view-objects</a> , the keys(), values() and items() methods of a dict will return corresponding iterators whose orders correspond. However, I am unable to find a reference to the official documentation for python 2.x for the same thing.</p> <p>So as far as I can tell, the answer is yes, but only in python 3.0+</p>
5
2009-05-07T15:10:48Z
[ "python" ]
Python dictionary: are keys() and values() always the same order?
835,092
<p>It looks like the lists returned by <code>keys()</code> and <code>values()</code> methods of a dictionary are always a 1-to-1 mapping (assuming the dictionary is not altered between calling the 2 methods).</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'one':1, 'two': 2, 'three': 3} &gt;&gt;&gt; k, v = d.keys(), d.values() &gt;&gt;&gt; for i in range(len(k)): print d[k[i]] == v[i] True True True </code></pre> <p>If you do not alter the dictionary between calling <code>keys()</code> and calling <code>values()</code>, is it wrong to assume the above for-loop will always print True? I could not find any documentation confirming this.</p>
132
2009-05-07T14:46:13Z
835,295
<p>Yes it is <a href="https://docs.python.org/2/library/stdtypes.html#dictionary-view-objects">guaranteed in python 2.x</a>:</p> <blockquote> <p>If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond.</p> </blockquote>
35
2009-05-07T15:20:08Z
[ "python" ]
Python dictionary: are keys() and values() always the same order?
835,092
<p>It looks like the lists returned by <code>keys()</code> and <code>values()</code> methods of a dictionary are always a 1-to-1 mapping (assuming the dictionary is not altered between calling the 2 methods).</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'one':1, 'two': 2, 'three': 3} &gt;&gt;&gt; k, v = d.keys(), d.values() &gt;&gt;&gt; for i in range(len(k)): print d[k[i]] == v[i] True True True </code></pre> <p>If you do not alter the dictionary between calling <code>keys()</code> and calling <code>values()</code>, is it wrong to assume the above for-loop will always print True? I could not find any documentation confirming this.</p>
132
2009-05-07T14:46:13Z
835,298
<p>For what it's worth, some heavy used production code I have written is based on this assumption and I never had a problem with it. I know that doesn't make it true though :-)</p> <p>If you don't want to take the risk I would use iteritems() if you can.</p> <pre><code>for key, value in myDictionary.iteritems(): print key, value </code></pre>
3
2009-05-07T15:21:05Z
[ "python" ]
Python dictionary: are keys() and values() always the same order?
835,092
<p>It looks like the lists returned by <code>keys()</code> and <code>values()</code> methods of a dictionary are always a 1-to-1 mapping (assuming the dictionary is not altered between calling the 2 methods).</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'one':1, 'two': 2, 'three': 3} &gt;&gt;&gt; k, v = d.keys(), d.values() &gt;&gt;&gt; for i in range(len(k)): print d[k[i]] == v[i] True True True </code></pre> <p>If you do not alter the dictionary between calling <code>keys()</code> and calling <code>values()</code>, is it wrong to assume the above for-loop will always print True? I could not find any documentation confirming this.</p>
132
2009-05-07T14:46:13Z
835,430
<p>Found this:</p> <blockquote> <p>If <code>items()</code>, <code>keys()</code>, <code>values()</code>, <code>iteritems()</code>, <code>iterkeys()</code>, and <code>itervalues()</code> are called with no intervening modifications to the dictionary, the lists will directly correspond.</p> </blockquote> <p>On <a href="http://docs.python.org/library/stdtypes.html#dict.items">2.x documentation</a> and <a href="https://docs.python.org/3/library/stdtypes.html#dictionary-view-objects">3.x documentation</a>.</p>
143
2009-05-07T15:45:47Z
[ "python" ]
Python dictionary: are keys() and values() always the same order?
835,092
<p>It looks like the lists returned by <code>keys()</code> and <code>values()</code> methods of a dictionary are always a 1-to-1 mapping (assuming the dictionary is not altered between calling the 2 methods).</p> <p>For example:</p> <pre><code>&gt;&gt;&gt; d = {'one':1, 'two': 2, 'three': 3} &gt;&gt;&gt; k, v = d.keys(), d.values() &gt;&gt;&gt; for i in range(len(k)): print d[k[i]] == v[i] True True True </code></pre> <p>If you do not alter the dictionary between calling <code>keys()</code> and calling <code>values()</code>, is it wrong to assume the above for-loop will always print True? I could not find any documentation confirming this.</p>
132
2009-05-07T14:46:13Z
33,065,618
<p>As already pointed out yes, many practical uses would be zipping both of them.</p> <pre><code>zip(d.keys(), d.values()) </code></pre> <p>Since the order of access remain the same though not predictable the above would always return same (key,value) tuple.</p>
-2
2015-10-11T13:36:57Z
[ "python" ]
Extending Python's builtin Str
835,469
<p>I'm trying to subclass <code>str</code>, but having some difficulties due to its immutability.</p> <pre><code>class DerivedClass(str): def __new__(cls, string): ob = super(DerivedClass, cls).__new__(cls, string) return ob def upper(self): #overridden, new functionality. Return ob of type DerivedClass. Great. caps = super(DerivedClass, self).upper() return DerivedClass(caps + '123') derived = DerivedClass('a') print derived.upper() #'A123' print type(derived.upper()) #&lt;class '__main__.DerivedClass'&gt; print derived.lower() #'a' print type(derived.lower()) #&lt;type 'str'&gt; </code></pre> <p>For inherited methods that don't require any new functionality, such as <code>derived.lower()</code>, is there a simple, pythonic way to return an object of type <code>DerivedClass</code> (instead of <code>str</code>)? Or am I stuck manually overriding each str.method(), as I did with <code>derived.upper()</code>?</p> <p>Edit:</p> <pre><code>#Any massive flaws in the following? class DerivedClass(str): def __new__(cls, string): ob = super(DerivedClass, cls).__new__(cls, string) return ob def upper(self): caps = super(DerivedClass, self).upper() return DerivedClass(caps + '123') def __getattribute__(self, name): att = super(DerivedClass, self).__getattribute__(name) if not callable(att): return att def call_me_later(*args, **kwargs): result = att(*args, **kwargs) if isinstance(result, basestring): return DerivedClass(result) return result return call_me_later </code></pre>
14
2009-05-07T15:50:29Z
835,523
<p>You might be able to do this by overriding <code>__getattribute__</code>.</p> <pre><code>def __getattribute__(self, name): # Simple hardcoded check for upper. # I'm sure there are better ways to get the list of defined methods in # your class and see if name is contained in it. if name == 'upper': return object.__getattribute__(self, name) return DerivedClass(object.__getattribute__(self, name)) </code></pre>
-2
2009-05-07T15:58:08Z
[ "python", "oop", "inheritance", "override", "immutability" ]
Extending Python's builtin Str
835,469
<p>I'm trying to subclass <code>str</code>, but having some difficulties due to its immutability.</p> <pre><code>class DerivedClass(str): def __new__(cls, string): ob = super(DerivedClass, cls).__new__(cls, string) return ob def upper(self): #overridden, new functionality. Return ob of type DerivedClass. Great. caps = super(DerivedClass, self).upper() return DerivedClass(caps + '123') derived = DerivedClass('a') print derived.upper() #'A123' print type(derived.upper()) #&lt;class '__main__.DerivedClass'&gt; print derived.lower() #'a' print type(derived.lower()) #&lt;type 'str'&gt; </code></pre> <p>For inherited methods that don't require any new functionality, such as <code>derived.lower()</code>, is there a simple, pythonic way to return an object of type <code>DerivedClass</code> (instead of <code>str</code>)? Or am I stuck manually overriding each str.method(), as I did with <code>derived.upper()</code>?</p> <p>Edit:</p> <pre><code>#Any massive flaws in the following? class DerivedClass(str): def __new__(cls, string): ob = super(DerivedClass, cls).__new__(cls, string) return ob def upper(self): caps = super(DerivedClass, self).upper() return DerivedClass(caps + '123') def __getattribute__(self, name): att = super(DerivedClass, self).__getattribute__(name) if not callable(att): return att def call_me_later(*args, **kwargs): result = att(*args, **kwargs) if isinstance(result, basestring): return DerivedClass(result) return result return call_me_later </code></pre>
14
2009-05-07T15:50:29Z
835,859
<p>You can do this by overriding <code>__getattribute__</code> as Zr40 suggests, but you will need to have getattribute return a callable function. The sample below should give you what you want; it uses the <code>functools.partial</code> wrapper to make life easier, though you could implement it without partial if you like:</p> <pre><code>from functools import partial class DerivedClass(str): def __new__(cls, string): ob = super(DerivedClass, cls).__new__(cls, string) return ob def upper(self): #overridden, new functionality. Return ob of type DerivedClass. Great. caps = super(DerivedClass, self).upper() return DerivedClass(caps + '123') def __getattribute__(self, name): func = str.__getattribute__(self, name) if name == 'upper': return func if not callable(func): return func def call_me_later(*args, **kwargs): result = func(*args, **kwargs) # Some str functions return lists, ints, etc if isinstance(result, basestring: return DerivedClass(result) return result return partial(call_me_later) </code></pre>
5
2009-05-07T16:56:42Z
[ "python", "oop", "inheritance", "override", "immutability" ]
Extending Python's builtin Str
835,469
<p>I'm trying to subclass <code>str</code>, but having some difficulties due to its immutability.</p> <pre><code>class DerivedClass(str): def __new__(cls, string): ob = super(DerivedClass, cls).__new__(cls, string) return ob def upper(self): #overridden, new functionality. Return ob of type DerivedClass. Great. caps = super(DerivedClass, self).upper() return DerivedClass(caps + '123') derived = DerivedClass('a') print derived.upper() #'A123' print type(derived.upper()) #&lt;class '__main__.DerivedClass'&gt; print derived.lower() #'a' print type(derived.lower()) #&lt;type 'str'&gt; </code></pre> <p>For inherited methods that don't require any new functionality, such as <code>derived.lower()</code>, is there a simple, pythonic way to return an object of type <code>DerivedClass</code> (instead of <code>str</code>)? Or am I stuck manually overriding each str.method(), as I did with <code>derived.upper()</code>?</p> <p>Edit:</p> <pre><code>#Any massive flaws in the following? class DerivedClass(str): def __new__(cls, string): ob = super(DerivedClass, cls).__new__(cls, string) return ob def upper(self): caps = super(DerivedClass, self).upper() return DerivedClass(caps + '123') def __getattribute__(self, name): att = super(DerivedClass, self).__getattribute__(name) if not callable(att): return att def call_me_later(*args, **kwargs): result = att(*args, **kwargs) if isinstance(result, basestring): return DerivedClass(result) return result return call_me_later </code></pre>
14
2009-05-07T15:50:29Z
835,913
<p>You're both close, but checking for each doesn't extend well to overriding many methods.</p> <pre><code>from functools import partial class DerivedClass(str): def __new__(cls, string): ob = super(DerivedClass, cls).__new__(cls, string) return ob def upper(self): caps = super(DerivedClass, self).upper() return DerivedClass(caps + '123') def __getattribute__(self, name): if name in ['__dict__', '__members__', '__methods__', '__class__']: return object.__getattribute__(self, name) func = str.__getattribute__(self, name) if name in self.__dict__.keys() or not callable(func): return func def call_me_later(*args, **kwargs): result = func(*args, **kwargs) # Some str functions return lists, ints, etc if isinstance(result, basestring): return DerivedClass(result) return result return partial(call_me_later) </code></pre> <p><sub>(Improvements suggested by <a href="http://stackoverflow.com/users/72247/jarret-hardie">jarret hardie</a> in comments.)</sub></p>
5
2009-05-07T17:10:53Z
[ "python", "oop", "inheritance", "override", "immutability" ]
Extending Python's builtin Str
835,469
<p>I'm trying to subclass <code>str</code>, but having some difficulties due to its immutability.</p> <pre><code>class DerivedClass(str): def __new__(cls, string): ob = super(DerivedClass, cls).__new__(cls, string) return ob def upper(self): #overridden, new functionality. Return ob of type DerivedClass. Great. caps = super(DerivedClass, self).upper() return DerivedClass(caps + '123') derived = DerivedClass('a') print derived.upper() #'A123' print type(derived.upper()) #&lt;class '__main__.DerivedClass'&gt; print derived.lower() #'a' print type(derived.lower()) #&lt;type 'str'&gt; </code></pre> <p>For inherited methods that don't require any new functionality, such as <code>derived.lower()</code>, is there a simple, pythonic way to return an object of type <code>DerivedClass</code> (instead of <code>str</code>)? Or am I stuck manually overriding each str.method(), as I did with <code>derived.upper()</code>?</p> <p>Edit:</p> <pre><code>#Any massive flaws in the following? class DerivedClass(str): def __new__(cls, string): ob = super(DerivedClass, cls).__new__(cls, string) return ob def upper(self): caps = super(DerivedClass, self).upper() return DerivedClass(caps + '123') def __getattribute__(self, name): att = super(DerivedClass, self).__getattribute__(name) if not callable(att): return att def call_me_later(*args, **kwargs): result = att(*args, **kwargs) if isinstance(result, basestring): return DerivedClass(result) return result return call_me_later </code></pre>
14
2009-05-07T15:50:29Z
836,963
<p>Good use for a class decorator -- roughly (untested code):</p> <pre><code>@do_overrides class Myst(str): def upper(self): ...&amp;c... </code></pre> <p>and</p> <pre><code>def do_overrides(cls): done = set(dir(cls)) base = cls.__bases__[0] def wrap(f): def wrapper(*a, **k): r = f(*a, **k) if isinstance(r, base): r = cls(r) return r for m in dir(base): if m in done or not callable(m): continue setattr(cls, m, wrap(getattr(base, m))) </code></pre>
7
2009-05-07T20:51:12Z
[ "python", "oop", "inheritance", "override", "immutability" ]
Can I use a List Comprehension to get Line Indexes from a file?
835,572
<p>I need to identify some locations in a file where certain markers might be. I started off thinking that I would use list.index but I soon discovered that returns the first (and only the first) item. so I decided to implement my own solution which was</p> <pre><code>count=0 docIndex=[] for line in open('myfile.txt','r'): if 'mystring' in line: docIndex.append(count) count+=1 </code></pre> <p>But this is Python right. There has to be a simpler solution since well it is Python. Hunting around this site and the web I came up with something slightly better</p> <pre><code>newDocIndex=[] for line in fileinput.input('myfile',inplace=1): if 'mystring' in line: newDocIndex.append(fileinput.lineno()) </code></pre> <p>I know this is too much info but since I finished grading finals last night I thought well-this is Python and we want to make some headway this summer-lets try a list comprehension</p> <p>so I did this:</p> <pre><code>[fileinput.lineno() for line in fileinput.input('myfile',inplace=1) if 'mystring' in line] </code></pre> <p>and got an empty list. So I first guessed that the problem is that the item in the for has to be the item that is used to build the list. That is if I had line instead of <code>fileinput.lineno()</code> I would have had a non-empty list but that is not the issue.</p> <p>Can the above process be reduced to a list comprehension?</p> <p>Using the answer but adjusting it for readability</p> <pre><code>listOfLines=[lineNumb for lineNumb,dataLine in enumerate(open('myfile')) if 'mystring' in dataLine] </code></pre>
0
2009-05-07T16:04:39Z
835,586
<p>What about this?</p> <pre><code>[index for index,line in enumerate(open('myfile.txt')) if 'mystring' in line] </code></pre>
8
2009-05-07T16:07:15Z
[ "python", "list-comprehension" ]
Elixir (SqlAlchemy): relations between 3 tables with composite primary keys
835,834
<p>I've 3 tables:</p> <ul> <li>A Company table with <code>(company_id)</code> primary key</li> <li>A Page table with <code>(company_id, url)</code> primary key &amp; a foreign key back to Company</li> <li>An Attr table with <code>(company_id, attr_key)</code> primary key &amp; a foreign key back to Company.</li> </ul> <p>My question is how to construct the ManyToOne relation from Attr back to Page using the existing columns in Attr, i.e. <code>company_id</code> and <code>url</code>? </p> <pre><code>from elixir import Entity, has_field, setup_all, ManyToOne, OneToMany, Field, Unicode, using_options from sqlalchemy.orm import relation class Company(Entity): using_options(tablename='company') company_id = Field(Unicode(32), primary_key=True) has_field('display_name', Unicode(255)) pages = OneToMany('Page') class Page(Entity): using_options(tablename='page') company = ManyToOne('Company', colname='company_id', primary_key=True) url = Field(Unicode(255), primary_key=True) class Attr(Entity): using_options(tablename='attr') company = ManyToOne('Company', colname='company_id', primary_key=True) attr_key = Field(Unicode(255), primary_key=True) url = Field(Unicode(255)) #, ForeignKey('page.url')) # page = ManyToOne('Page', colname=["company_id", "url"]) # page = relation(Page, backref='attrs', foreign_keys=["company_id", "url"], primaryjoin=and_(url==Page.url_part, company_id==Page.company_id)) </code></pre> <p>I've commented out some failed attempts.</p> <p>In the end, Attr.company_id will need to be a foreignkey to both Page and Company (as well as a primary key in Attr).</p> <p>Is this possible?</p>
1
2009-05-07T16:50:58Z
866,393
<p>Yes you can do this. Elixir doesn't have a built in way to do this, but because it's a thin wrapper on SQLAlchemy you can convince it to do this. Because Elixir doesn't have a concept of a many-to-one relation that reuses existing columns you need to use the GenericProperty with the SQLAlchemy relation property and add the foreign key using table options. The following code should do what you want:</p> <pre><code>from elixir import Entity, has_field, setup_all, ManyToOne, OneToMany, Field, Unicode, using_options, using_table_options, GenericProperty from sqlalchemy.orm import relation from sqlalchemy import ForeignKeyConstraint class Company(Entity): using_options(tablename='company') company_id = Field(Unicode(32), primary_key=True) display_name = Field(Unicode(255)) pages = OneToMany('Page') class Page(Entity): using_options(tablename='page') company = ManyToOne('Company', colname='company_id', primary_key=True) url = Field(Unicode(255), primary_key=True) attrs = OneToMany('Attr') class Attr(Entity): using_options(tablename='attr') page = ManyToOne('Page', colname=['company_id', 'url'], primary_key=True) attr_key = Field(Unicode(255), primary_key=True) using_table_options(ForeignKeyConstraint(['company_id'], ['company.company_id'])) company = GenericProperty(relation(Company)) </code></pre>
2
2009-05-14T23:34:12Z
[ "python", "sqlalchemy", "python-elixir" ]
How can I set a custom response header for pylons static (public) files?
836,191
<p>How do I add a custom header to files pylons is serving from public?</p>
2
2009-05-07T18:13:41Z
837,561
<p>a) Let your webserver serve files from /public instead of paster and configure it to pass some special headers.</p> <p>b) Add a special route and <a href="http://pythonpaste.org/modules/fileapp.html" rel="nofollow">serve the files yourself ala</a></p> <pre><code>class FilesController(BaseController): def download(self, path) fapp = FileApp( path, headers=self.get_headers(path) ) return fapp(request.environ, self.start_response) </code></pre> <p>c) maybe there is a way to overwrite headers and i just dont know how.</p>
2
2009-05-07T23:29:20Z
[ "python", "http-headers", "pylons" ]
How can I set a custom response header for pylons static (public) files?
836,191
<p>How do I add a custom header to files pylons is serving from public?</p>
2
2009-05-07T18:13:41Z
1,627,475
<p>With a recent version of route, you can use the '<a href="http://routes.groovie.org/manual.html#magic-path-info" rel="nofollow">Magic path_info</a>' feature, and follow the documentation from here to write your controller so it calls paster.DirectoryApp.</p> <p>In my project, I wanted to serve any file in the public directory, including subdirs, and ended with this as controller, to be able to override content_type :</p> <pre><code>import logging from paste.fileapp import FileApp from paste.urlparser import StaticURLParser from pylons import config from os.path import basename class ForceDownloadController(StaticURLParser): def __init__(self, directory=None, root_directory=None, cache_max_age=None): if not directory: directory = config['pylons.paths']['static_files'] StaticURLParser.__init__(self, directory, root_directory, cache_max_age) def make_app(self, filename): headers = [('Content-Disposition', 'filename=%s' % (basename(filename)))] return FileApp(filename, headers, content_type='application/octetstream') </code></pre>
0
2009-10-26T21:38:20Z
[ "python", "http-headers", "pylons" ]
How can I set a custom response header for pylons static (public) files?
836,191
<p>How do I add a custom header to files pylons is serving from public?</p>
2
2009-05-07T18:13:41Z
2,656,741
<p>In a standard Pylons setup, the public files are served from a StaticUrlParser. This is typically setup in your config/middleware.py:make_app() function</p> <p>You need to subclass the StaticUrlParser like Antonin ENFRUN describes, though calling it a Controller is confusing because it's doing a different purpose. Add something like the following to the top of the config/middleware.py:</p> <pre><code>from paste.fileapp import FileApp from paste.urlparser import StaticURLParser class HeaderUrlParser(StaticURLParser): def make_app(self, filename): headers = # your headers here return FileApp(filename, headers, content_type='application/octetstream') </code></pre> <p>then replace StaticUrlParser in config/middleware.py:make_app() with HeaderUrlParser</p> <pre><code> static_app = StaticURLParser(config['pylons.paths']['static_files']) </code></pre> <p>becomes</p> <pre><code> static_app = HeaderURLParser(config['pylons.paths']['static_files']) </code></pre>
0
2010-04-17T00:26:30Z
[ "python", "http-headers", "pylons" ]
How can I set a custom response header for pylons static (public) files?
836,191
<p>How do I add a custom header to files pylons is serving from public?</p>
2
2009-05-07T18:13:41Z
13,825,248
<p>A simpler way to use FileApp for streaming, based on the <a href="http://pylonsbook.com/en/1.1/the-web-server-gateway-interface-wsgi.html" rel="nofollow">pylons book</a>. The code below assumes your route provides <code>some_file_identifier</code>, but the other two variables are "magic" (see explanation after code).</p> <pre><code>class MyFileController(BaseController): def serve(self, environ, start_response, some_file_identifier): path = self._convert_id_to_path(some_file_identifier) app = FileApp(path) return app(environ, start_response) </code></pre> <p>Pylons automatically gives you the wsgi <code>environ</code> and <code>start_response</code> variables if you have variables of those names in your method signature. You should not need to set or munge headers otherwise, but if you do you can use the abilities <a href="http://pythonpaste.org/modules/fileapp.html" rel="nofollow">built in to FileApp</a> to achieve this.</p>
0
2012-12-11T17:20:35Z
[ "python", "http-headers", "pylons" ]
How can I tell if a python variable is a string or a list?
836,387
<p>I have a routine that takes a list of strings as a parameter, but I'd like to support passing in a single string and converting it to a list of one string. For example:</p> <pre><code>def func( files ): for f in files: doSomethingWithFile( f ) func( ['file1','file2','file3'] ) func( 'file1' ) # should be treated like ['file1'] </code></pre> <p>How can my function tell whether a string or a list has been passed in? I know there is a <code>type</code> function, but is there a "more pythonic" way?</p>
51
2009-05-07T18:53:26Z
836,402
<pre><code>isinstance(your_var, basestring) </code></pre>
31
2009-05-07T18:57:40Z
[ "python", "list", "duck-typing" ]
How can I tell if a python variable is a string or a list?
836,387
<p>I have a routine that takes a list of strings as a parameter, but I'd like to support passing in a single string and converting it to a list of one string. For example:</p> <pre><code>def func( files ): for f in files: doSomethingWithFile( f ) func( ['file1','file2','file3'] ) func( 'file1' ) # should be treated like ['file1'] </code></pre> <p>How can my function tell whether a string or a list has been passed in? I know there is a <code>type</code> function, but is there a "more pythonic" way?</p>
51
2009-05-07T18:53:26Z
836,406
<p>Well, there's nothing unpythonic about checking type. Having said that, if you're willing to put a small burden on the caller:</p> <pre><code>def func( *files ): for f in files: doSomethingWithFile( f ) func( *['file1','file2','file3'] ) #Is treated like func('file1','file2','file3') func( 'file1' ) </code></pre> <p>I'd argue this is more pythonic in that "explicit is better than implicit". Here there is at least a recognition on the part of the caller when the input is already in list form.</p>
30
2009-05-07T18:58:29Z
[ "python", "list", "duck-typing" ]
How can I tell if a python variable is a string or a list?
836,387
<p>I have a routine that takes a list of strings as a parameter, but I'd like to support passing in a single string and converting it to a list of one string. For example:</p> <pre><code>def func( files ): for f in files: doSomethingWithFile( f ) func( ['file1','file2','file3'] ) func( 'file1' ) # should be treated like ['file1'] </code></pre> <p>How can my function tell whether a string or a list has been passed in? I know there is a <code>type</code> function, but is there a "more pythonic" way?</p>
51
2009-05-07T18:53:26Z
836,407
<p>Personally, I don't really like this sort of behavior -- it interferes with duck typing. One could argue that it doesn't obey the "Explicit is better than implicit" mantra. Why not use the varargs syntax:</p> <pre><code>def func( *files ): for f in files: doSomethingWithFile( f ) func( 'file1', 'file2', 'file3' ) func( 'file1' ) func( *listOfFiles ) </code></pre>
30
2009-05-07T18:58:58Z
[ "python", "list", "duck-typing" ]
How can I tell if a python variable is a string or a list?
836,387
<p>I have a routine that takes a list of strings as a parameter, but I'd like to support passing in a single string and converting it to a list of one string. For example:</p> <pre><code>def func( files ): for f in files: doSomethingWithFile( f ) func( ['file1','file2','file3'] ) func( 'file1' ) # should be treated like ['file1'] </code></pre> <p>How can my function tell whether a string or a list has been passed in? I know there is a <code>type</code> function, but is there a "more pythonic" way?</p>
51
2009-05-07T18:53:26Z
836,535
<p>I would say the most Python'y way is to make the user always pass a list, even if there is only one item in it. It makes it really obvious <code>func()</code> can take a list of files</p> <pre><code>def func(files): for cur_file in files: blah(cur_file) func(['file1']) </code></pre> <p>As Dave suggested, you could use the <code>func(*files)</code> syntax, but I never liked this feature, and it seems more explicit ("explicit is better than implicit") to simply require a list. It's also turning your special-case (calling <code>func</code> with a single file) into the default case, because now you have to use extra syntax to call <code>func</code> with a list..</p> <p>If you do want to make a special-case for an argument being a string, use the <a href="http://docs.python.org/library/functions.html#isinstance"><code>isinstance()</code> builtin</a>, and compare to <code>basestring</code> (which both <code>str()</code> and <code>unicode()</code> are derived from) for example:</p> <pre><code>def func(files): if isinstance(files, basestring): doSomethingWithASingleFile(files) else: for f in files: doSomethingWithFile(f) </code></pre> <p>Really, I suggest simply requiring a list, even with only one file (after all, it only requires two extra characters!)</p>
14
2009-05-07T19:24:29Z
[ "python", "list", "duck-typing" ]
How can I tell if a python variable is a string or a list?
836,387
<p>I have a routine that takes a list of strings as a parameter, but I'd like to support passing in a single string and converting it to a list of one string. For example:</p> <pre><code>def func( files ): for f in files: doSomethingWithFile( f ) func( ['file1','file2','file3'] ) func( 'file1' ) # should be treated like ['file1'] </code></pre> <p>How can my function tell whether a string or a list has been passed in? I know there is a <code>type</code> function, but is there a "more pythonic" way?</p>
51
2009-05-07T18:53:26Z
837,588
<pre><code>if hasattr(f, 'lower'): print "I'm string like" </code></pre>
10
2009-05-07T23:42:28Z
[ "python", "list", "duck-typing" ]
How can I tell if a python variable is a string or a list?
836,387
<p>I have a routine that takes a list of strings as a parameter, but I'd like to support passing in a single string and converting it to a list of one string. For example:</p> <pre><code>def func( files ): for f in files: doSomethingWithFile( f ) func( ['file1','file2','file3'] ) func( 'file1' ) # should be treated like ['file1'] </code></pre> <p>How can my function tell whether a string or a list has been passed in? I know there is a <code>type</code> function, but is there a "more pythonic" way?</p>
51
2009-05-07T18:53:26Z
837,837
<p>Varargs was confusing for me, so I tested it out in Python to clear it up for myself.</p> <p>First of all the PEP for varargs is <a href="http://www.python.org/dev/peps/pep-3102/" rel="nofollow">here</a>.</p> <p>Here is sample program, based on the two answers from Dave and David Berger, followed by the output, just for clarification.</p> <pre><code>def func( *files ): print files for f in files: print( f ) if __name__ == '__main__': func( *['file1','file2','file3'] ) #Is treated like func('file1','file2','file3') func( 'onestring' ) func( 'thing1','thing2','thing3' ) func( ['stuff1','stuff2','stuff3'] ) </code></pre> <p>And the resulting output;</p> <pre><code>('file1', 'file2', 'file3') file1 file2 file3 ('onestring',) onestring ('thing1', 'thing2', 'thing3') thing1 thing2 thing3 (['stuff1', 'stuff2', 'stuff3'],) ['stuff1', 'stuff2', 'stuff3'] </code></pre> <p>Hope this is helpful to somebody else.</p>
3
2009-05-08T01:24:14Z
[ "python", "list", "duck-typing" ]
How can I tell if a python variable is a string or a list?
836,387
<p>I have a routine that takes a list of strings as a parameter, but I'd like to support passing in a single string and converting it to a list of one string. For example:</p> <pre><code>def func( files ): for f in files: doSomethingWithFile( f ) func( ['file1','file2','file3'] ) func( 'file1' ) # should be treated like ['file1'] </code></pre> <p>How can my function tell whether a string or a list has been passed in? I know there is a <code>type</code> function, but is there a "more pythonic" way?</p>
51
2009-05-07T18:53:26Z
837,986
<pre><code>def func(files): for f in files if not isinstance(files, basestring) else [files]: doSomethingWithFile(f) func(['file1', 'file2', 'file3']) func('file1') </code></pre>
9
2009-05-08T02:25:58Z
[ "python", "list", "duck-typing" ]
How can I tell if a python variable is a string or a list?
836,387
<p>I have a routine that takes a list of strings as a parameter, but I'd like to support passing in a single string and converting it to a list of one string. For example:</p> <pre><code>def func( files ): for f in files: doSomethingWithFile( f ) func( ['file1','file2','file3'] ) func( 'file1' ) # should be treated like ['file1'] </code></pre> <p>How can my function tell whether a string or a list has been passed in? I know there is a <code>type</code> function, but is there a "more pythonic" way?</p>
51
2009-05-07T18:53:26Z
11,106,461
<p>If you have more control over the caller, then one of the other answers is better. I don't have that luxury in my case so I settled on the following solution (with caveats):</p> <pre><code>def listLike(v): """Return True if v is a non-string sequence and is iterable. Note that not all objects with getitem() have the iterable attribute""" if hasattr(v, '__iter__') and not isinstance(items, basestring): return True else: #This will happen for most atomic types like numbers and strings return False </code></pre> <p>This approach will work for cases where you are dealing with a know set of list-like types that meet the above criteria. Some sequence types will be missed though.</p>
4
2012-06-19T17:46:39Z
[ "python", "list", "duck-typing" ]
How to programatically combine two aac files into one?
836,842
<p>I'm looking for a <code>cat</code> for aac music files (the stuff iTunes uses).</p> <p>Use Case: My father in law will not touch computers except for audiobooks he downloads to his iPod. I have taught him some iTunes (Windows) basics, but his library is a mess. It turns out, that iTunes is optimized for listening to podcasts and random songs from your library, not for audiobooks.</p> <p>I would like to write a script (preferably python, but comfortable with other stuff too) to import his audiobook cds in a sane fashion, combining the tracks of each cd into a bookmarkable aac file (.m4b?) and then adding that to iTunes so it shows up in the audiobooks section.</p> <p>I have figured out how to talk to iTunes (there is a COM interface in Windows, look for the iTunes SDK). Using that interface, I can use iTunes to rip the CD to aac format. It's the actual concatenation of the aac files I'm having trouble with. Can't find the right stuff on the net...</p>
3
2009-05-07T20:24:36Z
837,034
<p>I haven't seen an aac codec library for python, but you could use wav files as an intermediary format.</p> <p>You can pull the tracks off the cd as wav files, and then use the <a href="http://docs.python.org/library/wave.html" rel="nofollow">wave module</a> to concatenate them into one large file, which could then be converted by itunes to aac. This may increase your processing time considerably because of the size of the data, but it would be fairly easy, and you don't need any external libraries.</p>
0
2009-05-07T21:02:27Z
[ "python", "windows", "scripting", "itunes", "aac" ]
How to programatically combine two aac files into one?
836,842
<p>I'm looking for a <code>cat</code> for aac music files (the stuff iTunes uses).</p> <p>Use Case: My father in law will not touch computers except for audiobooks he downloads to his iPod. I have taught him some iTunes (Windows) basics, but his library is a mess. It turns out, that iTunes is optimized for listening to podcasts and random songs from your library, not for audiobooks.</p> <p>I would like to write a script (preferably python, but comfortable with other stuff too) to import his audiobook cds in a sane fashion, combining the tracks of each cd into a bookmarkable aac file (.m4b?) and then adding that to iTunes so it shows up in the audiobooks section.</p> <p>I have figured out how to talk to iTunes (there is a COM interface in Windows, look for the iTunes SDK). Using that interface, I can use iTunes to rip the CD to aac format. It's the actual concatenation of the aac files I'm having trouble with. Can't find the right stuff on the net...</p>
3
2009-05-07T20:24:36Z
837,156
<p>The most powerful Python audio manipulation module out there seems to be <a href="http://audiotools.sourceforge.net/index.html" rel="nofollow">Python Audio Tools</a>. The download comes with CLI tools that would probably do everything you'd want to do, even ripping, so you can even get by with shell scripting the whole thing. The module itself is also pretty powerful and has a handy set of functions to manipulate audio files. If you want to stick with writing everything in python, you can possibly learn enough to do what you want to do after studying their CLI source code. Specifically they have a tool that just does audio file cat in any codec. (They do depend on FAAC/FAAD2 for AAC support, but that'd be true for every library you'll find)</p>
1
2009-05-07T21:35:23Z
[ "python", "windows", "scripting", "itunes", "aac" ]
How to programatically combine two aac files into one?
836,842
<p>I'm looking for a <code>cat</code> for aac music files (the stuff iTunes uses).</p> <p>Use Case: My father in law will not touch computers except for audiobooks he downloads to his iPod. I have taught him some iTunes (Windows) basics, but his library is a mess. It turns out, that iTunes is optimized for listening to podcasts and random songs from your library, not for audiobooks.</p> <p>I would like to write a script (preferably python, but comfortable with other stuff too) to import his audiobook cds in a sane fashion, combining the tracks of each cd into a bookmarkable aac file (.m4b?) and then adding that to iTunes so it shows up in the audiobooks section.</p> <p>I have figured out how to talk to iTunes (there is a COM interface in Windows, look for the iTunes SDK). Using that interface, I can use iTunes to rip the CD to aac format. It's the actual concatenation of the aac files I'm having trouble with. Can't find the right stuff on the net...</p>
3
2009-05-07T20:24:36Z
837,172
<p>Not programming related (well, kinda.)</p> <p>iTunes already has functionality to rip as a single track (e.g. an audiobook.) Check this out: <a href="http://www.ehow.com/how_2108906_merge-cd-single-track-itunes.html" rel="nofollow">http://www.ehow.com/how_2108906_merge-cd-single-track-itunes.html</a></p> <p>That fixes your immediate problem, but I guess people can keep discussing how to do it programatically.</p>
2
2009-05-07T21:40:24Z
[ "python", "windows", "scripting", "itunes", "aac" ]
How to programatically combine two aac files into one?
836,842
<p>I'm looking for a <code>cat</code> for aac music files (the stuff iTunes uses).</p> <p>Use Case: My father in law will not touch computers except for audiobooks he downloads to his iPod. I have taught him some iTunes (Windows) basics, but his library is a mess. It turns out, that iTunes is optimized for listening to podcasts and random songs from your library, not for audiobooks.</p> <p>I would like to write a script (preferably python, but comfortable with other stuff too) to import his audiobook cds in a sane fashion, combining the tracks of each cd into a bookmarkable aac file (.m4b?) and then adding that to iTunes so it shows up in the audiobooks section.</p> <p>I have figured out how to talk to iTunes (there is a COM interface in Windows, look for the iTunes SDK). Using that interface, I can use iTunes to rip the CD to aac format. It's the actual concatenation of the aac files I'm having trouble with. Can't find the right stuff on the net...</p>
3
2009-05-07T20:24:36Z
991,742
<p>I created a freeware program called "Chapter and Verse" to concatenate m4a (AAC) files into a single m4b audiobook file with chapter marks and metadata.</p> <p>If you have already ripped the CD's to AAC using itunes (which you say you have) then the rest is easy with my software. I wrote it for this exact reason and scenario. You can download it from www.lodensoftware.com</p> <p>After trying to work with SlideShow Assembler, the QT SDK and a bunch of other command line tools, I ended up building my own application based on the publicly available MP4v2 library. The concatenating of files and adding of chapters is done using the MP4v2 library.</p> <p>There are quite a few nuances in building an audiobook properly formatted for the iPod. The information is hard to find. Working with Apple documentation and open libraries has its own challenges as well.</p> <p>Best of Luck.</p>
4
2009-06-13T23:14:02Z
[ "python", "windows", "scripting", "itunes", "aac" ]
datastore transaction restrictions
836,992
<p>in my google app application, whenever a user purchases a number of contracts, these events are executed (simplified for clarity):</p> <ul> <li>user.cash is decreased</li> <li>user.contracts is increased by the number</li> <li>contracts.current_price is updated.</li> <li>market.no_of_transactions is increased by 1.</li> </ul> <p>in a rdms, these would be placed within the same transaction. I conceive that google datastore does not allow entities of more than one model to be in the same transaction.</p> <p>what is the correct approach to this issue? how can I ensure that if a write fails, all preceding writes are rolled back? </p> <p>edit: I have obviously missed entity groups. Now I'd appreciate some further information regarding how they are used. Another point to clarify is google says "Only use entity groups when they are needed for transactions. For other relationships between entities, use ReferenceProperty properties and Key values, which can be used in queries". does it mean I have to define both a reference property (since I need queriying them) and a parent-child relationship (for transactions)? </p> <p>edit 2: and finally, how do I define two parents for an entity if the entity is being created to establish an n-to-n relationship between 2 parents?</p>
3
2009-05-07T20:55:48Z
838,960
<p>After a through research, I have found that a distributed transaction layer that provides a solution to the single entity group restriction has been developed in userland with the help of some google people. But so far, it is not released and is only available in java.</p>
0
2009-05-08T09:15:20Z
[ "python", "google-app-engine", "transactions", "gae-datastore", "gae-ds-transactions" ]
datastore transaction restrictions
836,992
<p>in my google app application, whenever a user purchases a number of contracts, these events are executed (simplified for clarity):</p> <ul> <li>user.cash is decreased</li> <li>user.contracts is increased by the number</li> <li>contracts.current_price is updated.</li> <li>market.no_of_transactions is increased by 1.</li> </ul> <p>in a rdms, these would be placed within the same transaction. I conceive that google datastore does not allow entities of more than one model to be in the same transaction.</p> <p>what is the correct approach to this issue? how can I ensure that if a write fails, all preceding writes are rolled back? </p> <p>edit: I have obviously missed entity groups. Now I'd appreciate some further information regarding how they are used. Another point to clarify is google says "Only use entity groups when they are needed for transactions. For other relationships between entities, use ReferenceProperty properties and Key values, which can be used in queries". does it mean I have to define both a reference property (since I need queriying them) and a parent-child relationship (for transactions)? </p> <p>edit 2: and finally, how do I define two parents for an entity if the entity is being created to establish an n-to-n relationship between 2 parents?</p>
3
2009-05-07T20:55:48Z
2,127,490
<p>Let me add a quote from the <a href="http://code.google.com/intl/de/appengine/docs/python/datastore/keysandentitygroups.html" rel="nofollow">Datastore documentation</a>:</p> <blockquote> <p>A good rule of thumb for entity groups is that they should be about the size of a single user's worth of data or smaller.</p> </blockquote> <p>You could create a pseudo root entity and put everything below this. Then, you execute everything in a transaction.</p>
0
2010-01-24T15:15:31Z
[ "python", "google-app-engine", "transactions", "gae-datastore", "gae-ds-transactions" ]
datastore transaction restrictions
836,992
<p>in my google app application, whenever a user purchases a number of contracts, these events are executed (simplified for clarity):</p> <ul> <li>user.cash is decreased</li> <li>user.contracts is increased by the number</li> <li>contracts.current_price is updated.</li> <li>market.no_of_transactions is increased by 1.</li> </ul> <p>in a rdms, these would be placed within the same transaction. I conceive that google datastore does not allow entities of more than one model to be in the same transaction.</p> <p>what is the correct approach to this issue? how can I ensure that if a write fails, all preceding writes are rolled back? </p> <p>edit: I have obviously missed entity groups. Now I'd appreciate some further information regarding how they are used. Another point to clarify is google says "Only use entity groups when they are needed for transactions. For other relationships between entities, use ReferenceProperty properties and Key values, which can be used in queries". does it mean I have to define both a reference property (since I need queriying them) and a parent-child relationship (for transactions)? </p> <p>edit 2: and finally, how do I define two parents for an entity if the entity is being created to establish an n-to-n relationship between 2 parents?</p>
3
2009-05-07T20:55:48Z
4,798,839
<p>shanyu, you mentioned the distributed transaction layer that lets you operate across arbitrarily many entity groups in a single transaction. it actually <a href="http://code.google.com/p/tapioca-orm/" rel="nofollow">has been released</a>, it just hasn't been advertised very loudly. it was designed and written by daniel wilkerson and erick armbrust, with some consulting on my part. dan describes it in <a href="http://www.google.com/events/io/2009/sessions" rel="nofollow">this talk</a>.</p> <p>nick johnson has also described <a href="http://blog.notdot.net/2009/9/Distributed-Transactions-on-App-Engine" rel="nofollow">how to do "transfer" type operations across entity groups</a>, similar to what you describe. it's not as general purpose as tapioca-orm, but it's simpler and lighter weight.</p> <p>there's a related built in feature, <a href="http://code.google.com/appengine/docs/python/taskqueue/overview.html#Tasks_Within_Transactions" rel="nofollow">transactional tasks</a>, that lets you add a task to a queue within a datastore transaction, such that it will only be added if the transaction commits successfully. that task can then do more datastore operations, including a transaction on a different entity group. it's not as strong as dan and erick's solution, but it does give you guaranteed eventual consistency across entity groups, which is good enough for many use cases, without the extra overhead.</p> <p>in response to your questions: 1) you're not required to use both reference properties and parent/child relationships (ie entity groups). that guideline just means that entity groups limit datastore write throughput, since writes are serialized per entity group. you should be aware of that if you're considering structuring your data into entity groups just for ancestor queries.</p> <p>2) an entity can't have more than one parent. if you want to model a many-to-many relationship, you should generally use a ListProperty of reference properties (ie keys). see <a href="http://code.google.com/appengine/articles/modeling.html" rel="nofollow">this article</a> and <a href="http://www.google.com/events/io/2009/sessions/BuildingScalableComplexApps.html" rel="nofollow">this talk</a> for details.</p>
0
2011-01-25T21:08:12Z
[ "python", "google-app-engine", "transactions", "gae-datastore", "gae-ds-transactions" ]
Form Submission in Python Without Name Attribute
837,195
<p>Background:</p> <p>Using urllib and urllib2 in Python, you can do a form submission. </p> <p>You first create a dictionary.</p> <pre><code>formdictionary = { 'search' : 'stackoverflow' } </code></pre> <p>Then you use urlencode method of urllib to transform this dictionary.</p> <pre><code>params = urllib.urlencode(formdictionary) </code></pre> <p>You can now make a url request with urllib2 and pass the variable params as a secondary parameter with the first parameter being the url.</p> <pre><code>open = urllib2.urlopen('www.searchpage.com', params) </code></pre> <p>From my understanding, urlencode automatically encodes the dictionary in html and adds the input tag. It takes the key to be the name attribute. It takes value in the dictionary to be the value of the name attribute. Urllib2 send this html code via an HTTP POST request.</p> <p>Problem:</p> <p>This is alright if the html code you are submitting to is formatted in a standard way with the html tag input having the name attribute.</p> <pre><code>&lt;input id="32324" type="text" name="search" &gt; </code></pre> <p>But, there is the situation where the html code is not properly formatted. And the html input tag only has an id attribute no name attribute. Is there may be another way to access the input tag via the id attribute? Or is there may be yet another way?</p> <p>Solution:</p> <p>?</p>
2
2009-05-07T21:44:49Z
837,283
<p>According to <a href="http://www.w3.org/TR/html401/interact/forms.html#successful-controls" rel="nofollow">the W3 standard</a>, for an input field to be submitted, it must have a name attribute. A quick test on Firefox 3 and Safari 3.2 shows that an input field that is missing the name attribute but has an id attribute is not submitted.</p> <p>With that said, if you have a form that you want to submit, and some of its fields have id but not name attributes, using the id attribute instead seems like the only available option. It could be that other browsers use the id attribute, or perhaps there is some JavaScript code that handles the submission event instead of letting the browser do it.</p>
2
2009-05-07T22:05:09Z
[ "python", "forms", "urllib2", "urllib" ]
Form Submission in Python Without Name Attribute
837,195
<p>Background:</p> <p>Using urllib and urllib2 in Python, you can do a form submission. </p> <p>You first create a dictionary.</p> <pre><code>formdictionary = { 'search' : 'stackoverflow' } </code></pre> <p>Then you use urlencode method of urllib to transform this dictionary.</p> <pre><code>params = urllib.urlencode(formdictionary) </code></pre> <p>You can now make a url request with urllib2 and pass the variable params as a secondary parameter with the first parameter being the url.</p> <pre><code>open = urllib2.urlopen('www.searchpage.com', params) </code></pre> <p>From my understanding, urlencode automatically encodes the dictionary in html and adds the input tag. It takes the key to be the name attribute. It takes value in the dictionary to be the value of the name attribute. Urllib2 send this html code via an HTTP POST request.</p> <p>Problem:</p> <p>This is alright if the html code you are submitting to is formatted in a standard way with the html tag input having the name attribute.</p> <pre><code>&lt;input id="32324" type="text" name="search" &gt; </code></pre> <p>But, there is the situation where the html code is not properly formatted. And the html input tag only has an id attribute no name attribute. Is there may be another way to access the input tag via the id attribute? Or is there may be yet another way?</p> <p>Solution:</p> <p>?</p>
2
2009-05-07T21:44:49Z
837,322
<p>An input tag without a name won't be submitted as a form parameter.</p> <p>For example, create an HTML page containing just this:</p> <pre><code>&lt;form&gt; &lt;input type="text" name="one" value="foo"/&gt; &lt;input type="text" value="bar"/&gt; &lt;input type="submit"/&gt; &lt;/form&gt; </code></pre> <p>You can see that the second text field is missing a <code>name</code> attribute. If you click "Submit," the page will refresh with the query string:</p> <pre><code>test.html?one=foo </code></pre> <p><hr /></p> <p>A good strategy for this would be to look at a live POST request sent by your browser and start by emulating that. Use a tool like the FireBug extension for Firefox to see the POST request and parameters sent by your browser. There might be parameters in there that you didn't notice before -- possibly because they were hidden form elements or they were created/set by JavaScript.</p>
0
2009-05-07T22:11:59Z
[ "python", "forms", "urllib2", "urllib" ]
How do I invoke Python code from Ruby?
837,256
<p>Does a easy to use Ruby to Python bridge exist? Or am I better off using system()? </p>
5
2009-05-07T21:59:01Z
837,296
<p>I don't think there's any way to invoke Python from Ruby without forking a process, via system() or something. The language run times are utterly diferent, they'd need to be in separate processes anyway.</p>
2
2009-05-07T22:08:15Z
[ "python", "ruby" ]
How do I invoke Python code from Ruby?
837,256
<p>Does a easy to use Ruby to Python bridge exist? Or am I better off using system()? </p>
5
2009-05-07T21:59:01Z
837,325
<p>You could try <a href="http://www.goto.info.waseda.ac.jp/~fukusima/ruby/python-e.html">Masaki Fukushima's library</a> for embedding python in ruby, although it doesn't appear to be maintained. YMMV</p> <blockquote> <p>With this library, Ruby scripts can directly call arbitrary Python modules. Both extension modules and modules written in Python can be used. </p> </blockquote> <p>The amusingly named <a href="http://github.com/why/unholy/tree/master">Unholy</a> from the ingenious Why the Lucky Stiff might also be of use:</p> <blockquote> <p>Compile Ruby to Python bytecode.<br /> And, in addition, translate that<br /> bytecode back to Python source code using Decompyle (included.)</p> <p>Requires Ruby 1.9 and Python 2.5.</p> </blockquote>
6
2009-05-07T22:12:39Z
[ "python", "ruby" ]
How do I invoke Python code from Ruby?
837,256
<p>Does a easy to use Ruby to Python bridge exist? Or am I better off using system()? </p>
5
2009-05-07T21:59:01Z
837,862
<p>For python code to run the interpreter needs to be launched as a process. So system() is your best option.</p> <p>For calling the python code you could use RPC or network sockets, got for the simplest thing which could possibly work.</p>
-1
2009-05-08T01:35:03Z
[ "python", "ruby" ]
How do I invoke Python code from Ruby?
837,256
<p>Does a easy to use Ruby to Python bridge exist? Or am I better off using system()? </p>
5
2009-05-07T21:59:01Z
5,331,067
<p>gem install rubypython</p> <p><a href="http://rubypython.rubyforge.org/">rubypython home page</a></p>
5
2011-03-16T20:00:02Z
[ "python", "ruby" ]
How do I invoke Python code from Ruby?
837,256
<p>Does a easy to use Ruby to Python bridge exist? Or am I better off using system()? </p>
5
2009-05-07T21:59:01Z
14,096,628
<p>If you want to use Python code like your Python script is a function, try IO.popen .</p> <p>If you wanted to reverse each string in an array using the python script "reverse.py", your ruby code would be as follows.</p> <pre><code>strings = ["hello", "my", "name", "is", "jimmy"] #IO.popen: 1st arg is exactly what you would type into the command line to execute your python script. #(You can do this for non-python scripts as well.) pythonPortal = IO.popen("python reverse.py", "w+") pythonPortal.puts strings #anything you puts will be available to your python script from stdin pythonPortal.close_write reversed = [] temp = pythonPortal.gets #everything your python script writes to stdout (usually using 'print') will be available using gets while temp!= nil reversed&lt;&lt;temp temp = pythonPortal.gets end puts reversed </code></pre> <p>Then your python script would look something like this</p> <pre><code>import sys def reverse(str): return str[::-1] temp = sys.stdin.readlines() #Everything your ruby programs "puts" is available to python through stdin for item in temp: print reverse(item[:-1]) #Everything your python script "prints" to stdout is available to the ruby script through .gets #[:-1] to not include the newline at the end, puts "hello" passes "hello\n" to the python script </code></pre> <p>Output: olleh ym eman si ymmij</p>
1
2012-12-31T01:52:50Z
[ "python", "ruby" ]
Find the oldest file (recursively) in a directory
837,606
<p>I'm writing a Python backup script and I need to find the oldest file in a directory (and its sub-directories). I also need to filter it down to *.avi files only.</p> <p>The script will always be running on a Linux machine. Is there some way to do it in Python or would running some shell commands be better?</p> <p>At the moment I'm running <code>df</code> to get the free space on a particular partition, and if there is less than 5 gigabytes free, I want to start deleting the oldest <code>*.avi</code> files until that condition is met.</p>
8
2009-05-07T23:50:50Z
837,609
<p>Check out the linux command <a href="http://content.hccfl.edu/pollock/Unix/FindCmd.htm" rel="nofollow"><code>find</code></a>.</p> <p>Alternatively, <a href="http://www.linuxforums.org/forum/debian-linux-help/70289-remove-oldest-file-directory.html" rel="nofollow">this post</a> pipes together ls and tail to delete the oldest file in a directory. That could be done in a loop while there isn't enough free space.</p> <p>For reference, here's the shell code that does it (follow the link for more alternatives and a discussion): </p> <pre><code>ls -t -r -1 /path/to/files | head --lines 1 | xargs rm </code></pre>
2
2009-05-07T23:53:02Z
[ "python", "linux", "file-io" ]
Find the oldest file (recursively) in a directory
837,606
<p>I'm writing a Python backup script and I need to find the oldest file in a directory (and its sub-directories). I also need to filter it down to *.avi files only.</p> <p>The script will always be running on a Linux machine. Is there some way to do it in Python or would running some shell commands be better?</p> <p>At the moment I'm running <code>df</code> to get the free space on a particular partition, and if there is less than 5 gigabytes free, I want to start deleting the oldest <code>*.avi</code> files until that condition is met.</p>
8
2009-05-07T23:50:50Z
837,629
<p>To do it in Python, you can use <a href="http://docs.python.org/library/os.html"><code>os.walk(path)</code></a> to iterate recursively over the files, and the <code>st_size</code> and <code>st_mtime</code> attributes of <a href="http://docs.python.org/library/os.html"><code>os.stat(filename)</code></a> to get the file sizes and modification times.</p>
12
2009-05-08T00:00:52Z
[ "python", "linux", "file-io" ]
Find the oldest file (recursively) in a directory
837,606
<p>I'm writing a Python backup script and I need to find the oldest file in a directory (and its sub-directories). I also need to filter it down to *.avi files only.</p> <p>The script will always be running on a Linux machine. Is there some way to do it in Python or would running some shell commands be better?</p> <p>At the moment I'm running <code>df</code> to get the free space on a particular partition, and if there is less than 5 gigabytes free, I want to start deleting the oldest <code>*.avi</code> files until that condition is met.</p>
8
2009-05-07T23:50:50Z
837,631
<p>You can use <a href="http://docs.python.org/library/stat.html#module-stat">stat</a> and <a href="http://docs.python.org/library/fnmatch.html#module-fnmatch">fnmatch</a> modules together to find the files</p> <p>ST_MTIME refere to the last modification time. You can choose another value if you want</p> <pre><code>import os, stat, fnmatch file_list = [] for filename in os.listdir('.'): if fnmatch.fnmatch(filename, '*.avi'): file_list.append((os.stat(filename)[stat.ST_MTIME], filename)) </code></pre> <p>Then you can order the list by time and delete according to it.</p> <pre><code>file_list.sort(key=lambda a: a[0]) </code></pre>
10
2009-05-08T00:01:00Z
[ "python", "linux", "file-io" ]
Find the oldest file (recursively) in a directory
837,606
<p>I'm writing a Python backup script and I need to find the oldest file in a directory (and its sub-directories). I also need to filter it down to *.avi files only.</p> <p>The script will always be running on a Linux machine. Is there some way to do it in Python or would running some shell commands be better?</p> <p>At the moment I'm running <code>df</code> to get the free space on a particular partition, and if there is less than 5 gigabytes free, I want to start deleting the oldest <code>*.avi</code> files until that condition is met.</p>
8
2009-05-07T23:50:50Z
837,637
<p>The <a href="http://docs.python.org/library/os.html#files-and-directories" rel="nofollow">os module</a> provides the functions that you need to get directory listings and file info in Python. I've found <a href="http://docs.python.org/library/os.html?highlight=walk#os.walk" rel="nofollow">os.walk</a> to be especially useful for walking directories recursively, and os.stat will give you detailed info (including modification time) on each entry.</p> <p>You may be able to do this easier with a simple shell command. Whether that works better for you or not depends on what you want to do with the results.</p>
0
2009-05-08T00:02:53Z
[ "python", "linux", "file-io" ]
Find the oldest file (recursively) in a directory
837,606
<p>I'm writing a Python backup script and I need to find the oldest file in a directory (and its sub-directories). I also need to filter it down to *.avi files only.</p> <p>The script will always be running on a Linux machine. Is there some way to do it in Python or would running some shell commands be better?</p> <p>At the moment I'm running <code>df</code> to get the free space on a particular partition, and if there is less than 5 gigabytes free, I want to start deleting the oldest <code>*.avi</code> files until that condition is met.</p>
8
2009-05-07T23:50:50Z
837,641
<p>I think the easiest way to do this would be to use find along with ls -t (sort files by time).</p> <p>something along these lines should do the trick (deletes oldest avi file under specified directory)</p> <pre><code>find / -name "*.avi" | xargs ls -t | tail -n 1 | xargs rm </code></pre> <p>step by step....</p> <p><strong>find / -name "*.avi"</strong> - find all avi files recursively starting at the root directory</p> <p><strong>xargs ls -t</strong> - sort all files found by modification time, from newest to oldest.</p> <p><strong>tail -n 1</strong> - grab the last file in the list (oldest)</p> <p><strong>xargs rm</strong> - and remove it</p>
7
2009-05-08T00:04:04Z
[ "python", "linux", "file-io" ]
Find the oldest file (recursively) in a directory
837,606
<p>I'm writing a Python backup script and I need to find the oldest file in a directory (and its sub-directories). I also need to filter it down to *.avi files only.</p> <p>The script will always be running on a Linux machine. Is there some way to do it in Python or would running some shell commands be better?</p> <p>At the moment I'm running <code>df</code> to get the free space on a particular partition, and if there is less than 5 gigabytes free, I want to start deleting the oldest <code>*.avi</code> files until that condition is met.</p>
8
2009-05-07T23:50:50Z
837,840
<p>Hm. Nadia's answer is closer to what you <em>meant</em> to ask; however, for finding the (single) oldest file in a tree, try this:</p> <pre><code>import os def oldest_file_in_tree(rootfolder, extension=".avi"): return min( (os.path.join(dirname, filename) for dirname, dirnames, filenames in os.walk(rootfolder) for filename in filenames if filename.endswith(extension)), key=lambda fn: os.stat(fn).st_mtime) </code></pre> <p>With a little modification, you can get the <code>n</code> oldest files (similar to Nadia's answer):</p> <pre><code>import os, heapq def oldest_files_in_tree(rootfolder, count=1, extension=".avi"): return heapq.nsmallest(count, (os.path.join(dirname, filename) for dirname, dirnames, filenames in os.walk(rootfolder) for filename in filenames if filename.endswith(extension)), key=lambda fn: os.stat(fn).st_mtime) </code></pre> <p>Note that using the <code>.endswith</code> method allows calls as:</p> <pre><code>oldest_files_in_tree("/home/user", 20, (".avi", ".mov")) </code></pre> <p>to select more than one extension.</p> <p>Finally, should you want the complete list of files, ordered by modification time, in order to delete as many as required to free space, here's some code:</p> <pre><code>import os def files_to_delete(rootfolder, extension=".avi"): return sorted( (os.path.join(dirname, filename) for dirname, dirnames, filenames in os.walk(rootfolder) for filename in filenames if filename.endswith(extension)), key=lambda fn: os.stat(fn).st_mtime), reverse=True) </code></pre> <p>and note that the <code>reverse=True</code> brings the oldest files at the end of the list, so that for the next file to delete, you just do a <code>file_list.pop()</code>.</p> <p>By the way, for a complete solution to your issue, since you are running on Linux, where the <code>os.statvfs</code> is available, you can do:</p> <pre><code>import os def free_space_up_to(free_bytes_required, rootfolder, extension=".avi"): file_list= files_to_delete(rootfolder, extension) while file_list: statv= os.statvfs(rootfolder) if statv.f_bfree*statv.f_bsize &gt;= free_bytes_required: break os.remove(file_list.pop()) </code></pre> <p><code>statvfs.f_bfree</code> are the device free blocks and <code>statvfs.f_bsize</code> is the block size. We take the <code>rootfolder</code> statvfs, so mind any symbolic links pointing to other devices, where we could delete many files without actually freeing up space in this device.</p> <p>UPDATE (copying a comment by Juan):</p> <p>Depending on the OS and filesystem implementation, you may want to multiply f_bfree by f_frsize rather than f_bsize. In some implementations, the latter is the preferred I/O request size. For example, on a FreeBSD 9 system I just tested, f_frsize was 4096 and f_bsize was 16384. POSIX says the block count fields are "in units of f_frsize" ( see <a href="http://pubs.opengroup.org/onlinepubs/9699919799//basedefs/sys_statvfs.h.html" rel="nofollow">http://pubs.opengroup.org/onlinepubs/9699919799//basedefs/sys_statvfs.h.html</a> )</p>
19
2009-05-08T01:24:55Z
[ "python", "linux", "file-io" ]
Find the oldest file (recursively) in a directory
837,606
<p>I'm writing a Python backup script and I need to find the oldest file in a directory (and its sub-directories). I also need to filter it down to *.avi files only.</p> <p>The script will always be running on a Linux machine. Is there some way to do it in Python or would running some shell commands be better?</p> <p>At the moment I'm running <code>df</code> to get the free space on a particular partition, and if there is less than 5 gigabytes free, I want to start deleting the oldest <code>*.avi</code> files until that condition is met.</p>
8
2009-05-07T23:50:50Z
838,037
<p>Here's another Python formulation, which a bit old-school compared to some others, but is easy to modify, and handles the case of no matching files without raising an exception.</p> <pre><code>import os def find_oldest_file(dirname="..", extension=".avi"): oldest_file, oldest_time = None, None for dirpath, dirs, files in os.walk(dirname): for filename in files: file_path = os.path.join(dirpath, filename) file_time = os.stat(file_path).st_mtime if file_path.endswith(extension) and (file_time&lt;oldest_time or oldest_time is None): oldest_file, oldest_time = file_path, file_time return oldest_file, oldest_time print find_oldest_file() </code></pre>
2
2009-05-08T02:56:00Z
[ "python", "linux", "file-io" ]
How do I create a slug in Django?
837,828
<p>I am trying to create a SlugField in Django.</p> <p>I created this simple model:</p> <pre><code>from django.db import models class Test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() </code></pre> <p>I then do this:</p> <pre><code>&gt;&gt;&gt; from mysite.books.models import Test &gt;&gt;&gt; t=Test(q="aa a a a", s="b b b b") &gt;&gt;&gt; t.s 'b b b b' &gt;&gt;&gt; t.save() &gt;&gt;&gt; t.s 'b b b b' &gt;&gt;&gt; </code></pre> <p>I was expecting b-b-b-b</p>
156
2009-05-08T01:17:11Z
837,835
<p>You will need to use the slugify function. </p> <pre><code>&gt;&gt;&gt; from django.template.defaultfilters import slugify &gt;&gt;&gt; slugify("b b b b") u'b-b-b-b' &gt;&gt;&gt; </code></pre> <p>You can call <code>slugify</code> automatically by overriding the <code>save</code> method:</p> <pre><code>class test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() def save(self, *args, **kwargs): self.s = slugify(self.q) super(test, self).save(*args, **kwargs) </code></pre> <p>Be aware that the above will cause your URL to change when the <code>q</code> field is edited, which <a href="http://www.w3.org/Provider/Style/URI.html">can cause broken links</a>. It may be preferable to generate the slug only once when you create a new object:</p> <pre><code>class test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() def save(self, *args, **kwargs): if not self.id: # Newly created object, so set slug self.s = slugify(self.q) super(test, self).save(*args, **kwargs) </code></pre>
314
2009-05-08T01:22:34Z
[ "python", "django", "slug" ]
How do I create a slug in Django?
837,828
<p>I am trying to create a SlugField in Django.</p> <p>I created this simple model:</p> <pre><code>from django.db import models class Test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() </code></pre> <p>I then do this:</p> <pre><code>&gt;&gt;&gt; from mysite.books.models import Test &gt;&gt;&gt; t=Test(q="aa a a a", s="b b b b") &gt;&gt;&gt; t.s 'b b b b' &gt;&gt;&gt; t.save() &gt;&gt;&gt; t.s 'b b b b' &gt;&gt;&gt; </code></pre> <p>I was expecting b-b-b-b</p>
156
2009-05-08T01:17:11Z
842,865
<p>If you're using the admin interface to add new items of your model, you can set up a <code>ModelAdmin</code> in your <code>admin.py</code> and utilize <a href="https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.prepopulated_fields"><code>prepopulated_fields</code></a> to automate entering of a slug:</p> <pre><code>class ClientAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('name',)} admin.site.register(Client, ClientAdmin) </code></pre> <p>Here, when the user enters a value in the admin form for the <code>name</code> field, the <code>slug</code> will be automatically populated with the correct slugified <code>name</code>. </p>
26
2009-05-09T07:26:29Z
[ "python", "django", "slug" ]
How do I create a slug in Django?
837,828
<p>I am trying to create a SlugField in Django.</p> <p>I created this simple model:</p> <pre><code>from django.db import models class Test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() </code></pre> <p>I then do this:</p> <pre><code>&gt;&gt;&gt; from mysite.books.models import Test &gt;&gt;&gt; t=Test(q="aa a a a", s="b b b b") &gt;&gt;&gt; t.s 'b b b b' &gt;&gt;&gt; t.save() &gt;&gt;&gt; t.s 'b b b b' &gt;&gt;&gt; </code></pre> <p>I was expecting b-b-b-b</p>
156
2009-05-08T01:17:11Z
843,067
<p>In most cases the slug should not change, so you really only want to calculate it on first save:</p> <pre><code>class Test(models.Model): q = models.CharField(max_length=30) s = models.SlugField(editable=False) # hide from admin def save(self): if not self.id: self.s = slugify(self.q) super(Test, self).save() </code></pre>
20
2009-05-09T10:10:12Z
[ "python", "django", "slug" ]
How do I create a slug in Django?
837,828
<p>I am trying to create a SlugField in Django.</p> <p>I created this simple model:</p> <pre><code>from django.db import models class Test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() </code></pre> <p>I then do this:</p> <pre><code>&gt;&gt;&gt; from mysite.books.models import Test &gt;&gt;&gt; t=Test(q="aa a a a", s="b b b b") &gt;&gt;&gt; t.s 'b b b b' &gt;&gt;&gt; t.save() &gt;&gt;&gt; t.s 'b b b b' &gt;&gt;&gt; </code></pre> <p>I was expecting b-b-b-b</p>
156
2009-05-08T01:17:11Z
1,480,440
<p>A small correction to Thepeer's answer: To override <code>save()</code> function in model classes, better add arguments to it:</p> <pre><code>from django.utils.text import slugify def save(self, *args, **kwargs): if not self.id: self.s = slugify(self.q) super(test, self).save(*args, **kwargs) </code></pre> <p>Otherwise, <code>test.objects.create(q="blah blah blah")</code> will result in a <code>force_insert</code> error (unexpected argument).</p>
49
2009-09-26T04:36:35Z
[ "python", "django", "slug" ]
How do I create a slug in Django?
837,828
<p>I am trying to create a SlugField in Django.</p> <p>I created this simple model:</p> <pre><code>from django.db import models class Test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() </code></pre> <p>I then do this:</p> <pre><code>&gt;&gt;&gt; from mysite.books.models import Test &gt;&gt;&gt; t=Test(q="aa a a a", s="b b b b") &gt;&gt;&gt; t.s 'b b b b' &gt;&gt;&gt; t.save() &gt;&gt;&gt; t.s 'b b b b' &gt;&gt;&gt; </code></pre> <p>I was expecting b-b-b-b</p>
156
2009-05-08T01:17:11Z
4,440,730
<p>If you don't want to set the slugfield to Not be editable, then I believe you'll want to set the Null and Blank properties to False. Otherwise you'll get an error when trying to save in Admin.</p> <p>So a modification to the above example would be::</p> <pre><code>class test(models.Model): q = models.CharField(max_length=30) s = models.SlugField(null=True, blank=True) # Allow blank submission in admin. def save(self): if not self.id: self.s = slugify(self.q) super(test, self).save() </code></pre>
6
2010-12-14T15:26:49Z
[ "python", "django", "slug" ]
How do I create a slug in Django?
837,828
<p>I am trying to create a SlugField in Django.</p> <p>I created this simple model:</p> <pre><code>from django.db import models class Test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() </code></pre> <p>I then do this:</p> <pre><code>&gt;&gt;&gt; from mysite.books.models import Test &gt;&gt;&gt; t=Test(q="aa a a a", s="b b b b") &gt;&gt;&gt; t.s 'b b b b' &gt;&gt;&gt; t.save() &gt;&gt;&gt; t.s 'b b b b' &gt;&gt;&gt; </code></pre> <p>I was expecting b-b-b-b</p>
156
2009-05-08T01:17:11Z
4,895,850
<p>Use prepopulated_fields in your admin class:</p> <pre><code>class ArticleAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("title",)} admin.site.register(Article, ArticleAdmin) </code></pre> <p><a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.prepopulated_fields" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.prepopulated_fields</a></p>
4
2011-02-04T08:14:47Z
[ "python", "django", "slug" ]
How do I create a slug in Django?
837,828
<p>I am trying to create a SlugField in Django.</p> <p>I created this simple model:</p> <pre><code>from django.db import models class Test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() </code></pre> <p>I then do this:</p> <pre><code>&gt;&gt;&gt; from mysite.books.models import Test &gt;&gt;&gt; t=Test(q="aa a a a", s="b b b b") &gt;&gt;&gt; t.s 'b b b b' &gt;&gt;&gt; t.save() &gt;&gt;&gt; t.s 'b b b b' &gt;&gt;&gt; </code></pre> <p>I was expecting b-b-b-b</p>
156
2009-05-08T01:17:11Z
12,212,162
<p>There is corner case with some utf-8 characters</p> <p>Example:</p> <pre><code>&gt;&gt;&gt; from django.template.defaultfilters import slugify &gt;&gt;&gt; slugify(u"test ąęśćółń") u'test-aescon' # there is no "l" </code></pre> <p>This can be solved with <a href="http://pypi.python.org/pypi/Unidecode/0.04.9">Unidecode</a></p> <pre><code>&gt;&gt;&gt; from unidecode import unidecode &gt;&gt;&gt; from django.template.defaultfilters import slugify &gt;&gt;&gt; slugify(unidecode(u"test ąęśćółń")) u'test-aescoln' </code></pre>
87
2012-08-31T09:05:21Z
[ "python", "django", "slug" ]
How do I create a slug in Django?
837,828
<p>I am trying to create a SlugField in Django.</p> <p>I created this simple model:</p> <pre><code>from django.db import models class Test(models.Model): q = models.CharField(max_length=30) s = models.SlugField() </code></pre> <p>I then do this:</p> <pre><code>&gt;&gt;&gt; from mysite.books.models import Test &gt;&gt;&gt; t=Test(q="aa a a a", s="b b b b") &gt;&gt;&gt; t.s 'b b b b' &gt;&gt;&gt; t.save() &gt;&gt;&gt; t.s 'b b b b' &gt;&gt;&gt; </code></pre> <p>I was expecting b-b-b-b</p>
156
2009-05-08T01:17:11Z
28,526,821
<p>I'm using Django 1.7</p> <p>Create a SlugField in your model like this:</p> <pre><code>slug = models.SlugField() </code></pre> <p>Then in <code>admin.py</code> define <code>prepopulated_fields</code>;</p> <pre><code>class ArticleAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("title",)} </code></pre>
2
2015-02-15T13:58:37Z
[ "python", "django", "slug" ]
Working with subdomain in google app engine
838,078
<p>How can I work with sub domain in google app engine (python).</p> <p>I wanna get first domain part and take some action (handler).</p> <p><b>Example:</b><br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;product.example.com -> send it to products handler<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;user.example.com -> send it to users handler</p> <p>Actually, using virtual path I have this code:</p> <pre><code> application = webapp.WSGIApplication( [('/', IndexHandler), ('/product/(.*)', ProductHandler), ('/user/(.*)', UserHandler) ] </code></pre> <p>Did I make my self clear? <em>(sorry poor english)</em></p>
19
2009-05-08T03:15:08Z
838,726
<p>WSGIApplication isn't capable of routing based on domain. Instead, you need to create a separate application for each subdomain, like this:</p> <pre><code>applications = { 'product.example.com': webapp.WSGIApplication([ ('/', IndexHandler), ('/(.*)', ProductHandler)]), 'user.example.com': webapp.WSGIApplication([ ('/', IndexHandler), ('/(.*)', UserHandler)]), } def main(): run_wsgi_app(applications[os.environ['HTTP_HOST']]) if __name__ == '__main__': main() </code></pre> <p>Alternately, you could write your own WSGIApplication subclass that knows how to handle multiple hosts.</p>
26
2009-05-08T08:05:53Z
[ "python", "google-app-engine", "subdomain" ]
Working with subdomain in google app engine
838,078
<p>How can I work with sub domain in google app engine (python).</p> <p>I wanna get first domain part and take some action (handler).</p> <p><b>Example:</b><br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;product.example.com -> send it to products handler<br /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;user.example.com -> send it to users handler</p> <p>Actually, using virtual path I have this code:</p> <pre><code> application = webapp.WSGIApplication( [('/', IndexHandler), ('/product/(.*)', ProductHandler), ('/user/(.*)', UserHandler) ] </code></pre> <p>Did I make my self clear? <em>(sorry poor english)</em></p>
19
2009-05-08T03:15:08Z
4,316,588
<p>I liked the idea from Nick but I had a slightly different issue. I wanted to match one specific subdomain to handle it a bit different, but all other sub domains should be handled the same. So here is my example.</p> <pre><code>import os def main(): if (os.environ['HTTP_HOST'] == "sub.example.com"): application = webapp.WSGIApplication([('/(.*)', OtherMainHandler)], debug=True) else: application = webapp.WSGIApplication([('/', MainHandler),], debug=True) run_wsgi_app(application) if __name__ == '__main__': main() </code></pre>
2
2010-11-30T17:28:58Z
[ "python", "google-app-engine", "subdomain" ]
Python dictionary deepcopy
838,642
<p>I was wondering in how does exactly deepcopy work in the following context:</p> <pre><code>from copy import deepcopy def copyExample: self.myDict = {} firstPosition = "First" firstPositionContent = ["first", "primero"] secondPosition = "Second" secondPositionContent = ["second"] self.myDict[firstPosition] = firstPositionContent self.myDict[secondPosition] = secondPositionContent return deepcopy(self.myDict) def addExample(self): copy = self.copyExample() copy["Second"].add("segundo") </code></pre> <p>Does it return the reference to the lists I have in the dictionary? Or does it work as I expect and copy every list in a new list with a different reference?</p> <p>I know what a deep copy is (so there is no need to explain the difference between deep and shallow) but I am wondering if it works as I expect it to do and therefore do not change the instance variable when I use <code>addExample()</code>.</p>
19
2009-05-08T07:38:49Z
838,673
<p>The <a href="http://docs.python.org/library/copy.html">documentation</a> makes it pretty clear that you're getting new copies, not references. Deepcopy creates deep copies for built in types, with various exceptions and that you can add custom copy operations to your user-defined objects to get deep copy support for them as well. If you're not sure, well that's what unit testing is for.</p>
14
2009-05-08T07:49:17Z
[ "python", "dictionary", "deep-copy" ]
Python dictionary deepcopy
838,642
<p>I was wondering in how does exactly deepcopy work in the following context:</p> <pre><code>from copy import deepcopy def copyExample: self.myDict = {} firstPosition = "First" firstPositionContent = ["first", "primero"] secondPosition = "Second" secondPositionContent = ["second"] self.myDict[firstPosition] = firstPositionContent self.myDict[secondPosition] = secondPositionContent return deepcopy(self.myDict) def addExample(self): copy = self.copyExample() copy["Second"].add("segundo") </code></pre> <p>Does it return the reference to the lists I have in the dictionary? Or does it work as I expect and copy every list in a new list with a different reference?</p> <p>I know what a deep copy is (so there is no need to explain the difference between deep and shallow) but I am wondering if it works as I expect it to do and therefore do not change the instance variable when I use <code>addExample()</code>.</p>
19
2009-05-08T07:38:49Z
21,904,054
<p>I know it isn't answering your question but I think it's noteworthy for people looking at this question.</p> <p>If the data you're copying is simple in nature deepcopy might be overkill. With simple in nature I mean if your data is representable as Json. Let me illustrate with code:</p> <p>I've used <a href="http://www.json-generator.com/" rel="nofollow">http://www.json-generator.com/</a> to get some sample json data.</p> <pre><code>def deepCopyList(inp): for vl in inp: if isinstance(vl, list): yield list(deepCopyList(vl)) elif isinstance(vl, dict): yield deepCopyDict(vl) def deepCopyDict(inp): outp = inp.copy() for ky, vl in outp.iteritems(): if isinstance(vl, dict): outp[ky] = deepCopyDict(vl) elif isinstance(vl, list): outp[ky] = list(deepCopyList(vl)) return outp def simpleDeepCopy(inp): if isinstance(inp, dict): return deepCopyDict(inp) elif isinstance(inp, list): return deepCopyList(inp) else: return inp if __name__ == '__main__': import simplejson as json import time from copy import deepcopy fl = open('sample.json', 'r') sample = json.load(fl) start = time.time() for _ in xrange(10000): tmp = simpleDeepCopy(sample) end = time.time() print 'simpleDeepCopy: ' + str(end - start) start = time.time() for _ in xrange(10000): tmp = deepcopy(sample) end = time.time() print 'copy.deepcopy: ' + str(end - start) </code></pre> <p>output:</p> <pre><code>simpleDeepCopy: 0.0132050514221 copy.deepcopy: 2.66142916679 simpleDeepCopy: 0.0128579139709 copy.deepcopy: 2.60736298561 </code></pre>
1
2014-02-20T09:51:02Z
[ "python", "dictionary", "deep-copy" ]
Python cgi and stdin
838,991
<p>I'm using pycurl to upload a file via put and python cgi script to receive the file on the server side. Essentially, the code on the server side is:</p> <pre><code>while True: next = sys.stdin.read(4096) if not next: break #.... write the buffer </code></pre> <p>This seems to work with text, but not binary files (I'm on windows). With binary files, the loop doing stdin.read breaks after receiving anything around 10kb to 100kb. Any ideas?</p>
1
2009-05-08T09:26:34Z
839,009
<p>You need to run Python in binary mode. Change your CGI script from:</p> <pre><code>#!C:/Python25/python.exe </code></pre> <p>or whatever it says to:</p> <pre><code>#!C:/Python25/python.exe -u </code></pre> <p>Or you can do it programmatically like this:</p> <pre><code>msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY) </code></pre> <p>before starting to read from <code>stdin</code>.</p>
3
2009-05-08T09:30:14Z
[ "python", "cgi", "stdin" ]
Python cgi and stdin
838,991
<p>I'm using pycurl to upload a file via put and python cgi script to receive the file on the server side. Essentially, the code on the server side is:</p> <pre><code>while True: next = sys.stdin.read(4096) if not next: break #.... write the buffer </code></pre> <p>This seems to work with text, but not binary files (I'm on windows). With binary files, the loop doing stdin.read breaks after receiving anything around 10kb to 100kb. Any ideas?</p>
1
2009-05-08T09:26:34Z
839,163
<p>Use <a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a> instead of cgi. It will provide you an input file for the upload that's correctly opened.</p>
0
2009-05-08T10:15:11Z
[ "python", "cgi", "stdin" ]
cursor.rowcount always -1 in sqlite3 in python3k
839,069
<p>I am trying to get the <code>rowcount</code> of a <code>sqlite3</code> <code>cursor</code> in my Python3k program, but I am puzzled, as the <code>rowcount</code> is always <code>-1</code>, despite what Python3 docs say (actually it is contradictory, it should be <code>None</code>). Even after fetching all the rows, <code>rowcount</code> stays at <code>-1</code>. Is it a <code>sqlite3</code> bug? I have already checked if there are rows in the table.</p> <p>I can get around this checking if a <code>fetchone()</code> returns something different than <code>None</code>, but I thought this issue would be nice to discuss.</p> <p>Thanks.</p>
12
2009-05-08T09:49:27Z
839,419
<p>From the <a href="http://docs.python.org/3.0/library/sqlite3.html#sqlite3.Cursor.rowcount">documentation</a>:</p> <blockquote> <p>As required by the Python DB API Spec, the rowcount attribute “is -1 in case no executeXX() has been performed on the cursor or the rowcount of the last operation is not determinable by the interface”.</p> <p><strong>This includes <code>SELECT</code> statements because we cannot determine the number of rows a query produced until all rows were fetched.</strong></p> </blockquote> <p>That means <strong>all</strong> <code>SELECT</code> statements <strong>won't have a <code>rowcount</code></strong>. The behaviour you're observing is documented. </p> <p><strong>EDIT:</strong> Documentation doesn't say anywhere that <code>rowcount</code> <strong>will</strong> be updated after you do a <code>fetchall()</code> so it is just wrong to assume that.</p>
11
2009-05-08T11:33:06Z
[ "python", "database", "sqlite" ]
cursor.rowcount always -1 in sqlite3 in python3k
839,069
<p>I am trying to get the <code>rowcount</code> of a <code>sqlite3</code> <code>cursor</code> in my Python3k program, but I am puzzled, as the <code>rowcount</code> is always <code>-1</code>, despite what Python3 docs say (actually it is contradictory, it should be <code>None</code>). Even after fetching all the rows, <code>rowcount</code> stays at <code>-1</code>. Is it a <code>sqlite3</code> bug? I have already checked if there are rows in the table.</p> <p>I can get around this checking if a <code>fetchone()</code> returns something different than <code>None</code>, but I thought this issue would be nice to discuss.</p> <p>Thanks.</p>
12
2009-05-08T09:49:27Z
845,555
<p>Instead of "checking if a fetchone() returns something different than None", I suggest:</p> <pre><code>cursor.execute('SELECT * FROM foobar') for row in cursor: ... </code></pre> <p>this is <code>sqlite</code>-only (not supported in other DB API implementations) but very handy for <code>sqlite</code>-specific Python code (<em>and</em> fully documented, see <a href="http://docs.python.org/library/sqlite3.html">http://docs.python.org/library/sqlite3.html</a>).</p>
7
2009-05-10T15:50:09Z
[ "python", "database", "sqlite" ]
cursor.rowcount always -1 in sqlite3 in python3k
839,069
<p>I am trying to get the <code>rowcount</code> of a <code>sqlite3</code> <code>cursor</code> in my Python3k program, but I am puzzled, as the <code>rowcount</code> is always <code>-1</code>, despite what Python3 docs say (actually it is contradictory, it should be <code>None</code>). Even after fetching all the rows, <code>rowcount</code> stays at <code>-1</code>. Is it a <code>sqlite3</code> bug? I have already checked if there are rows in the table.</p> <p>I can get around this checking if a <code>fetchone()</code> returns something different than <code>None</code>, but I thought this issue would be nice to discuss.</p> <p>Thanks.</p>
12
2009-05-08T09:49:27Z
21,838,197
<pre><code>cursor = newdb.execute('select * from mydb;') print len(cursor.fetchall()) </code></pre> <p>The fetchall() will return a list of the rows returned from the select. Len of that list will give you the rowcount.</p>
6
2014-02-17T19:57:48Z
[ "python", "database", "sqlite" ]
cursor.rowcount always -1 in sqlite3 in python3k
839,069
<p>I am trying to get the <code>rowcount</code> of a <code>sqlite3</code> <code>cursor</code> in my Python3k program, but I am puzzled, as the <code>rowcount</code> is always <code>-1</code>, despite what Python3 docs say (actually it is contradictory, it should be <code>None</code>). Even after fetching all the rows, <code>rowcount</code> stays at <code>-1</code>. Is it a <code>sqlite3</code> bug? I have already checked if there are rows in the table.</p> <p>I can get around this checking if a <code>fetchone()</code> returns something different than <code>None</code>, but I thought this issue would be nice to discuss.</p> <p>Thanks.</p>
12
2009-05-08T09:49:27Z
37,788,479
<p>May better count the rows this way:</p> <blockquote> <pre><code>print cur.execute("SELECT COUNT(*) FROM db_name").fetchone()[0] </code></pre> </blockquote>
2
2016-06-13T11:21:05Z
[ "python", "database", "sqlite" ]
Twisted and p2p applications
839,384
<p>Can you tell me: could I use twisted for p2p-applications creating? And what protocols should I choose for this?</p>
13
2009-05-08T11:20:58Z
839,411
<p>Yes, twisted was used to create the initial version of Bittorrent. There are some opensource libraries to start from.</p>
1
2009-05-08T11:30:12Z
[ "python", "twisted", "protocols", "p2p" ]
Twisted and p2p applications
839,384
<p>Can you tell me: could I use twisted for p2p-applications creating? And what protocols should I choose for this?</p>
13
2009-05-08T11:20:58Z
839,711
<p><a href="http://code.activestate.com/recipes/440555/" rel="nofollow">bittorrent twisted python client/server</a></p>
4
2009-05-08T13:06:53Z
[ "python", "twisted", "protocols", "p2p" ]
Twisted and p2p applications
839,384
<p>Can you tell me: could I use twisted for p2p-applications creating? And what protocols should I choose for this?</p>
13
2009-05-08T11:20:58Z
846,470
<p>Yes, you can absolutely use twisted to create a p2p application. The one that comes first to my mind is Dtella (<a href="http://dtella.org/" rel="nofollow">http://dtella.org/</a>). It's uses the Direct Connect protocol.</p> <p>They provide the source code, so that could get you started. I know that quite a few different university networks have DC hubs running. That seems to be the ideal use of this protocol.</p>
0
2009-05-11T01:46:14Z
[ "python", "twisted", "protocols", "p2p" ]
Twisted and p2p applications
839,384
<p>Can you tell me: could I use twisted for p2p-applications creating? And what protocols should I choose for this?</p>
13
2009-05-08T11:20:58Z
846,492
<p>The best solution is to use the source code for BitTorrent. It was built with Twisted until they switched over to a C++ implementation called Utorrent.</p> <ul> <li>Last known Twisted version of BitTorrent <ul> <li><a href="http://download.bittorrent.com/dl/archive/BitTorrent-5.2.2.tar.gz" rel="nofollow">http://download.bittorrent.com/dl/archive/BitTorrent-5.2.2.tar.gz</a></li> </ul></li> <li>Older versions <ul> <li><a href="http://download.bittorrent.com/dl/archive/" rel="nofollow">http://download.bittorrent.com/dl/archive/</a></li> </ul></li> </ul> <p>As an alternative, you also might want to take a look at <a href="https://github.com/twisted/vertex" rel="nofollow">Vertex</a>.</p> <p>It is a p2p library built on top of Twisted and comes with goodies like bypassing firewalls.</p> <p>Its probably more complete than the other people's sample.</p> <ul> <li>Link to Vertex <ul> <li><a href="https://github.com/twisted/vertex" rel="nofollow">https://github.com/twisted/vertex</a></li> </ul></li> </ul>
12
2009-05-11T02:02:34Z
[ "python", "twisted", "protocols", "p2p" ]
Best Practices for Python Exceptions?
839,636
<p>What are the best practices for creating exceptions? I just saw this, and I don't know if I should be horrified, or like it. I read several times in books that exceptions should never ever hold a string, because strings themselves can throw exceptions. Any real truth to this?</p> <p>Basically from my understanding from the scripts is that this was done so all the inhouse Python libraries will have a common error message format (something that is desperately needed) so I can understand why putting the error message string is a good idea. (Almost every method throws exceptions due to the utter need for nothing invalid getting through).</p> <p>The code in question is the following:</p> <pre><code>""" Base Exception, Error """ class Error(Exception): def __init__(self, message): self.message = message def __str__(self): return "[ERROR] %s\n" % str(self.message) def log(self): ret = "%s" % str(self.message) if(hasattr(self, "reason")): return "".join([ret, "\n==&gt; %s" % str(self.reason)]) return ret class PCSException(Error): def __init__(self, message, reason = None): self.message = message self.reason = reason def __str__(self): ret = "[PCS_ERROR] %s\n" % str(self.message) if(self.reason != None): ret += "[REASON] %s\n" % str(self.reason) return ret </code></pre> <p>This is just the tip of the iceberg, but can someone give me some insight in what makes this a terrible idea? Or if there is a much better exception coding process/style.</p>
45
2009-05-08T12:44:43Z
839,662
<blockquote> <p>I read several times in books that exceptions should never ever hold a string, because strings themselves can throw exceptions. Any real truth to this?</p> </blockquote> <p>What?</p> <p>Please provide a reference or a link to this. It's totally untrue.</p> <p>Since all objects can throw exceptions, no object could be contained in an exception by that logic.</p> <p>No, the "no strings" is simply crazy in a Python context. Perhaps you read it in a C++ context.</p> <hr> <p><strong>Edit</strong></p> <p>Once upon a time (back in the olden days) you could raise a Python exception by name instead of by the actual class.</p> <pre><code>raise "SomeNameOfAnExceptionClass" </code></pre> <p>This is bad. But this is <em>not</em> including a string inside an exception. This is naming the exception with a string instead of the actual class object. In 2.5, this can still work, but gets a deprecation warning.</p> <p>Perhaps this is what you read "Do not raise an exception with a string name"</p>
26
2009-05-08T12:54:39Z
[ "python", "exception" ]
Best Practices for Python Exceptions?
839,636
<p>What are the best practices for creating exceptions? I just saw this, and I don't know if I should be horrified, or like it. I read several times in books that exceptions should never ever hold a string, because strings themselves can throw exceptions. Any real truth to this?</p> <p>Basically from my understanding from the scripts is that this was done so all the inhouse Python libraries will have a common error message format (something that is desperately needed) so I can understand why putting the error message string is a good idea. (Almost every method throws exceptions due to the utter need for nothing invalid getting through).</p> <p>The code in question is the following:</p> <pre><code>""" Base Exception, Error """ class Error(Exception): def __init__(self, message): self.message = message def __str__(self): return "[ERROR] %s\n" % str(self.message) def log(self): ret = "%s" % str(self.message) if(hasattr(self, "reason")): return "".join([ret, "\n==&gt; %s" % str(self.reason)]) return ret class PCSException(Error): def __init__(self, message, reason = None): self.message = message self.reason = reason def __str__(self): ret = "[PCS_ERROR] %s\n" % str(self.message) if(self.reason != None): ret += "[REASON] %s\n" % str(self.reason) return ret </code></pre> <p>This is just the tip of the iceberg, but can someone give me some insight in what makes this a terrible idea? Or if there is a much better exception coding process/style.</p>
45
2009-05-08T12:44:43Z
839,757
<p>First impression is that it's entirely too much code for an exception.</p> <p>Formatting exceptions should be done in logger configuration. Same goes for the logging itself.</p> <p>It also redefines the standard (and deprecated) message attribute, and doesn't call the superclass constructor. (This might or might not break Python 3.0 exception chaining, I haven't tried because I'm running 2.6)</p> <p>Most of what the extra code does can be realised using BaseException.args, by logging the following as the "message":</p> <pre><code>'\n==&gt; '.join(exception.args) </code></pre> <p>I'd argue that if something can be done using a common / idiomatic mechanism, it should especially be done so in exception handling. (Exceptions being a mechanism to signal something <em>across</em> application layers.)</p> <p>Personally, I try to avoid anything beyond </p> <pre><code>class SomeException(Exception): pass </code></pre> <p>(Disclaimer: answer subjective, possibly by nature of the question.)</p>
2
2009-05-08T13:20:42Z
[ "python", "exception" ]
Best Practices for Python Exceptions?
839,636
<p>What are the best practices for creating exceptions? I just saw this, and I don't know if I should be horrified, or like it. I read several times in books that exceptions should never ever hold a string, because strings themselves can throw exceptions. Any real truth to this?</p> <p>Basically from my understanding from the scripts is that this was done so all the inhouse Python libraries will have a common error message format (something that is desperately needed) so I can understand why putting the error message string is a good idea. (Almost every method throws exceptions due to the utter need for nothing invalid getting through).</p> <p>The code in question is the following:</p> <pre><code>""" Base Exception, Error """ class Error(Exception): def __init__(self, message): self.message = message def __str__(self): return "[ERROR] %s\n" % str(self.message) def log(self): ret = "%s" % str(self.message) if(hasattr(self, "reason")): return "".join([ret, "\n==&gt; %s" % str(self.reason)]) return ret class PCSException(Error): def __init__(self, message, reason = None): self.message = message self.reason = reason def __str__(self): ret = "[PCS_ERROR] %s\n" % str(self.message) if(self.reason != None): ret += "[REASON] %s\n" % str(self.reason) return ret </code></pre> <p>This is just the tip of the iceberg, but can someone give me some insight in what makes this a terrible idea? Or if there is a much better exception coding process/style.</p>
45
2009-05-08T12:44:43Z
839,844
<p><a href="http://eli.thegreenplace.net/2008/08/21/robust-exception-handling/" rel="nofollow">Robust exception handling (in Python)</a> - a "best practices for Python exceptions" blog post I wrote a while ago. You may find it useful.</p> <p>Some key points from the blog:</p> <blockquote> <p><strong>Never use exceptions for flow-control</strong></p> <p>Exceptions exist for exceptional situations: events that are not a part of normal execution.</p> </blockquote> <p>Consider 'find' on a string returning -1 if the pattern isn't found, but indexing beyond the end of a string raises an exception. Not finding the string is normal execution.</p> <blockquote> <p><strong>Handle exceptions at the level that knows how to handle them</strong></p> <p>... </p> <p>The best place is that piece of code that can handle the exception. For some exceptions, like programming errors (e.g. IndexError, TypeError, NameError etc.) exceptions are best left to the programmer / user, because "handling" them will just hide real bugs.</p> </blockquote> <p>Always ask "is this the right place to handle this exception?" and be careful with catching all exceptions.</p> <blockquote> <p><strong>Document the exceptions thrown by your code</strong></p> <p>...</p> <p>thinking about which exceptions your code may throw will help you write better, safer and more encapsulated code</p> </blockquote>
68
2009-05-08T13:41:01Z
[ "python", "exception" ]
Best Practices for Python Exceptions?
839,636
<p>What are the best practices for creating exceptions? I just saw this, and I don't know if I should be horrified, or like it. I read several times in books that exceptions should never ever hold a string, because strings themselves can throw exceptions. Any real truth to this?</p> <p>Basically from my understanding from the scripts is that this was done so all the inhouse Python libraries will have a common error message format (something that is desperately needed) so I can understand why putting the error message string is a good idea. (Almost every method throws exceptions due to the utter need for nothing invalid getting through).</p> <p>The code in question is the following:</p> <pre><code>""" Base Exception, Error """ class Error(Exception): def __init__(self, message): self.message = message def __str__(self): return "[ERROR] %s\n" % str(self.message) def log(self): ret = "%s" % str(self.message) if(hasattr(self, "reason")): return "".join([ret, "\n==&gt; %s" % str(self.reason)]) return ret class PCSException(Error): def __init__(self, message, reason = None): self.message = message self.reason = reason def __str__(self): ret = "[PCS_ERROR] %s\n" % str(self.message) if(self.reason != None): ret += "[REASON] %s\n" % str(self.reason) return ret </code></pre> <p>This is just the tip of the iceberg, but can someone give me some insight in what makes this a terrible idea? Or if there is a much better exception coding process/style.</p>
45
2009-05-08T12:44:43Z
8,271,420
<p>I believe the advice against creating exceptions with a string comes from "Learning Python" (O'Reilly). In a section entitled <strong>String Exceptions Are Right Out!</strong>, it points out the (now removed) ability to create an exception directly with an arbitrary string. </p> <p>The code it gives as an example is:</p> <pre><code>myexc = "My exception string" try: raise myexc except myexc: print ('caught') </code></pre> <p>This is on p858 of the Fourth Edition (paperback).</p>
4
2011-11-25T15:48:03Z
[ "python", "exception" ]
How to use time > year 2038 on official Windows Python 2.5
839,755
<p>The official Python 2.5 on Windows was build with Visual Studio.Net 2003, which uses 32 bit time_t. So when the year is > 2038, it just gives exceptions.</p> <p>Although this is fixed in Python 2.6 (which changed time_t to 64 bit with VS2008), I'd like to use 2.5 because many modules are already compiled for it.</p> <p>So here's my question - is there any solution to easily let my program handle year > 2038 and still using official Python 2.5? For example some pre-made libraries like <code>"time64"</code> or "longtime" etc...</p> <p>Please do not tell me to upgrade to 2.6+ or forget about the bug - I have my reason to need to make it work, that's why I post the question here.</p>
5
2009-05-08T13:19:17Z
839,826
<p>The <code>datetime</code> module in the standard library should work fine for you. What do you need from module <code>time</code> that <code>datetime</code> doesn't offer?</p>
5
2009-05-08T13:34:27Z
[ "python", "time", "python-2.5", "time-t", "year2038" ]
How to use time > year 2038 on official Windows Python 2.5
839,755
<p>The official Python 2.5 on Windows was build with Visual Studio.Net 2003, which uses 32 bit time_t. So when the year is > 2038, it just gives exceptions.</p> <p>Although this is fixed in Python 2.6 (which changed time_t to 64 bit with VS2008), I'd like to use 2.5 because many modules are already compiled for it.</p> <p>So here's my question - is there any solution to easily let my program handle year > 2038 and still using official Python 2.5? For example some pre-made libraries like <code>"time64"</code> or "longtime" etc...</p> <p>Please do not tell me to upgrade to 2.6+ or forget about the bug - I have my reason to need to make it work, that's why I post the question here.</p>
5
2009-05-08T13:19:17Z
839,830
<p>I don't mean to sound trite, but why not:</p> <ul> <li>forget about the Y2038 bug with Python 2.5</li> <li>upgrade to Python 2.6 at some point in the future before 2038</li> </ul> <p><strong>edit:</strong> To clarify: (and I'm serious &mdash; I didn't mean to poke fun)</p> <p>Presumably you can upgrade Python to 2.6 (or later) at some indefinite time between now and 2038. Maybe in 2012. Maybe in 2015. Maybe in 2037.</p> <p>If you are aware of the differences between the Python timestamp variable in your application (I'm not much of a Python user), it seems like these would be the important aspects to consider:</p> <ul> <li>what data is being saved persistently</li> <li>how a Python 2.5 timestamp variable that has been persisted, gets restored using Python 2.6 (presumably it will "do the right thing")</li> <li>whether old data will be stored in its persistent form long enough for ambiguities to arise (e.g. the year "96" is unambiguous when considered between 1950 and 2049, but if that data is kept around until the year 2230 then "96" could be 1996, 2096, or 2196)</li> </ul> <p>If the answers are favorable, just use the regular timestamp with its 2038 bug. You'll have to compare that with the amount of redesign/refactoring you'd have to do to make your application work with an alternate timestamp (e.g. a database timestamp string or whatever).</p>
5
2009-05-08T13:35:51Z
[ "python", "time", "python-2.5", "time-t", "year2038" ]