title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
listlengths
1
5
How do you verify an RSA SHA1 signature in pyOpenSSL
1,471,037
<p>I tried installing M2Crypto and facing problems. I don't want to force my customers to use such libraries which are difficult to install. So, I thought I would give pyOpenSSL a try. I am able to get the public key from pem certificate but am not able to find any way to verify the signature.</p>
1
2009-09-24T11:16:52Z
1,506,756
<p>You simply can't do this with pyOpenSSL. It is a very limited wrapper around openssl library. But I have a guess what's wrong with building M2Crypto on your host. Try running:</p> <pre><code>export SWIG_FEATURES=-I/usr/include/openssl </code></pre> <p>before trying to install M2Crypto.</p>
0
2009-10-01T22:02:07Z
[ "python", "installation", "m2crypto", "pyopenssl" ]
How do you verify an RSA SHA1 signature in pyOpenSSL
1,471,037
<p>I tried installing M2Crypto and facing problems. I don't want to force my customers to use such libraries which are difficult to install. So, I thought I would give pyOpenSSL a try. I am able to get the public key from pem certificate but am not able to find any way to verify the signature.</p>
1
2009-09-24T11:16:52Z
17,179,006
<p>I believe that what you want is the code from this blog entry (it's mine):</p> <p><a href="http://www.v13.gr/blog/?p=303" rel="nofollow">http://www.v13.gr/blog/?p=303</a></p> <p>As you can see you have to use DER to handle the certificate and get the appropriate parts. That took me a considerable amount of effort and days so let me know whether it worked for you too.</p>
0
2013-06-18T21:11:10Z
[ "python", "installation", "m2crypto", "pyopenssl" ]
String similarity metrics in Python
1,471,153
<p>I want to find string similarity between two strings. <a href="http://en.wikipedia.org/wiki/Category%3aString_similarity_measures">This</a> page has examples of some of them. Python has an implemnetation of <a href="http://code.google.com/p/pylevenshtein/">Levenshtein algorithm</a>. Is there a better algorithm, (and hopefully a python library), under these contraints.</p> <ol> <li>I want to do fuzzy matches between strings. eg matches('Hello, All you people', 'hello, all You peopl') should return True</li> <li>False negatives are acceptable, False positives, except in extremely rare cases are not.</li> <li>This is done in a non realtime setting, so speed is not (much) of concern.</li> <li>[Edit] I am comparing multi word strings.</li> </ol> <p>Would something other than Levenshtein distance(or Levenshtein ratio) be a better algorithm for my case?</p>
28
2009-09-24T11:43:00Z
1,471,170
<p>Is that what you mean?</p> <pre><code>&gt;&gt;&gt; get_close_matches('appel', ['ape', 'apple', 'peach', 'puppy']) ['apple', 'ape'] &gt;&gt;&gt; import keyword &gt;&gt;&gt; get_close_matches('wheel', keyword.kwlist) ['while'] &gt;&gt;&gt; get_close_matches('apple', keyword.kwlist) [] &gt;&gt;&gt; get_close_matches('accept', keyword.kwlist) ['except'] </code></pre> <p>look at <a href="http://docs.python.org/library/difflib.html#difflib.get%5Fclose%5Fmatches" rel="nofollow">http://docs.python.org/library/difflib.html#difflib.get%5Fclose%5Fmatches</a></p>
3
2009-09-24T11:46:47Z
[ "python", "algorithm", "string", "levenshtein-distance" ]
String similarity metrics in Python
1,471,153
<p>I want to find string similarity between two strings. <a href="http://en.wikipedia.org/wiki/Category%3aString_similarity_measures">This</a> page has examples of some of them. Python has an implemnetation of <a href="http://code.google.com/p/pylevenshtein/">Levenshtein algorithm</a>. Is there a better algorithm, (and hopefully a python library), under these contraints.</p> <ol> <li>I want to do fuzzy matches between strings. eg matches('Hello, All you people', 'hello, all You peopl') should return True</li> <li>False negatives are acceptable, False positives, except in extremely rare cases are not.</li> <li>This is done in a non realtime setting, so speed is not (much) of concern.</li> <li>[Edit] I am comparing multi word strings.</li> </ol> <p>Would something other than Levenshtein distance(or Levenshtein ratio) be a better algorithm for my case?</p>
28
2009-09-24T11:43:00Z
1,471,303
<p>There's a great resource for string similarity metrics at the University of Sheffield. It has a list of various metrics (beyond just Levenshtein) and has open-source implementations of them. Looks like many of them should be easy to adapt into Python.</p> <p><a href="http://web.archive.org/web/20081224234350/http://www.dcs.shef.ac.uk/~sam/stringmetrics.html" rel="nofollow">http://web.archive.org/web/20081224234350/http://www.dcs.shef.ac.uk/~sam/stringmetrics.html</a></p> <p>Here's a bit of the list:</p> <ul> <li>Hamming distance</li> <li>Levenshtein distance</li> <li>Needleman-Wunch distance or Sellers Algorithm</li> <li>and many more...</li> </ul>
15
2009-09-24T12:13:28Z
[ "python", "algorithm", "string", "levenshtein-distance" ]
String similarity metrics in Python
1,471,153
<p>I want to find string similarity between two strings. <a href="http://en.wikipedia.org/wiki/Category%3aString_similarity_measures">This</a> page has examples of some of them. Python has an implemnetation of <a href="http://code.google.com/p/pylevenshtein/">Levenshtein algorithm</a>. Is there a better algorithm, (and hopefully a python library), under these contraints.</p> <ol> <li>I want to do fuzzy matches between strings. eg matches('Hello, All you people', 'hello, all You peopl') should return True</li> <li>False negatives are acceptable, False positives, except in extremely rare cases are not.</li> <li>This is done in a non realtime setting, so speed is not (much) of concern.</li> <li>[Edit] I am comparing multi word strings.</li> </ol> <p>Would something other than Levenshtein distance(or Levenshtein ratio) be a better algorithm for my case?</p>
28
2009-09-24T11:43:00Z
1,471,603
<p>I realize it's not the same thing, but this is close enough:</p> <pre><code>&gt;&gt;&gt; import difflib &gt;&gt;&gt; a = 'Hello, All you people' &gt;&gt;&gt; b = 'hello, all You peopl' &gt;&gt;&gt; seq=difflib.SequenceMatcher(a=a.lower(), b=b.lower()) &gt;&gt;&gt; seq.ratio() 0.97560975609756095 </code></pre> <p>You can make this as a function</p> <pre><code>def similar(seq1, seq2): return difflib.SequenceMatcher(a=seq1.lower(), b=seq2.lower()).ratio() &gt; 0.9 &gt;&gt;&gt; similar(a, b) True &gt;&gt;&gt; similar('Hello, world', 'Hi, world') False </code></pre>
63
2009-09-24T13:10:55Z
[ "python", "algorithm", "string", "levenshtein-distance" ]
String similarity metrics in Python
1,471,153
<p>I want to find string similarity between two strings. <a href="http://en.wikipedia.org/wiki/Category%3aString_similarity_measures">This</a> page has examples of some of them. Python has an implemnetation of <a href="http://code.google.com/p/pylevenshtein/">Levenshtein algorithm</a>. Is there a better algorithm, (and hopefully a python library), under these contraints.</p> <ol> <li>I want to do fuzzy matches between strings. eg matches('Hello, All you people', 'hello, all You peopl') should return True</li> <li>False negatives are acceptable, False positives, except in extremely rare cases are not.</li> <li>This is done in a non realtime setting, so speed is not (much) of concern.</li> <li>[Edit] I am comparing multi word strings.</li> </ol> <p>Would something other than Levenshtein distance(or Levenshtein ratio) be a better algorithm for my case?</p>
28
2009-09-24T11:43:00Z
1,472,165
<p>I would use Levenshtein distance, or the so-called Damerau distance (which takes transpositions into account) rather than the difflib stuff for two reasons (1) "fast enough" (dynamic programming algo) and "whoooosh" (bit-bashing) C code is available and (2) well-understood behaviour e.g. Levenshtein satisfies the triangle inequality and thus can be used in e.g. a Burkhard-Keller tree.</p> <p>Threshold: you should treat as "positive" only those cases where distance &lt; (1 - X) * max(len(string1), len(string2)) and adjust X (the similarity factor) to suit yourself. One way of choosing X is to get a sample of matches, calculate X for each, ignore cases where X &lt; say 0.8 or 0.9, then sort the remainder in descending order of X and eye-ball them and insert the correct result and calculate some cost-of-mistakes measure for various levels of X.</p> <p>N.B. Your ape/apple example has distance 2, so X is 0.6 ... I would only use a threshold as low as 0.75 if I were desperately looking for something and had a high false-negative penalty</p>
5
2009-09-24T14:41:31Z
[ "python", "algorithm", "string", "levenshtein-distance" ]
String similarity metrics in Python
1,471,153
<p>I want to find string similarity between two strings. <a href="http://en.wikipedia.org/wiki/Category%3aString_similarity_measures">This</a> page has examples of some of them. Python has an implemnetation of <a href="http://code.google.com/p/pylevenshtein/">Levenshtein algorithm</a>. Is there a better algorithm, (and hopefully a python library), under these contraints.</p> <ol> <li>I want to do fuzzy matches between strings. eg matches('Hello, All you people', 'hello, all You peopl') should return True</li> <li>False negatives are acceptable, False positives, except in extremely rare cases are not.</li> <li>This is done in a non realtime setting, so speed is not (much) of concern.</li> <li>[Edit] I am comparing multi word strings.</li> </ol> <p>Would something other than Levenshtein distance(or Levenshtein ratio) be a better algorithm for my case?</p>
28
2009-09-24T11:43:00Z
26,894,959
<p>I know this isn't the same but you can adjust the ratio to filter out strings that are not similar enough and return the closest match to the string you are looking for.</p> <p>Perhaps you would be more interested in semantic similarity metrics.</p> <p><a href="https://www.google.com/search?client=ubuntu&amp;channel=fs&amp;q=semantic+similarity+string+match&amp;ie=utf-8&amp;oe=utf-8" rel="nofollow">https://www.google.com/search?client=ubuntu&amp;channel=fs&amp;q=semantic+similarity+string+match&amp;ie=utf-8&amp;oe=utf-8</a></p> <p>I realize you said speed is not an issue but if you are processing a lot of the strings for your algorithm the below is very helpful.</p> <pre><code>def spellcheck(self, sentence): #return ' '.join([difflib.get_close_matches(word, wordlist,1 , 0)[0] for word in sentence.split()]) return ' '.join( [ sorted( { Levenshtein.ratio(x, word):x for x in wordlist }.items(), reverse=True)[0][1] for word in sentence.split() ] ) </code></pre> <p>Its about 20 times faster than difflib.</p> <p><a href="https://pypi.python.org/pypi/python-Levenshtein/" rel="nofollow">https://pypi.python.org/pypi/python-Levenshtein/</a></p> <p>import Levenshtein</p>
1
2014-11-12T19:28:21Z
[ "python", "algorithm", "string", "levenshtein-distance" ]
String similarity metrics in Python
1,471,153
<p>I want to find string similarity between two strings. <a href="http://en.wikipedia.org/wiki/Category%3aString_similarity_measures">This</a> page has examples of some of them. Python has an implemnetation of <a href="http://code.google.com/p/pylevenshtein/">Levenshtein algorithm</a>. Is there a better algorithm, (and hopefully a python library), under these contraints.</p> <ol> <li>I want to do fuzzy matches between strings. eg matches('Hello, All you people', 'hello, all You peopl') should return True</li> <li>False negatives are acceptable, False positives, except in extremely rare cases are not.</li> <li>This is done in a non realtime setting, so speed is not (much) of concern.</li> <li>[Edit] I am comparing multi word strings.</li> </ol> <p>Would something other than Levenshtein distance(or Levenshtein ratio) be a better algorithm for my case?</p>
28
2009-09-24T11:43:00Z
31,236,472
<p>This snippet will calculate the difflib, Levenshtein, Sørensen, and Jaccard similarity values for two strings. In the snippet below, I was iterating over a tsv in which the strings of interest occupied columns <code>[3]</code> and <code>[4]</code> of the tsv. (<code>pip install python-Levenshtein</code> and <code>pip install distance</code>):</p> <pre><code>import codecs, difflib, Levenshtein, distance with codecs.open("titles.tsv","r","utf-8") as f: title_list = f.read().split("\n")[:-1] for row in title_list: sr = row.lower().split("\t") diffl = difflib.SequenceMatcher(None, sr[3], sr[4]).ratio() lev = Levenshtein.ratio(sr[3], sr[4]) sor = 1 - distance.sorensen(sr[3], sr[4]) jac = 1 - distance.jaccard(sr[3], sr[4]) print diffl, lev, sor, jac </code></pre>
5
2015-07-06T00:51:12Z
[ "python", "algorithm", "string", "levenshtein-distance" ]
How do I determine the proper `paramstyle` when all I have is a `Connection` object?
1,471,304
<p>I have an instance of a <code>Connection</code> (required to DB API 2.0-compliant), but I don't have the module from which it was imported. The problem is that I am trying to use named parameters, but I don't know which <code>paramstyle</code> to use.</p> <p>Since <code>paramstyle</code> is a module-level constant, I can't just ask the <code>Connection</code>. I tried using <a href="http://docs.python.org/library/inspect.html#inspect.getmodule" rel="nofollow"><code>inspect.getmodule()</code></a> on my <code>Connection</code> instance, but it just returned <code>None</code>. Is there an easier way that I'm just missing, or will I need to do some <code>try</code>/<code>except</code> code to determine which <code>paramstyle</code> to use?</p> <p>Thanks.</p>
2
2009-09-24T12:14:04Z
1,471,348
<p>Where did you get the instance from? I can't imagine a situation where you won't know the beforehand the source of the connection. If the user of your library is passing you a connection, ask him for the paramstyle as well.</p> <p>Anyway, look at the following console session:</p> <pre><code>&gt;&gt;&gt; import sqlite3 &gt;&gt;&gt; c = sqlite3.connect('/tmp/test.db') &gt;&gt;&gt; c &lt;sqlite3.Connection object at 0xb7db2320&gt; &gt;&gt;&gt; type(c) &lt;type 'sqlite3.Connection'&gt; &gt;&gt;&gt; type(c).__module__ 'sqlite3' &gt;&gt;&gt; import sys &gt;&gt;&gt; sys.modules[type(c).__module__].paramstyle 'qmark' </code></pre> <p>However that sucks. I wouldn't rely on it not even for a second. I use my own connection-like objects, and I'd like to pass one of those to your library. I'd hate it when it tries to magically find out the paramstyle and fails because I am using a connection-like wrapper object.</p>
2
2009-09-24T12:22:11Z
[ "python", "db-api-2" ]
How do I determine the proper `paramstyle` when all I have is a `Connection` object?
1,471,304
<p>I have an instance of a <code>Connection</code> (required to DB API 2.0-compliant), but I don't have the module from which it was imported. The problem is that I am trying to use named parameters, but I don't know which <code>paramstyle</code> to use.</p> <p>Since <code>paramstyle</code> is a module-level constant, I can't just ask the <code>Connection</code>. I tried using <a href="http://docs.python.org/library/inspect.html#inspect.getmodule" rel="nofollow"><code>inspect.getmodule()</code></a> on my <code>Connection</code> instance, but it just returned <code>None</code>. Is there an easier way that I'm just missing, or will I need to do some <code>try</code>/<code>except</code> code to determine which <code>paramstyle</code> to use?</p> <p>Thanks.</p>
2
2009-09-24T12:14:04Z
1,471,359
<p>Pass <code>type(connection)</code> (connection class) to <code>inspect.getmodule()</code>, not connection object. The class tracks the module it was defined in so <code>inspect</code> can find it, while object creation is not tracked.</p>
2
2009-09-24T12:24:34Z
[ "python", "db-api-2" ]
How do I determine the proper `paramstyle` when all I have is a `Connection` object?
1,471,304
<p>I have an instance of a <code>Connection</code> (required to DB API 2.0-compliant), but I don't have the module from which it was imported. The problem is that I am trying to use named parameters, but I don't know which <code>paramstyle</code> to use.</p> <p>Since <code>paramstyle</code> is a module-level constant, I can't just ask the <code>Connection</code>. I tried using <a href="http://docs.python.org/library/inspect.html#inspect.getmodule" rel="nofollow"><code>inspect.getmodule()</code></a> on my <code>Connection</code> instance, but it just returned <code>None</code>. Is there an easier way that I'm just missing, or will I need to do some <code>try</code>/<code>except</code> code to determine which <code>paramstyle</code> to use?</p> <p>Thanks.</p>
2
2009-09-24T12:14:04Z
1,471,428
<p>You can't.</p> <p>You can try by looking at <code>connection.__class__.__module__</code>, but it's not specified by DB-API that it'll work. In fact for many common cases it won't. (eg. the class is defined in a submodule of the package that acts as the DB-API module object; or the class is a C extension with no <code>__module__</code>.)</p> <p>It is unfortunate, but you will have to pass a reference to the DB-API module object around with the DB-API connection object.</p>
2
2009-09-24T12:37:57Z
[ "python", "db-api-2" ]
How should I handle software packages?
1,471,567
<p>I am trying to install pysqlite and have troubles with that. I found out that the most probable reason of that is missing sqlite headers and I have to install them. My platform: CentOS release 5.3 (Final). I have Python-2.6.2.</p> <p>I also found out that I need .rpm files. As far as I have them I execute:</p> <pre><code>rpm -i sqlite3-devel-3.n.n.n.rpm </code></pre> <p>and everything should be fine.</p> <p>However, I do not know where to find sqlite3-devel-3.n.n.n.rpm file. Should it already be on my system? I could not locate it with "locate sqlite3-devel-3". Should I download this file? If yes where I can find it and which version should I use? I mean, the .rpm file should be, probably, consistent with the version of sqlite that I have on my computer? If it is the case, how can I find out the version of my sqlite?</p> <p>If I type "from pysqlite2 import dbapi2 as sqlite" I get:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named pysqlite2 </code></pre> <p>"yum search pysqlite" gives me the following:</p> <pre><code>Loaded plugins: fastestmirror Excluding Packages in global exclude list Finished ==== Matched: pysqlite ==== python-sqlite.x86_64 : Python bindings for sqlite. </code></pre> <p>By the way, I have the following directory: /home/myname/opt/lib/python2.6/sqlite3 and there I have the following files:</p> <pre><code>dbapi2.py dbapi2.pyc dbapi2.pyo dump.py dump.pyc dump.pyo __init__.py __init__.pyc __init__.pyo test </code></pre> <p>If I type "import unittest" and then "import sqlite3 as sqlite" I get:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/myname/opt/lib/python2.6/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/home/myname/opt/lib/python2.6/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 </code></pre> <p>Thank you in advance.</p>
1
2009-09-24T13:05:49Z
1,471,595
<p>Python 2.6 (and some earlier) include sqlite <a href="http://file%3A///Users/mark/Public/docs/python-2.6.2-docs-html/library/sqlite3.html" rel="nofollow">Python org library ref</a> so you should not need to do this. Just import it and run</p>
3
2009-09-24T13:09:18Z
[ "python", "sqlite", "rpm", "pysqlite" ]
How should I handle software packages?
1,471,567
<p>I am trying to install pysqlite and have troubles with that. I found out that the most probable reason of that is missing sqlite headers and I have to install them. My platform: CentOS release 5.3 (Final). I have Python-2.6.2.</p> <p>I also found out that I need .rpm files. As far as I have them I execute:</p> <pre><code>rpm -i sqlite3-devel-3.n.n.n.rpm </code></pre> <p>and everything should be fine.</p> <p>However, I do not know where to find sqlite3-devel-3.n.n.n.rpm file. Should it already be on my system? I could not locate it with "locate sqlite3-devel-3". Should I download this file? If yes where I can find it and which version should I use? I mean, the .rpm file should be, probably, consistent with the version of sqlite that I have on my computer? If it is the case, how can I find out the version of my sqlite?</p> <p>If I type "from pysqlite2 import dbapi2 as sqlite" I get:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named pysqlite2 </code></pre> <p>"yum search pysqlite" gives me the following:</p> <pre><code>Loaded plugins: fastestmirror Excluding Packages in global exclude list Finished ==== Matched: pysqlite ==== python-sqlite.x86_64 : Python bindings for sqlite. </code></pre> <p>By the way, I have the following directory: /home/myname/opt/lib/python2.6/sqlite3 and there I have the following files:</p> <pre><code>dbapi2.py dbapi2.pyc dbapi2.pyo dump.py dump.pyc dump.pyo __init__.py __init__.pyc __init__.pyo test </code></pre> <p>If I type "import unittest" and then "import sqlite3 as sqlite" I get:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/myname/opt/lib/python2.6/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/home/myname/opt/lib/python2.6/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 </code></pre> <p>Thank you in advance.</p>
1
2009-09-24T13:05:49Z
1,472,838
<p>Typically, you should install the python <code>sqlite</code> module through <code>yum</code>, something like:</p> <pre><code>yum install python-sqlite </code></pre> <p>and then edit your code changing <code>sqlite2</code> references to <code>sqlite3</code>.</p> <p>By the way, whenever you read directions to install <code>sqlite3-devel-3.n.n.n.rpm</code>, the <code>n</code> parts are not literal; they're supposed to be replaced with numbers specifying a version of the rpm package.</p>
1
2009-09-24T16:33:45Z
[ "python", "sqlite", "rpm", "pysqlite" ]
How should I handle software packages?
1,471,567
<p>I am trying to install pysqlite and have troubles with that. I found out that the most probable reason of that is missing sqlite headers and I have to install them. My platform: CentOS release 5.3 (Final). I have Python-2.6.2.</p> <p>I also found out that I need .rpm files. As far as I have them I execute:</p> <pre><code>rpm -i sqlite3-devel-3.n.n.n.rpm </code></pre> <p>and everything should be fine.</p> <p>However, I do not know where to find sqlite3-devel-3.n.n.n.rpm file. Should it already be on my system? I could not locate it with "locate sqlite3-devel-3". Should I download this file? If yes where I can find it and which version should I use? I mean, the .rpm file should be, probably, consistent with the version of sqlite that I have on my computer? If it is the case, how can I find out the version of my sqlite?</p> <p>If I type "from pysqlite2 import dbapi2 as sqlite" I get:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; ImportError: No module named pysqlite2 </code></pre> <p>"yum search pysqlite" gives me the following:</p> <pre><code>Loaded plugins: fastestmirror Excluding Packages in global exclude list Finished ==== Matched: pysqlite ==== python-sqlite.x86_64 : Python bindings for sqlite. </code></pre> <p>By the way, I have the following directory: /home/myname/opt/lib/python2.6/sqlite3 and there I have the following files:</p> <pre><code>dbapi2.py dbapi2.pyc dbapi2.pyo dump.py dump.pyc dump.pyo __init__.py __init__.pyc __init__.pyo test </code></pre> <p>If I type "import unittest" and then "import sqlite3 as sqlite" I get:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "/home/myname/opt/lib/python2.6/sqlite3/__init__.py", line 24, in &lt;module&gt; from dbapi2 import * File "/home/myname/opt/lib/python2.6/sqlite3/dbapi2.py", line 27, in &lt;module&gt; from _sqlite3 import * ImportError: No module named _sqlite3 </code></pre> <p>Thank you in advance.</p>
1
2009-09-24T13:05:49Z
1,473,910
<p>You can use buildout to create localized version of your project. This will install all necessary packages without having sudo access to the server.</p> <p>To give it try, do the following:</p> <pre><code>mkdir tmp cd tmp wget http://svn.zope.org/*checkout*/zc.buildout/trunk/bootstrap/bootstrap.py python bootstrap.py init vim buildout.cfg </code></pre> <p>edit buildout.cfg and replace it with following:</p> <pre><code>[buildout] parts = sqlite [sqlite] recipe = zc.recipe.egg eggs = pysqlite interpreter = mypython </code></pre> <p>Now, run ./bin/buildout to rebuild the project. This will download all of the necessary packages and create a new interpreter for you that you can use test that you can access sqlite.</p> <pre><code>./bin/buildout ./bin/mypython &gt;&gt;&gt; import sqlite3 </code></pre> <p>This gives you a controlled environment that you can use to develop inside of. To learn more about buildout, you can watch videos from pycon 2009 on Setuptools, Distutils and Buildout.</p> <p><a href="http://pycon.blip.tv/file/2061520/" rel="nofollow">Eggs and Buildout Deployment in Python - Part 1</a></p> <p><a href="http://pycon.blip.tv/file/2061678/" rel="nofollow">Eggs and Buildout Deployment in Python - Part 2</a> </p> <p><a href="http://pycon.blip.tv/file/2061724/" rel="nofollow">Eggs and Buildout Deployment in Python - Part 3</a></p> <p>Good luck</p>
2
2009-09-24T20:17:23Z
[ "python", "sqlite", "rpm", "pysqlite" ]
making HTTP authentication optional with mod-python
1,471,602
<p>I've a web application that accesses multiple controller classes based on the parameters it is passed. For some of the controllers, I want users to authenticate themselves (by simple HTTP authentication), and for some I want public access.</p> <p>Is there a way to make this happen? In my .htaccess file, I now have</p> <pre><code>AddHandler mod_python .py PythonHandler handler PythonAuthenHandler handler PythonDebug On AuthType Basic AuthName "My Realm" AuthBasicAuthoritative Off require valid-user </code></pre> <p>The authenhandler is called correctly, but even when I just do</p> <pre><code>def authenhandler(req): return apache.OK </code></pre> <p>the user is asked for a password (though any password that is entered is accepted)</p> <p>I tried removing the Auth* stuff (and the require directive) from the .htaccess entirely, and just did the following in the normal handler for those cases where I <em>do</em> want authentication (and it was not found):</p> <pre><code>request.err_headers_out.add('WWW-Authenticate', 'Basic realm="My Realm") return apache.HTTP_UNAUTHORIZED </code></pre> <p>which is what I understand what the server should do when not receiving correct authentication. That did not work either, however.</p> <p>I come from a PHP background and I know that the latter is how it's done in PHP - but PHP sometimes does extra little pieces of undocumented magic to make this stuff actually work. Is this one of those cases? </p> <p>Is there any way to optionally request authentication, depending on the URL passed, from the same handler?</p>
1
2009-09-24T13:10:42Z
6,150,509
<p>There are a couple ways to specify authentication scope with Apache, the one most people are used to is gt;Directorylt; based - i.e. anything in or below a directory gets authenticated against htpasswd.</p> <p>There's also gt;Locationlt;, which applies directives to content that live outside the filesystem such as mod_python registered code.</p> <p>This is how you can set authentication on a 'virtual' path like <strong>/status</strong>, if you have mod_status enabled.</p> <p>You can do the same thing with mod_python paths</p> <pre><code>&lt;Location /python/app1/&gt; Order allow,deny Allow from all &lt;/Location&gt; &lt;Location /python/app2/&gt; Order allow,deny Allow from all AuthType basic AuthName "Protected Intranet Area" AuthUserFile /etc/apache2/htpasswd Require valid-user &lt;/Location&gt; </code></pre> <p>I should add - it's not necessarily clear if you mean 'some users should authenticate with a username and password and other users should only have to put in a username'</p> <p><em>or</em></p> <p>'some applications should require authentication 100% of the time, and other applications should be freely available 100% of the time'</p> <p>My first answer sorts out the last query.</p>
1
2011-05-27T09:46:44Z
[ "python", "apache", "authentication", "mod-python" ]
Copying modules into Django, "No module named [moduleName]"
1,471,707
<p>I run into this problem pretty consistently... keep in mind I am quite new to Django and a total Python amateur.</p> <p>It seems that, for example, whenever I check out my Django project on a new computer after a clean install of Python and Django, it can never find the project/apps I create or copy in.</p> <p>So right now I have an app that is working, and I downloaded a 3rd party Django module and installed it into my app directory, include it in my settings, and the web server quits because it cannot find the module.</p> <p>This is the first time I've imported an third party module. In the past when it couldn't find modules I created, I would just rename the folder and run "manage.py startapp appname", delete the folder it created, and name my original folder back, boom, problem solved...</p> <p>But that's obviously a hack, I am wondering if anyone can explain the the heck is going on here and how best to approach it.</p> <p>I can't be the only one who has run into this, but I couldn't find any other questions on this site that seemed to match my issue.</p> <p>Happens on both OS X and Windows 7.</p>
0
2009-09-24T13:32:10Z
1,471,945
<p>Your third party django module should be searchable by PYTHONPATH, because django module is no other than a python module. Now there are two ways to do this:</p> <ol> <li><p>Create a folder (anywhere you want), put your third party django module under there. Now set that directory to environment variable $PYTHONPATH e.g (on Linux box): </p> <p>export PYTHONPATH = /home/me/pythonmodules/</p></li> <li><p>Create a folder (anywhere you want), put the third party django module under there. Now if you are on Unix box, create a <a href="http://en.wikipedia.org/wiki/Symbolic%5Flink" rel="nofollow">symlink</a> to that directory to python site-packages. Use this command to find out where your python site packages is:</p> <p>python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"</p></li> </ol>
0
2009-09-24T14:10:21Z
[ "python", "django" ]
Copying modules into Django, "No module named [moduleName]"
1,471,707
<p>I run into this problem pretty consistently... keep in mind I am quite new to Django and a total Python amateur.</p> <p>It seems that, for example, whenever I check out my Django project on a new computer after a clean install of Python and Django, it can never find the project/apps I create or copy in.</p> <p>So right now I have an app that is working, and I downloaded a 3rd party Django module and installed it into my app directory, include it in my settings, and the web server quits because it cannot find the module.</p> <p>This is the first time I've imported an third party module. In the past when it couldn't find modules I created, I would just rename the folder and run "manage.py startapp appname", delete the folder it created, and name my original folder back, boom, problem solved...</p> <p>But that's obviously a hack, I am wondering if anyone can explain the the heck is going on here and how best to approach it.</p> <p>I can't be the only one who has run into this, but I couldn't find any other questions on this site that seemed to match my issue.</p> <p>Happens on both OS X and Windows 7.</p>
0
2009-09-24T13:32:10Z
1,472,013
<p>They way Django works is pretty much how Python works. At default the folder you create when you run django-admin.py startproject name is added to your python path. That means that anything you put into there you can get to. But you have to mind that when you write the app into the installed app list. If you have an app at project/apps/appname, you would have to write <code>'app.appname'</code> in the installed apps list.</p> <p>Now there are some ways to go about adding 3rd party apps located somewhere else to your project. You can either add them to your python path, put in your python path, or make a link to your python path. However, you can also add a <code>sys.path.insert(...)</code> in your manage.py file where you add the folder of your liking to your python path. Doing this will allow you to add folders to your python path for that project only, and will keep your python path more clean.</p>
2
2009-09-24T14:19:31Z
[ "python", "django" ]
Small Tables in Python?
1,471,924
<p>Let's say I don't have more than one or two dozen objects with different properties, such as the following:</p> <p>UID, Name, Value, Color, Type, Location</p> <p>I want to be able to call up all objects with Location = "Boston", or Type = "Primary". Classic database query type stuff.</p> <p>Most table solutions (pytables, *sql) are really overkill for such a small set of data. Should I simply iterate over all the objects and create a separate dictionary for each data column (adding values to dictionaries as I add new objects)?</p> <p>This would create dicts like this:</p> <p>{'Boston' : [234, 654, 234], 'Chicago' : [324, 765, 342] } - where those 3 digit entries represent things like UID's.</p> <p>As you can see, querying this would be a bit of a pain. </p> <p>Any thoughts of an alternative?</p>
12
2009-09-24T14:07:17Z
1,472,025
<p>For small relational problems I love using Python's builtin <a href="http://docs.python.org/library/sets.html">sets</a>.</p> <p>For the example of location = 'Boston' OR type = 'Primary', if you had this data:</p> <pre><code>users = { 1: dict(Name="Mr. Foo", Location="Boston", Type="Secondary"), 2: dict(Name="Mr. Bar", Location="New York", Type="Primary"), 3: dict(Name="Mr. Quux", Location="Chicago", Type="Secondary"), #... } </code></pre> <p>You can do the <code>WHERE ... OR ...</code> query like this:</p> <pre><code>set1 = set(u for u in users if users[u]['Location'] == 'Boston') set2 = set(u for u in users if users[u]['Type'] == 'Primary') result = set1.union(set2) </code></pre> <p>Or with just one expression:</p> <pre><code>result = set(u for u in users if users[u]['Location'] == 'Boston' or users[u]['Type'] == 'Primary') </code></pre> <p>You can also use the functions in <a href="http://docs.python.org/library/itertools.html">itertools</a> to create fairly efficient queries of the data. For example if you want to do something similar to a <code>GROUP BY city</code>:</p> <pre><code>cities = ('Boston', 'New York', 'Chicago') cities_users = dict(map(lambda city: (city, ifilter(lambda u: users[u]['Location'] == city, users)), cities)) </code></pre> <p>You could also build indexes manually (build a <code>dict</code> mapping Location to User ID) to speed things up. If this becomes too slow or unwieldy then I would probably switch to <a href="http://docs.python.org/library/sqlite3.html">sqlite</a>, which is now included in the Python (2.5) standard library.</p>
13
2009-09-24T14:21:30Z
[ "python", "table", "lookup-tables" ]
Small Tables in Python?
1,471,924
<p>Let's say I don't have more than one or two dozen objects with different properties, such as the following:</p> <p>UID, Name, Value, Color, Type, Location</p> <p>I want to be able to call up all objects with Location = "Boston", or Type = "Primary". Classic database query type stuff.</p> <p>Most table solutions (pytables, *sql) are really overkill for such a small set of data. Should I simply iterate over all the objects and create a separate dictionary for each data column (adding values to dictionaries as I add new objects)?</p> <p>This would create dicts like this:</p> <p>{'Boston' : [234, 654, 234], 'Chicago' : [324, 765, 342] } - where those 3 digit entries represent things like UID's.</p> <p>As you can see, querying this would be a bit of a pain. </p> <p>Any thoughts of an alternative?</p>
12
2009-09-24T14:07:17Z
1,472,092
<p>If it's really a small amount of data, I'd not bother with an index and probably just write a helper function:</p> <pre><code>users = [ dict(Name="Mr. Foo", Location="Boston", Type="Secondary"), dict(Name="Mr. Bar", Location="New York", Type="Primary"), dict(Name="Mr. Quux", Location="Chicago", Type="Secondary"), ] def search(dictlist, **kwargs): def match(d): for k,v in kwargs.iteritems(): try: if d[k] != v: return False except KeyError: return False return True return [d for d in dictlist if match(d)] </code></pre> <p>Which will allow nice looking queries like this:</p> <pre><code>result = search(users, Type="Secondary") </code></pre>
2
2009-09-24T14:31:39Z
[ "python", "table", "lookup-tables" ]
Small Tables in Python?
1,471,924
<p>Let's say I don't have more than one or two dozen objects with different properties, such as the following:</p> <p>UID, Name, Value, Color, Type, Location</p> <p>I want to be able to call up all objects with Location = "Boston", or Type = "Primary". Classic database query type stuff.</p> <p>Most table solutions (pytables, *sql) are really overkill for such a small set of data. Should I simply iterate over all the objects and create a separate dictionary for each data column (adding values to dictionaries as I add new objects)?</p> <p>This would create dicts like this:</p> <p>{'Boston' : [234, 654, 234], 'Chicago' : [324, 765, 342] } - where those 3 digit entries represent things like UID's.</p> <p>As you can see, querying this would be a bit of a pain. </p> <p>Any thoughts of an alternative?</p>
12
2009-09-24T14:07:17Z
1,472,343
<p>I do not think sqlite would be "overkill" -- it comes with standard Python since 2.5, so no need to install stuff, and it can make and handle databases in either memory or local disk files. Really, how could it be simpler...? If you want everything in-memory including the initial values, and want to use dicts to express those initial values, for example...:</p> <pre><code>import sqlite3 db = sqlite3.connect(':memory:') db.execute('Create table Users (Name, Location, Type)') db.executemany('Insert into Users values(:Name, :Location, :Type)', [ dict(Name="Mr. Foo", Location="Boston", Type="Secondary"), dict(Name="Mr. Bar", Location="New York", Type="Primary"), dict(Name="Mr. Quux", Location="Chicago", Type="Secondary"), ]) db.commit() db.row_factory = sqlite3.Row </code></pre> <p>and now your in-memory tiny "db" is ready to go. It's no harder to make a DB in a disk file and/or read the initial values from a text file, a CSV, and so forth, of course.</p> <p>Querying is especially flexible, easy and sweet, e.g., you can mix string insertion and parameter substitution at will...:</p> <pre><code>def where(w, *a): c = db.cursor() c.execute('Select * From Users where %s' % w, *a) return c.fetchall() print [r["Name"] for r in where('Type="Secondary"')] </code></pre> <p>emits <code>[u'Mr. Foo', u'Mr. Quux']</code>, just like the more elegant but equivalent</p> <pre><code>print [r["Name"] for r in where('Type=?', ["Secondary"])] </code></pre> <p>and your desired query's just:</p> <pre><code>print [r["Name"] for r in where('Location="Boston" or Type="Primary"')] </code></pre> <p>etc. Seriously -- what's not to like?</p>
5
2009-09-24T15:11:08Z
[ "python", "table", "lookup-tables" ]
How do I parse an HTTP date-string in Python?
1,471,987
<p>Is there an easy way to parse HTTP date-strings in Python? According to <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3">the standard</a>, there are several ways to format HTTP date strings; the method should be able to handle this.</p> <p>In other words, I want to convert a string like "Wed, 23 Sep 2009 22:15:29 GMT" to a python time-structure.</p>
27
2009-09-24T14:15:39Z
1,472,008
<pre><code>&gt;&gt;&gt; import datetime &gt;&gt;&gt; datetime.datetime.strptime('Wed, 23 Sep 2009 22:15:29 GMT', '%a, %d %b %Y %H:%M:%S GMT') datetime.datetime(2009, 9, 23, 22, 15, 29) </code></pre>
1
2009-09-24T14:18:53Z
[ "python", "http", "datetime", "parsing" ]
How do I parse an HTTP date-string in Python?
1,471,987
<p>Is there an easy way to parse HTTP date-strings in Python? According to <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3">the standard</a>, there are several ways to format HTTP date strings; the method should be able to handle this.</p> <p>In other words, I want to convert a string like "Wed, 23 Sep 2009 22:15:29 GMT" to a python time-structure.</p>
27
2009-09-24T14:15:39Z
1,472,336
<pre><code>&gt;&gt;&gt; import email.utils as eut &gt;&gt;&gt; eut.parsedate('Wed, 23 Sep 2009 22:15:29 GMT') (2009, 9, 23, 22, 15, 29, 0, 1, -1) </code></pre> <p>If you want a <code>datetime.datetime</code> object, you can do:</p> <pre><code>def my_parsedate(text): return datetime.datetime(*eut.parsedate(text)[:6]) </code></pre>
35
2009-09-24T15:10:31Z
[ "python", "http", "datetime", "parsing" ]
How do I parse an HTTP date-string in Python?
1,471,987
<p>Is there an easy way to parse HTTP date-strings in Python? According to <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3">the standard</a>, there are several ways to format HTTP date strings; the method should be able to handle this.</p> <p>In other words, I want to convert a string like "Wed, 23 Sep 2009 22:15:29 GMT" to a python time-structure.</p>
27
2009-09-24T14:15:39Z
21,888,767
<pre><code>httplib.HTTPMessage(filehandle).getdate(headername) httplib.HTTPMessage(filehandle).getdate_tz(headername) mimetools.Message(filehandle).getdate() rfc822.parsedate(datestr) rfc822.parsedate_tz(datestr) </code></pre> <ul> <li>if you have a raw data stream, you can build an HTTPMessage or a mimetools.Message from it. it may offer additional help while querying the response object for infos</li> <li>if you are using urllib2, you already have an HTTPMessage object hidden in the filehandler returned by urlopen</li> <li>it can probably parse many date formats</li> <li>httplib is in the core</li> </ul> <p>NOTE: </p> <ul> <li>had a look at implementation, HTTPMessage inherits from mimetools.Message which inherits from rfc822.Message. two floating defs are of your interest maybe, parsedate and parsedate_tz (in the latter)</li> <li>parsedate(_tz) from email.utils has a different implementation, although it looks kind of the same.</li> </ul> <p>you can do this, if you only have that piece of string and you want to parse it:</p> <pre><code>&gt;&gt;&gt; from rfc822 import parsedate, parsedate_tz &gt;&gt;&gt; parsedate('Wed, 23 Sep 2009 22:15:29 GMT') (2009, 9, 23, 22, 15, 29, 0, 1, 0) &gt;&gt;&gt; </code></pre> <p>but let me exemplify through mime messages:</p> <pre><code>import mimetools import StringIO message = mimetools.Message( StringIO.StringIO('Date:Wed, 23 Sep 2009 22:15:29 GMT\r\n\r\n')) &gt;&gt;&gt; m &lt;mimetools.Message instance at 0x7fc259146710&gt; &gt;&gt;&gt; m.getdate('Date') (2009, 9, 23, 22, 15, 29, 0, 1, 0) </code></pre> <p>or via http messages (responses)</p> <pre><code>&gt;&gt;&gt; from httplib import HTTPMessage &gt;&gt;&gt; from StringIO import StringIO &gt;&gt;&gt; http_response = HTTPMessage(StringIO('Date:Wed, 23 Sep 2009 22:15:29 GMT\r\n\r\n')) &gt;&gt;&gt; #http_response can be grabbed via urllib2.urlopen(url).info(), right? &gt;&gt;&gt; http_response.getdate('Date') (2009, 9, 23, 22, 15, 29, 0, 1, 0) </code></pre> <p>right?</p> <pre><code>&gt;&gt;&gt; import urllib2 &gt;&gt;&gt; urllib2.urlopen('https://fw.io/').info().getdate('Date') (2014, 2, 19, 18, 53, 26, 0, 1, 0) </code></pre> <p>there, now we now more about date formats, mime messages, mime tools and their pythonic implementation ;-)</p> <p>whatever the case, looks better than using email.utils for parsing http headers.</p>
1
2014-02-19T18:07:52Z
[ "python", "http", "datetime", "parsing" ]
What is setup.py?
1,471,994
<p>Can anyone please explain, what is <code>setup.py</code> and how can it be configured or used?</p>
285
2009-09-24T14:16:52Z
1,472,014
<p>setup.py is a python file, which usually tells you that the module/package you are about to install have been packaged and distributed with Distutils, which is the standard for distributing Python Modules.</p> <p>This allows you to easily install Python packages, often it's enough to write:</p> <pre><code>python setup.py install </code></pre> <p>and the module will install itself.</p> <p><a href="http://docs.python.org/install/index.html">http://docs.python.org/install/index.html</a></p>
202
2009-09-24T14:19:35Z
[ "python", "setup.py", "pypi", "python-packaging" ]
What is setup.py?
1,471,994
<p>Can anyone please explain, what is <code>setup.py</code> and how can it be configured or used?</p>
285
2009-09-24T14:16:52Z
1,472,029
<p>If you downloaded package that has "setup.py" in root folder, you can install it by running</p> <pre><code>python setup.py install </code></pre> <p>If you are developing a project and are wondering what this file is useful for, check <a href="http://docs.python.org/distutils/setupscript.html">Python documentation on writing the Setup Script</a></p>
36
2009-09-24T14:21:46Z
[ "python", "setup.py", "pypi", "python-packaging" ]
What is setup.py?
1,471,994
<p>Can anyone please explain, what is <code>setup.py</code> and how can it be configured or used?</p>
285
2009-09-24T14:16:52Z
1,472,031
<p><code>setup.py</code> is a Python script that is usually shipped with libraries or programs, written in that language. It's purpose is the correct installation of the software.</p> <p>Many packages use the <code>distutils</code> framework in conjuction with <code>setup.py</code>.</p> <p><a href="http://docs.python.org/distutils/">http://docs.python.org/distutils/</a></p>
14
2009-09-24T14:21:58Z
[ "python", "setup.py", "pypi", "python-packaging" ]
What is setup.py?
1,471,994
<p>Can anyone please explain, what is <code>setup.py</code> and how can it be configured or used?</p>
285
2009-09-24T14:16:52Z
1,472,439
<p><code>setup.py</code> is Python's answer to a multi-platform installer and <code>make</code> file. </p> <p>If you’re familiar with command line installations, then <code>make &amp;&amp; make install</code> translates to <code>python setup.py build &amp;&amp; python setup.py install</code>. </p> <p>Some packages are pure Python, and are only byte compiled. Others may contain native code, which will require a native compiler (like <code>gcc</code> or <code>cl</code>) and a Python interfacing module (like <code>swig</code> or <code>pyrex</code>).</p>
43
2009-09-24T15:29:09Z
[ "python", "setup.py", "pypi", "python-packaging" ]
What is setup.py?
1,471,994
<p>Can anyone please explain, what is <code>setup.py</code> and how can it be configured or used?</p>
285
2009-09-24T14:16:52Z
16,088,409
<p>setup.py can be used in two scenarios , First, you want to install a Python package. Second, you want to create your own Python package. Usually standard Python package has couple of important files like setup.py, setup.cfg and Manifest.in. When you are creating the Python package, these three files will determine the (content in PKG-INFO under egg-info folder) name, version, description, other required installations (usually in .txt file) and few other parameters. setup.cfg is read by setup.py while package is created (could be tar.gz ). Manifest.in is where you can define what should be included in your package. Anyways you can do bunch of stuff using setup.py like </p> <pre><code>python setup.py build python setup.py install python setup.py sdist &lt;distname&gt; upload [-r urltorepo] (to upload package to pypi or local repo) </code></pre> <p>There are bunch of other commands which could be used with setup.py . for help </p> <pre><code>python setup.py --help-commands </code></pre>
9
2013-04-18T16:29:38Z
[ "python", "setup.py", "pypi", "python-packaging" ]
What is setup.py?
1,471,994
<p>Can anyone please explain, what is <code>setup.py</code> and how can it be configured or used?</p>
285
2009-09-24T14:16:52Z
18,870,208
<p>When you download a package with <code>setup.py</code> open your Terminal (Mac,Linux) or Command Prompt (Windows). Using <code>cd</code> and helping you with Tab button set the path right to the folder where you have downloaded the file and where there is <code>setup.py</code> :</p> <pre><code>iMac:~ user $ cd path/pakagefolderwithsetupfile/ </code></pre> <p>Press enter, you should see something like this:</p> <pre><code>iMac:pakagefolderwithsetupfile user$ </code></pre> <p>Then type after this <code>python setup.py install</code> :</p> <pre><code>iMac:pakagefolderwithsetupfile user$ python setup.py install </code></pre> <p>Press <code>enter</code>. Done!</p>
4
2013-09-18T10:49:14Z
[ "python", "setup.py", "pypi", "python-packaging" ]
What is setup.py?
1,471,994
<p>Can anyone please explain, what is <code>setup.py</code> and how can it be configured or used?</p>
285
2009-09-24T14:16:52Z
23,998,536
<p>To install a Python package you've downloaded, you extract the archive and run the setup.py script inside:</p> <pre><code>python setup.py install </code></pre> <p>To me, this has always felt odd. It would be more natural to point a package manager at the download, as one would do in Ruby and Nodejs, eg. <code>gem install rails-4.1.1.gem</code></p> <p>A package manager is more comfortable too, because it's familiar and reliable. On the other hand, each <code>setup.py</code> is novel, because it's specific to the package. It demands faith in convention "I trust this setup.py takes the same commands as others I have used in the past". That's a regrettable tax on mental willpower. </p> <p>I'm not saying the setup.py workflow is less secure than a package manager (I understand Pip just runs the setup.py inside), but certainly I feel it's awkard and jarring. There's a harmony to commands all being to the same package manager application. You might even grow fond it.</p>
5
2014-06-02T15:52:36Z
[ "python", "setup.py", "pypi", "python-packaging" ]
What is setup.py?
1,471,994
<p>Can anyone please explain, what is <code>setup.py</code> and how can it be configured or used?</p>
285
2009-09-24T14:16:52Z
39,811,884
<p>It helps to install a python package <code>foo</code> on your machine (can also be in <code>virtualenv</code>) so that you can import the package <code>foo</code> from other projects and also from Python prompt. </p> <p><strong><em>It does the similar job of <code>pip</code>, <code>easy_install</code> etc.,</em></strong></p> <hr> <p><strong>Using <code>setup.py</code></strong> </p> <p>Let's start with some definitions.</p> <p><em>Package</em> - A folder/directory that contains <code>__init__.py</code> file.<br> <em>Module</em> - A valid python file with <code>.py</code> extension.<br> <em>Distribution</em> - How one package relates to others. </p> <p>Let's say you want to install a package named <code>foo</code>. Then you do, </p> <pre><code>$ git clone https://github.com/user/foo $ cd foo $ python setup.py install </code></pre> <p>Instead, if you don't want to actually install it but still would like to use it. Then do, </p> <pre><code>$ python setup.py develop </code></pre> <p>This command will create symlinks to the source directory within site-packages instead of copying things. Because of this, it is quite fast (particularly for large packages). </p> <hr> <p><strong>Creating <code>setup.py</code></strong> </p> <p>If you have your package tree like, </p> <pre><code>foo ├── foo │   ├── data_struct.py │   ├── __init__.py │   └── internals.py ├── README ├── requirements.txt └── setup.py </code></pre> <p>Then, you do the following so that it can be installed on some machine: </p> <pre><code>from setuptools import setup setup( name='foo', version='1.0', description='A useful module', author='Man Foo', author_email='foomail@foo.com', packages=['foo'], #same as name install_requires=['bar', 'greek'], #external packages as dependencies ) </code></pre> <p>Instead if your package tree is more complex like: </p> <pre><code>foo ├── foo │   ├── data_struct.py │   ├── __init__.py │   └── internals.py ├── README ├── requirements.txt ├── scripts │   ├── cool │   └── skype └── setup.py </code></pre> <p>In this case your <code>setup.py</code> would look be,</p> <pre><code>from setuptools import setup setup( name='foo', version='1.0', description='A useful module', author='Man Foo', author_email='foomail@foo.com', packages=['foo'], #same as name install_requires=['bar', 'greek'], #external packages as dependencies scripts=[ 'scripts/cool', 'scripts/skype', ] ) </code></pre> <hr> <p><strong>Add more stuff to (<code>setup.py</code>)</strong> &amp; make it decent:</p> <pre><code>from setuptools import setup with open("README", 'r') as f: long_description = f.read() setup( name='foo', version='1.0', description='A useful module', license="MIT", long_description=long_description, author='Man Foo', author_email='foomail@foo.com', url="http://www.foopackage.com/", packages=['foo'], #same as name install_requires=['bar', 'greek'], #external packages as dependencies scripts=[ 'scripts/cool', 'scripts/skype', ] ) </code></pre> <p>The <code>long_description</code> is used in pypi.org as the README description of your package. </p> <hr> <p>And, you're ready to upload your package to <a href="http://pypi.org" rel="nofollow">PyPi.org</a> so that others can install your package using <code>pip install yourpackage</code>. </p> <p>First step is to claim your package name &amp; space in pypi using:</p> <pre><code>$ python setup.py register </code></pre> <p>Once registered, nobody can use your package name. After this, you have to upload your package there (to the cloud) by,</p> <pre><code>$ python setup.py upload </code></pre> <p>Optionally, you can also sign your package with <code>GPG</code> by,</p> <pre><code>$ python setup.py --sign upload </code></pre>
2
2016-10-01T22:04:48Z
[ "python", "setup.py", "pypi", "python-packaging" ]
PyQt4 Highlighting
1,472,044
<p>I'm trying to add some syntax highlighting to a text editor in PyQt4. I've found an example in the documentation which works find when compiled from C++ but when i convert it to Python/PyQt it no longer works.</p> <p>The part of the code that fails (no longer highlights anything) is:</p> <pre><code>def highlightCurrentLine(self): extraSelections = [] if not self.isReadOnly(): selection = QTextEdit.ExtraSelection() lineColor = QColor(Qt.yellow).lighter(160) selection.format.setBackground(lineColor) selection.format.setProperty(QTextFormat.FullWidthSelection, QVariant(True)) selection.cursor = self.textCursor() selection.cursor.clearSelection() extraSelections.append(selection) self.setExtraSelections(extraSelections) </code></pre> <p>which is called by:</p> <pre><code>self.connect(self, SIGNAL('cursorPositionChanged()'), self.highlightCurrentLine) </code></pre> <p>Anyone have any idea why this doesn't work?</p> <p>The versions i am usuing are: Python 2.6.2, PyQt 4.4.4</p>
2
2009-09-24T14:24:48Z
1,472,288
<p>Save <code>lineColor</code> somewhere (like <code>self.lineColor</code>). Otherwise, Python will discard the object when the method returns and the <code>format</code> will use an illegal pointer.</p>
0
2009-09-24T15:02:02Z
[ "python", "qt4", "pyqt4" ]
PyQt4 Highlighting
1,472,044
<p>I'm trying to add some syntax highlighting to a text editor in PyQt4. I've found an example in the documentation which works find when compiled from C++ but when i convert it to Python/PyQt it no longer works.</p> <p>The part of the code that fails (no longer highlights anything) is:</p> <pre><code>def highlightCurrentLine(self): extraSelections = [] if not self.isReadOnly(): selection = QTextEdit.ExtraSelection() lineColor = QColor(Qt.yellow).lighter(160) selection.format.setBackground(lineColor) selection.format.setProperty(QTextFormat.FullWidthSelection, QVariant(True)) selection.cursor = self.textCursor() selection.cursor.clearSelection() extraSelections.append(selection) self.setExtraSelections(extraSelections) </code></pre> <p>which is called by:</p> <pre><code>self.connect(self, SIGNAL('cursorPositionChanged()'), self.highlightCurrentLine) </code></pre> <p>Anyone have any idea why this doesn't work?</p> <p>The versions i am usuing are: Python 2.6.2, PyQt 4.4.4</p>
2
2009-09-24T14:24:48Z
1,505,829
<p>Ok... turns out i wasn't going mad, i was just using an out of date version of PyQt4.</p> <p>For information the version of PyQt4 that ships with Ubuntu 9.04 is 4.4.4 but this functionality seems to require 4.5+.</p> <p>I've upgraded to PyQt4 4.6 and it works fine (plus 4.6 seems to have some nice new functionality too).</p>
1
2009-10-01T19:02:20Z
[ "python", "qt4", "pyqt4" ]
regex for triple quote
1,472,047
<p>What regex will find the triple quote comments (possibly multi-line) in a Python source code?</p>
3
2009-09-24T14:26:01Z
1,472,080
<pre><code>re.findall('(?:\n[\t ]*)\"{3}(.*?)\"{3}', s, re.M | re.S) </code></pre> <p>captures only text within triple quotes that are at the begging of a line and could be preceded by spaces, tabs or nothing, as python docstrings should be.</p>
5
2009-09-24T14:29:57Z
[ "python", "regex" ]
regex for triple quote
1,472,047
<p>What regex will find the triple quote comments (possibly multi-line) in a Python source code?</p>
3
2009-09-24T14:26:01Z
1,472,390
<p>Python is not a regular language and cannot reliably be parsed using regex.</p> <p>If you want a proper Python parser, look at the <a href="http://docs.python.org/library/ast.html" rel="nofollow">ast</a> module. You may be looking for <code>get_docstring</code>.</p>
10
2009-09-24T15:20:41Z
[ "python", "regex" ]
regex for triple quote
1,472,047
<p>What regex will find the triple quote comments (possibly multi-line) in a Python source code?</p>
3
2009-09-24T14:26:01Z
1,491,525
<p>I've found this one from Tim Peters (I think) :</p> <pre><code>pat = """ qqq [^\\q]* ( ( \\\\[\000-\377] | q ( \\\\[\000-\377] | [^\\q] | q ( \\\\[\000-\377] | [^\\q] ) ) ) [^\\q]* )* qqq """ pat = ''.join(pat.split(), '') tripleQuotePat = pat.replace("q", "'") + "|" + pat.replace('q', '"') </code></pre> <p>But, as stated by bobince, regex alone doesn't seem to be the right tool for parsing Python code.<br> So I went with <strong>tokenize</strong> from the standard library.</p>
0
2009-09-29T09:36:13Z
[ "python", "regex" ]
regex for triple quote
1,472,047
<p>What regex will find the triple quote comments (possibly multi-line) in a Python source code?</p>
3
2009-09-24T14:26:01Z
8,798,548
<p>I find this to be working perfectly for me (used it with TextMate):</p> <pre><code>"{3}([\s\S]*?"{3}) </code></pre> <p>I wanted to remove all comments from a library and this took care of the triple-quote comments (single or multi-line, regardless of where they started on the line).</p> <p>For hash comments (much easier), this works:</p> <pre><code>#.*$ </code></pre> <p>I used these with TextMate, which uses the Oniguruma regular expression library by K. Kosako (http://manual.macromates.com/en/regular_expressions)</p>
2
2012-01-10T04:25:57Z
[ "python", "regex" ]
What is the Python equivalent of application & session scope variables?
1,472,279
<p>Recently started on python, wondered what the equivalent object was for storing session &amp; application scope data?</p> <p>I'm using Google App Engine too so if it has any extra features (can't seem to find any immediate references myself) that would be useful</p>
0
2009-09-24T14:59:59Z
1,472,345
<p>I assume you're talking about a web session, used to retain state between http requests. Python is a general programming language and by itself doesn't contain the concept of a session. </p> <p>However most different python web frameworks have session implementations. Which one are you using? I've linked to the session documentation on some python web frameworks:</p> <ul> <li><a href="http://www.modpython.org/live/current/doc-html/pyapi-sess.html" rel="nofollow">mod_python</a></li> <li><a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/#topics-http-sessions" rel="nofollow">django</a></li> <li><a href="http://pythonpaste.org/modules/session.html" rel="nofollow">paste</a></li> <li><a href="http://webpy.org/sessions" rel="nofollow">web.py</a></li> </ul>
0
2009-09-24T15:11:32Z
[ "python", "session", "scope", "web-applications" ]
How can I link against libpython.a such the runtime linker can find all the symbols in libpython.a?
1,472,828
<p>In a sequel question to <a href="http://stackoverflow.com/questions/1469370/why-cant-i-import-the-math-library-when-embedding-python-in-c">this question</a>, my corporate environment lacks the <code>libpython2.6.so</code> shared object but has the <code>libpython2.6.a</code> file. Is there a way that I can compile in <code>libpython2.6.a</code> while retaining the symbols in <code>libpython2.6.a</code> such that dynamic libraries can find these symbols at runtime?</p> <p>My current compile with the static library looks like:</p> <pre><code>g++ -I/usr/CORP/pkgs/python/2.6.2/include/python2.6 \ ~/tmp.cpp -pthread -lm -ldl -lutil \ /usr/CORP/pkgs/python/2.6.2/lib/python2.6/config/libpython2.6.a \ -o tmp.exe </code></pre> <p>However, if I load a module like 'math', it dies with:</p> <pre><code>undefined symbol: PyInt_FromLong </code></pre>
0
2009-09-24T16:32:25Z
1,472,853
<p>You need to pass <code>--export-dynamic</code> to the linker. So from <code>g++</code> it's...</p> <pre><code>g++ -Wl,--export-dynamic ... </code></pre>
2
2009-09-24T16:36:35Z
[ "python", "gcc", "g++" ]
Why is host aborting connection?
1,472,876
<p>I'm teaching myself Python networking, and I recalled that back when I was teaching myself threading, I came across <a href="http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/">this page</a>, so I copied the scripts, updated them for Python 3.1.1 and ran them. They worked perfectly.</p> <p>Then I made a few modifications. My goal is to do something simple:</p> <ol> <li>The client pickles an integer and sends it to the server.</li> <li>The server receives the pickled integer, unpickles it, doubles it, then pickles it and sends it back to the client.</li> <li>The client receives the pickled (and doubled) integer, unpickles it, and outputs it.</li> </ol> <p>Here's the server:</p> <pre><code>import pickle import socket import threading class ClientThread(threading.Thread): def __init__(self, channel, details): self.channel = channel self.details = details threading.Thread.__init__ ( self ) def run(self): print('Received connection:', self.details[0]) request = self.channel.recv(1024) response = pickle.dumps(pickle.loads(request) * 2) self.channel.send(response) self.channel.close() print('Closed connection:', self.details [ 0 ]) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('', 2727)) server.listen(5) while True: channel, details = server.accept() ClientThread(channel, details).start() </code></pre> <p>And here is the client:</p> <pre><code>import pickle import socket import threading class ConnectionThread(threading.Thread): def run(self): client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('localhost', 2727)) for x in range(10): client.send(pickle.dumps(x)) print('Sent:',str(x)) print('Received:',repr(pickle.loads(client.recv(1024)))) client.close() for x in range(5): ConnectionThread().start() </code></pre> <p>The server runs fine, and when I run the client it successfully connects and starts sending integers and receiving them back doubled as expected. However, very quickly it exceptions out:</p> <pre><code>Exception in thread Thread-2: Traceback (most recent call last): File "C:\Python30\lib\threading.py", line 507, in _bootstrap_inner self.run() File "C:\Users\Imagist\Desktop\server\client.py", line 13, in run print('Received:',repr(pickle.loads(client.recv(1024)))) socket.error: [Errno 10053] An established connection was aborted by the softwar e in your host machine </code></pre> <p>The server continues to run and receives connections just fine; only the client crashes. What's causing this?</p> <p>EDIT: I got the client working with the following code:</p> <pre><code>import pickle import socket import threading class ConnectionThread(threading.Thread): def run(self): for x in range(10): client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('localhost', 2727)) client.send(pickle.dumps(x)) print('Sent:',str(x)) print('Received:',repr(pickle.loads(client.recv(1024)))) client.close() for x in range(5): ConnectionThread().start() </code></pre> <p>However, I still don't understand what's going on. Isn't this just opening and closing the socket a bunch of times? Shouldn't there be time limitations to that (you shouldn't be able to open a socket so soon after closing it)?</p>
7
2009-09-24T16:44:28Z
1,474,829
<p>That's not how you learn python networking programming. Nobody doing anything serious will ever program like that, so you're learning how to NOT do python networking programming.</p> <ol> <li>Sockets are too low-level, and python is a high-level language. Then, to do python network programming, in a pythonic way, you want to avoid dealing with sockets entirely, and leave that to some module or package. If you want to learn how the low-level stuff works, studying the existing implementations is essential anyway, so learning a <a href="http://twistedmatrix.com/" rel="nofollow">high-level library</a> is essential.</li> <li><code>pickle</code> isn't really how you serialize python objects to send them down the wire. They are a potential security issue you're intoducing, since you can make a fake pickled packet that executes arbritary code when unpickled. It's better to use a safe serializing method - since there are many available, like calling <code>str()</code> on the integer object and <code>int()</code> on the other side.</li> <li>To serve/listen to multiple clients at the same time, don't use threading. In particular, never use the "one thread per connection" approach you seem to be using. It doesn't scale as you think. Since using threads is also error-prone and hard to debug, and bring absolutely no advantage to your end results, <a href="http://entitycrisis.blogspot.com/2009/06/python-threading-is-fundamentally.html" rel="nofollow">bringing problems instead</a>, just try to avoid them entirely. Sockets (and thus <a href="http://twistedmatrix.com/" rel="nofollow">higher level libraries</a> as discussed in item 1) can work in a non-blocking mode, where you can operate while other code is running, and that can be done <strong>without using threads</strong>.</li> </ol> <p>I've just seen your comment on the question:</p> <blockquote> <p><em>@leeroy (continued) My goal is to work up to implementing something like this: <a href="http://www.mcwalter.org/technology/java/httpd/tiny/index.html" rel="nofollow">http://www.mcwalter.org/technology/java/httpd/tiny/index.html</a> only in Python</em></p> </blockquote> <p>Well, here's a working implementation:</p> <pre><code>from SimpleHTTPServer import SimpleHTTPRequestHandler as RH from SocketServer import TCPServer print "serving current directory at port 8000" TCPServer(("", 8000), RH).serve_forever() </code></pre>
-11
2009-09-25T00:22:22Z
[ "python", "networking" ]
Why is host aborting connection?
1,472,876
<p>I'm teaching myself Python networking, and I recalled that back when I was teaching myself threading, I came across <a href="http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/">this page</a>, so I copied the scripts, updated them for Python 3.1.1 and ran them. They worked perfectly.</p> <p>Then I made a few modifications. My goal is to do something simple:</p> <ol> <li>The client pickles an integer and sends it to the server.</li> <li>The server receives the pickled integer, unpickles it, doubles it, then pickles it and sends it back to the client.</li> <li>The client receives the pickled (and doubled) integer, unpickles it, and outputs it.</li> </ol> <p>Here's the server:</p> <pre><code>import pickle import socket import threading class ClientThread(threading.Thread): def __init__(self, channel, details): self.channel = channel self.details = details threading.Thread.__init__ ( self ) def run(self): print('Received connection:', self.details[0]) request = self.channel.recv(1024) response = pickle.dumps(pickle.loads(request) * 2) self.channel.send(response) self.channel.close() print('Closed connection:', self.details [ 0 ]) server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.bind(('', 2727)) server.listen(5) while True: channel, details = server.accept() ClientThread(channel, details).start() </code></pre> <p>And here is the client:</p> <pre><code>import pickle import socket import threading class ConnectionThread(threading.Thread): def run(self): client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('localhost', 2727)) for x in range(10): client.send(pickle.dumps(x)) print('Sent:',str(x)) print('Received:',repr(pickle.loads(client.recv(1024)))) client.close() for x in range(5): ConnectionThread().start() </code></pre> <p>The server runs fine, and when I run the client it successfully connects and starts sending integers and receiving them back doubled as expected. However, very quickly it exceptions out:</p> <pre><code>Exception in thread Thread-2: Traceback (most recent call last): File "C:\Python30\lib\threading.py", line 507, in _bootstrap_inner self.run() File "C:\Users\Imagist\Desktop\server\client.py", line 13, in run print('Received:',repr(pickle.loads(client.recv(1024)))) socket.error: [Errno 10053] An established connection was aborted by the softwar e in your host machine </code></pre> <p>The server continues to run and receives connections just fine; only the client crashes. What's causing this?</p> <p>EDIT: I got the client working with the following code:</p> <pre><code>import pickle import socket import threading class ConnectionThread(threading.Thread): def run(self): for x in range(10): client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect(('localhost', 2727)) client.send(pickle.dumps(x)) print('Sent:',str(x)) print('Received:',repr(pickle.loads(client.recv(1024)))) client.close() for x in range(5): ConnectionThread().start() </code></pre> <p>However, I still don't understand what's going on. Isn't this just opening and closing the socket a bunch of times? Shouldn't there be time limitations to that (you shouldn't be able to open a socket so soon after closing it)?</p>
7
2009-09-24T16:44:28Z
1,475,855
<p>Your client is now correct - you want to open the socket send the data, receive the reply and then close the socket.</p> <p>The error original error was caused by the server closing the socket after it sent the first response which caused the client to receive a connection closed message when it tried to send the second message on the same connection.</p> <blockquote> <p>However, I still don't understand what's going on. Isn't this just opening and closing the socket a bunch of times?</p> </blockquote> <p>Yes. This is acceptable, if not the highest performance way of doing things.</p> <blockquote> <p>Shouldn't there be time limitations to that (you shouldn't be able to open a socket so soon after closing it)?</p> </blockquote> <p>You can open a client socket as quickly as you like as every time you open a socket you will get a new local port number, meaning that the connections won't interfere. In the server code above, it will start a new thread for each incoming connection.</p> <p>There are 4 parts to every IP connection (source_address, source_port, destination_address, destination_port) and this quad (as it is known) must change for ever connection. Everything except source_port is fixed for a client socket so that is what the OS changes for you.</p> <p>Opening server sockets is more troublesome - if you want to open a new server socket quickly, your</p> <pre><code>server.bind(('', 2727)) </code></pre> <p>Above then you need to read up on SO_REUSEADDR.</p>
3
2009-09-25T07:13:47Z
[ "python", "networking" ]
select_related does not join columns marked with nulll=True
1,472,974
<p>I have a Django model -</p> <pre><code>class NoticedUser(models.Model): user = models.ForeignKey(User, null=False) text = models.CharField(max_length=255, null=True) photo = models.ForeignKey(Photo, null=True, blank=True) article = models.ForeignKey(Article, null=True, blank=True) date = models.DateTimeField(default=datetime.now) </code></pre> <p>When I try to fetch the objects, i.e. with NoticedUser.objects.all().select_related(), resulting query does not contain joins with 'photo' and 'article' tables. I have looked through the Django sources and it seems that fields containing null=True should result in left join instead of inner join, but I have not found why appropriate left joins do not appear in resulting query. This causes additional queries while displaying related objects, as well as there is no possibility to perform custom joins for 'photo' and 'article' tables used in our project.</p> <p>Actually, joins appear only for fields with null=False, but I cannot change the field definitions.</p> <p>How can I add joins for fields with null=True to resulting query? Django version I use is 1.0.2.</p> <p>Thanks.</p>
2
2009-09-24T17:02:10Z
1,473,114
<p>It doesn't follow these relations by default when using <code>select_related()</code> with no parameters. You have to explicitly specify the names:</p> <pre><code>NoticedUser.objects.all().select_related('article', 'photo') </code></pre>
4
2009-09-24T17:34:50Z
[ "python", "django" ]
open source data mining/text analysis tools in python
1,473,087
<p>I have a database full of reviews of various products. My task is to perform various calculation and "create" another "database/xml-export" with aggregated data. I am thinking of writing command line programs in python to do that. But I know someone have done this before and I know that there is some open source python solution or similar which probably gives lot more interesting "aggregated data" then I can possibly think off. </p> <p>The problem is I don't really know much about this area other then basic data manipulation from command line nor I know what are the terms I should use to even search for this thing.. I am really not looking for some scientific/visualization stuff (not that I don't mind if the tool provides), something simple to start with and gradually see/develop stuff what I need.</p> <p>My only requirement is either the "end aggregated data" be in a database or export as XML file no proprietary stuff. Its a bit robust then my python scripts as I have to deal with "lots" of data across 4 machines. </p> <p>Any hint where should I start my research?</p> <p>Thanks.</p>
2
2009-09-24T17:29:29Z
1,473,123
<p>What kind of analysis are you trying to do?</p> <p>If you're analyzing text take a look at the <a href="http://www.nltk.org/" rel="nofollow">Natural Language Toolkit</a> (NLTK).</p> <p>If you want to index and search the data, take a look at the <a href="http://whoosh.ca/" rel="nofollow">whoosh</a> search engine.</p> <p>Please provide some more detail on what kind of analysis you're looking to do.</p>
1
2009-09-24T17:36:31Z
[ "python", "database", "data-mining", "analyzer" ]
open source data mining/text analysis tools in python
1,473,087
<p>I have a database full of reviews of various products. My task is to perform various calculation and "create" another "database/xml-export" with aggregated data. I am thinking of writing command line programs in python to do that. But I know someone have done this before and I know that there is some open source python solution or similar which probably gives lot more interesting "aggregated data" then I can possibly think off. </p> <p>The problem is I don't really know much about this area other then basic data manipulation from command line nor I know what are the terms I should use to even search for this thing.. I am really not looking for some scientific/visualization stuff (not that I don't mind if the tool provides), something simple to start with and gradually see/develop stuff what I need.</p> <p>My only requirement is either the "end aggregated data" be in a database or export as XML file no proprietary stuff. Its a bit robust then my python scripts as I have to deal with "lots" of data across 4 machines. </p> <p>Any hint where should I start my research?</p> <p>Thanks.</p>
2
2009-09-24T17:29:29Z
1,473,267
<p>Looks like you are looking for a <strong>Data Integration</strong> solution.<br> One suggestion is the open source <a href="http://kettle.pentaho.org/" rel="nofollow">Kettle project</a> part of the <a href="http://www.pentaho.com/products/data%5Fintegration/" rel="nofollow">Pentaho</a> suite.<br> For python, a quick search yielded <a href="http://pydi.sourceforge.net/" rel="nofollow">PyDI</a> and <a href="https://www.snaplogic.org/trac" rel="nofollow">SnapLogic</a></p>
1
2009-09-24T18:06:24Z
[ "python", "database", "data-mining", "analyzer" ]
Django ORM - assigning a raw value to DecimalField
1,473,332
<p>EDIT!!! - The casting of the value to a string seems to work fine when I create a <em>new</em> object, but when I try to edit an existing object, it does not allow it.</p> <p>So I have a decimal field in one of my models of Decimal(3,2)</p> <p>When I query up all these objects and try to set this field:</p> <pre><code>fieldName = 0.85 </code></pre> <p>OR</p> <pre><code>fieldName = .85 </code></pre> <p>It will throw a hissy fit, "Cannot convert float to DecimalField, try converting to a string first"...</p> <p>So then I do:</p> <pre><code>fieldName = str(0.85) </code></pre> <p>same error.</p> <p>I even tried:</p> <pre><code>fieldName = "0.85" </code></pre> <p>Same error. Am I running into some sort of framework bug here, or what? Note that when I actually go into Django Admin and manually edit the objects, it works fine.</p> <p>I am running Django 1.1 on Python 2.6</p>
1
2009-09-24T18:20:58Z
1,473,442
<p>The Django <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#decimalfield" rel="nofollow">DecimalField</a> is "...represented in by a python <a href="http://docs.python.org/library/decimal.html" rel="nofollow">Decimal</a> instance." You might try:</p> <pre><code>&gt;&gt;&gt; obj.fieldName = Decimal("0.85") </code></pre> <p>Behavior may also vary depending on the database backend you are using. With sqlite, I am able to assign string values to DecimalFields in new and existing objects without error.</p>
1
2009-09-24T18:39:29Z
[ "python", "django", "django-models", "casting", "django-orm" ]
Django ORM - assigning a raw value to DecimalField
1,473,332
<p>EDIT!!! - The casting of the value to a string seems to work fine when I create a <em>new</em> object, but when I try to edit an existing object, it does not allow it.</p> <p>So I have a decimal field in one of my models of Decimal(3,2)</p> <p>When I query up all these objects and try to set this field:</p> <pre><code>fieldName = 0.85 </code></pre> <p>OR</p> <pre><code>fieldName = .85 </code></pre> <p>It will throw a hissy fit, "Cannot convert float to DecimalField, try converting to a string first"...</p> <p>So then I do:</p> <pre><code>fieldName = str(0.85) </code></pre> <p>same error.</p> <p>I even tried:</p> <pre><code>fieldName = "0.85" </code></pre> <p>Same error. Am I running into some sort of framework bug here, or what? Note that when I actually go into Django Admin and manually edit the objects, it works fine.</p> <p>I am running Django 1.1 on Python 2.6</p>
1
2009-09-24T18:20:58Z
1,474,216
<pre><code>from decimal import Decimal object.fieldName = Decimal("0.85") </code></pre> <p>or</p> <pre><code>f = 0.85 object.fieldName = Decimal(str(f)) </code></pre>
6
2009-09-24T21:20:21Z
[ "python", "django", "django-models", "casting", "django-orm" ]
How to create a hardlink on attached Volumes on Mac?
1,473,368
<p>os.link is not working for the attached Volumes on Mac.</p> <pre><code>~ $ python Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; os.link("/Volumes/ARCHANA/JULY 09/PRAMANPATRA.doc", "/Volumes/ARCHANA/temp") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; OSError: [Errno 45] Operation not supported &gt;&gt;&gt; </code></pre>
0
2009-09-24T18:28:04Z
1,473,394
<p>What filesystem in on ARCHANA? And are you trying to link to a directory? Not all file systems support hardlinks, and very few support hardlinks to directories.</p> <p>In particular USB mass-storage devices are generally formatted as with FAT filesystems which do not support links.</p>
1
2009-09-24T18:32:15Z
[ "python", "osx" ]
How to create a hardlink on attached Volumes on Mac?
1,473,368
<p>os.link is not working for the attached Volumes on Mac.</p> <pre><code>~ $ python Python 2.6.2 (r262:71600, Apr 16 2009, 09:17:39) [GCC 4.0.1 (Apple Computer, Inc. build 5250)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; import os &gt;&gt;&gt; os.link("/Volumes/ARCHANA/JULY 09/PRAMANPATRA.doc", "/Volumes/ARCHANA/temp") Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; OSError: [Errno 45] Operation not supported &gt;&gt;&gt; </code></pre>
0
2009-09-24T18:28:04Z
1,473,431
<p>You're working on a mac, yet the volume ARCHANA might not have a link-able file system. (The uppercase label makes it suspicious.)</p> <p>Also, you are trying to refer a hard link to a directory and "Hard links may not normally refer to directories and may not span file systems." (from the man page.)</p> <p>One last thing to try seems the directory name 'July 09'. It might be worth inspecting the os.link function to check that it works with spaces in directory names.</p>
2
2009-09-24T18:37:56Z
[ "python", "osx" ]
django view function code runs after return
1,473,543
<p>I have a django view that looks like...</p> <pre> def add_user(request): if User.objects.get(username__exact = request.POST['username']): context = { 'message': "Username already taken"} return render_to_response("mytemplate.html", context, RequestContext(request)) newUser = User(username="freeandclearusername") newUser.save() #then other code that is related to setting up a new user. </pre> <p>The other code that is related to setting up the user is still ran even if the initial conditional statement fails and the "return render_to_response()" is called.</p> <p>The page is rendered with the correct context but other information is added to the database after the initial return. I thought that the code after the "return render_to_response()" would not run.</p> <p>Can anyone confirm or explain this?</p> <p>UPDATE....</p> <p>Ok so if I add a conditional....</p> <pre><code>def add_user(request): if User.objects.get(username__exact = request.POST['username']): bad_user = True context = { 'message': "Username already taken"} return render_to_response("mytemplate.html", context, RequestContext(request)) newUser = User(username="freeandclearusername") newUser.save() if bad_user != True: #then other code that is related to setting up a new user. context = { 'message': "Username is great!!!!!"} return render_to_response("mytemplate.html", context, RequestContext(request)) </code></pre> <p>This behaves as expected. Also if I remove the RequestConext() it seems to behave correctly as well. </p> <p>Any ideas? I think the problem lies in how I'm using RequestContext.</p>
0
2009-09-24T18:56:09Z
1,473,571
<p>The return statement will indeed terminate the function. So if you see other code being executed, you either</p> <ul> <li>don't execute the return statement, and thus produce the output somehow differently, or</li> <li>have other code (before the function is called, or in a middleware) that makes the database changes.</li> </ul>
1
2009-09-24T19:01:50Z
[ "python", "django", "views" ]
django view function code runs after return
1,473,543
<p>I have a django view that looks like...</p> <pre> def add_user(request): if User.objects.get(username__exact = request.POST['username']): context = { 'message': "Username already taken"} return render_to_response("mytemplate.html", context, RequestContext(request)) newUser = User(username="freeandclearusername") newUser.save() #then other code that is related to setting up a new user. </pre> <p>The other code that is related to setting up the user is still ran even if the initial conditional statement fails and the "return render_to_response()" is called.</p> <p>The page is rendered with the correct context but other information is added to the database after the initial return. I thought that the code after the "return render_to_response()" would not run.</p> <p>Can anyone confirm or explain this?</p> <p>UPDATE....</p> <p>Ok so if I add a conditional....</p> <pre><code>def add_user(request): if User.objects.get(username__exact = request.POST['username']): bad_user = True context = { 'message': "Username already taken"} return render_to_response("mytemplate.html", context, RequestContext(request)) newUser = User(username="freeandclearusername") newUser.save() if bad_user != True: #then other code that is related to setting up a new user. context = { 'message': "Username is great!!!!!"} return render_to_response("mytemplate.html", context, RequestContext(request)) </code></pre> <p>This behaves as expected. Also if I remove the RequestConext() it seems to behave correctly as well. </p> <p>Any ideas? I think the problem lies in how I'm using RequestContext.</p>
0
2009-09-24T18:56:09Z
1,473,743
<p>You are correct, assuming your conditions are met, the view will exit on your return statement. The only other thing I can think of that hasn't already been mentioned is indentation -- double-check that you do not have a mix of tabs and spaces. That can sometimes result in the unexpected.</p>
0
2009-09-24T19:35:33Z
[ "python", "django", "views" ]
Writing unicode strings via sys.stdout in Python
1,473,577
<p>Assume for a moment that one cannot use <code>print</code> (and thus enjoy the benefit of automatic encoding detection). So that leaves us with <code>sys.stdout</code>. However, <code>sys.stdout</code> is so dumb as to <a href="http://bugs.python.org/issue4947" rel="nofollow">not do any sensible encoding</a>.</p> <p>Now one reads the Python wiki page <a href="http://wiki.python.org/moin/PrintFails" rel="nofollow">PrintFails</a> and goes to try out the following code:</p> <pre><code>$ python -c 'import sys, codecs, locale; print str(sys.stdout.encoding); \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); </code></pre> <p>However this too does not work (at least on Mac). Too see why:</p> <pre><code>&gt;&gt;&gt; import locale &gt;&gt;&gt; locale.getpreferredencoding() 'mac-roman' &gt;&gt;&gt; sys.stdout.encoding 'UTF-8' </code></pre> <p>(UTF-8 is what one's terminal understands).</p> <p>So one changes the above code to:</p> <pre><code>$ python -c 'import sys, codecs, locale; print str(sys.stdout.encoding); \ sys.stdout = codecs.getwriter(sys.stdout.encoding)(sys.stdout); </code></pre> <p>And now unicode strings are properly sent to <code>sys.stdout</code> and hence printed properly on the terminal (<code>sys.stdout</code> is attached the terminal).</p> <p>Is this the correct way to write unicode strings in <code>sys.stdout</code> or should I be doing something else?</p> <p><strong>EDIT</strong>: at times--say, when piping the output to <code>less</code>--<code>sys.stdout.encoding</code> will be <code>None</code>. in this case, the above code will fail.</p>
13
2009-09-24T19:02:35Z
1,473,764
<p>It's not clear to my why you wouldn't be able to do print; but assuming so, yes, the approach looks right to me.</p>
3
2009-09-24T19:40:07Z
[ "python", "unicode", "osx", "terminal", "stdout" ]
Writing unicode strings via sys.stdout in Python
1,473,577
<p>Assume for a moment that one cannot use <code>print</code> (and thus enjoy the benefit of automatic encoding detection). So that leaves us with <code>sys.stdout</code>. However, <code>sys.stdout</code> is so dumb as to <a href="http://bugs.python.org/issue4947" rel="nofollow">not do any sensible encoding</a>.</p> <p>Now one reads the Python wiki page <a href="http://wiki.python.org/moin/PrintFails" rel="nofollow">PrintFails</a> and goes to try out the following code:</p> <pre><code>$ python -c 'import sys, codecs, locale; print str(sys.stdout.encoding); \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); </code></pre> <p>However this too does not work (at least on Mac). Too see why:</p> <pre><code>&gt;&gt;&gt; import locale &gt;&gt;&gt; locale.getpreferredencoding() 'mac-roman' &gt;&gt;&gt; sys.stdout.encoding 'UTF-8' </code></pre> <p>(UTF-8 is what one's terminal understands).</p> <p>So one changes the above code to:</p> <pre><code>$ python -c 'import sys, codecs, locale; print str(sys.stdout.encoding); \ sys.stdout = codecs.getwriter(sys.stdout.encoding)(sys.stdout); </code></pre> <p>And now unicode strings are properly sent to <code>sys.stdout</code> and hence printed properly on the terminal (<code>sys.stdout</code> is attached the terminal).</p> <p>Is this the correct way to write unicode strings in <code>sys.stdout</code> or should I be doing something else?</p> <p><strong>EDIT</strong>: at times--say, when piping the output to <code>less</code>--<code>sys.stdout.encoding</code> will be <code>None</code>. in this case, the above code will fail.</p>
13
2009-09-24T19:02:35Z
1,475,202
<p>Best idea is to check if you are directly connected to a terminal. If you are, use the terminal's encoding. Otherwise, use system preferred encoding. </p> <pre><code>if sys.stdout.isatty(): default_encoding = sys.stdout.encoding else: default_encoding = locale.getpreferredencoding() </code></pre> <p>It's also very important to always allow the user specify whichever encoding she wants. Usually I make it a command-line option (like <code>-e ENCODING</code>), and parse it with the <code>optparse</code> module.</p> <p>Another good thing is to <strong>not</strong> overwrite <code>sys.stdout</code> with an automatic encoder. Create your encoder and use it, but leave <code>sys.stdout</code> alone. You could import 3rd party libraries that write encoded bytestrings directly to <code>sys.stdout</code>.</p>
9
2009-09-25T02:55:36Z
[ "python", "unicode", "osx", "terminal", "stdout" ]
Writing unicode strings via sys.stdout in Python
1,473,577
<p>Assume for a moment that one cannot use <code>print</code> (and thus enjoy the benefit of automatic encoding detection). So that leaves us with <code>sys.stdout</code>. However, <code>sys.stdout</code> is so dumb as to <a href="http://bugs.python.org/issue4947" rel="nofollow">not do any sensible encoding</a>.</p> <p>Now one reads the Python wiki page <a href="http://wiki.python.org/moin/PrintFails" rel="nofollow">PrintFails</a> and goes to try out the following code:</p> <pre><code>$ python -c 'import sys, codecs, locale; print str(sys.stdout.encoding); \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); </code></pre> <p>However this too does not work (at least on Mac). Too see why:</p> <pre><code>&gt;&gt;&gt; import locale &gt;&gt;&gt; locale.getpreferredencoding() 'mac-roman' &gt;&gt;&gt; sys.stdout.encoding 'UTF-8' </code></pre> <p>(UTF-8 is what one's terminal understands).</p> <p>So one changes the above code to:</p> <pre><code>$ python -c 'import sys, codecs, locale; print str(sys.stdout.encoding); \ sys.stdout = codecs.getwriter(sys.stdout.encoding)(sys.stdout); </code></pre> <p>And now unicode strings are properly sent to <code>sys.stdout</code> and hence printed properly on the terminal (<code>sys.stdout</code> is attached the terminal).</p> <p>Is this the correct way to write unicode strings in <code>sys.stdout</code> or should I be doing something else?</p> <p><strong>EDIT</strong>: at times--say, when piping the output to <code>less</code>--<code>sys.stdout.encoding</code> will be <code>None</code>. in this case, the above code will fail.</p>
13
2009-09-24T19:02:35Z
4,027,905
<p>There is an optional environment variable "PYTHONIOENCODING" which may be set to a desired default encoding. It would be one way of grabbing the user-desired encoding in a way consistent with all of Python. It is buried in the Python manual <a href="http://docs.python.org/release/3.1.2/using/cmdline.html?highlight=pythonioencoding">here</a>.</p>
8
2010-10-26T20:50:59Z
[ "python", "unicode", "osx", "terminal", "stdout" ]
Writing unicode strings via sys.stdout in Python
1,473,577
<p>Assume for a moment that one cannot use <code>print</code> (and thus enjoy the benefit of automatic encoding detection). So that leaves us with <code>sys.stdout</code>. However, <code>sys.stdout</code> is so dumb as to <a href="http://bugs.python.org/issue4947" rel="nofollow">not do any sensible encoding</a>.</p> <p>Now one reads the Python wiki page <a href="http://wiki.python.org/moin/PrintFails" rel="nofollow">PrintFails</a> and goes to try out the following code:</p> <pre><code>$ python -c 'import sys, codecs, locale; print str(sys.stdout.encoding); \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); </code></pre> <p>However this too does not work (at least on Mac). Too see why:</p> <pre><code>&gt;&gt;&gt; import locale &gt;&gt;&gt; locale.getpreferredencoding() 'mac-roman' &gt;&gt;&gt; sys.stdout.encoding 'UTF-8' </code></pre> <p>(UTF-8 is what one's terminal understands).</p> <p>So one changes the above code to:</p> <pre><code>$ python -c 'import sys, codecs, locale; print str(sys.stdout.encoding); \ sys.stdout = codecs.getwriter(sys.stdout.encoding)(sys.stdout); </code></pre> <p>And now unicode strings are properly sent to <code>sys.stdout</code> and hence printed properly on the terminal (<code>sys.stdout</code> is attached the terminal).</p> <p>Is this the correct way to write unicode strings in <code>sys.stdout</code> or should I be doing something else?</p> <p><strong>EDIT</strong>: at times--say, when piping the output to <code>less</code>--<code>sys.stdout.encoding</code> will be <code>None</code>. in this case, the above code will fail.</p>
13
2009-09-24T19:02:35Z
6,361,471
<pre><code>export PYTHONIOENCODING=utf-8 </code></pre> <p>will do the job, but can't set it on python itself ... </p> <p>what we can do is verify if isn't setting and tell the user to set it before call script with :</p> <pre><code>if __name__ == '__main__': if (sys.stdout.encoding is None): print &gt;&gt; sys.stderr, "please set python env PYTHONIOENCODING=UTF-8, example: export PYTHONIOENCODING=UTF-8, when write to stdout." exit(1) </code></pre>
23
2011-06-15T17:04:06Z
[ "python", "unicode", "osx", "terminal", "stdout" ]
Writing unicode strings via sys.stdout in Python
1,473,577
<p>Assume for a moment that one cannot use <code>print</code> (and thus enjoy the benefit of automatic encoding detection). So that leaves us with <code>sys.stdout</code>. However, <code>sys.stdout</code> is so dumb as to <a href="http://bugs.python.org/issue4947" rel="nofollow">not do any sensible encoding</a>.</p> <p>Now one reads the Python wiki page <a href="http://wiki.python.org/moin/PrintFails" rel="nofollow">PrintFails</a> and goes to try out the following code:</p> <pre><code>$ python -c 'import sys, codecs, locale; print str(sys.stdout.encoding); \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); </code></pre> <p>However this too does not work (at least on Mac). Too see why:</p> <pre><code>&gt;&gt;&gt; import locale &gt;&gt;&gt; locale.getpreferredencoding() 'mac-roman' &gt;&gt;&gt; sys.stdout.encoding 'UTF-8' </code></pre> <p>(UTF-8 is what one's terminal understands).</p> <p>So one changes the above code to:</p> <pre><code>$ python -c 'import sys, codecs, locale; print str(sys.stdout.encoding); \ sys.stdout = codecs.getwriter(sys.stdout.encoding)(sys.stdout); </code></pre> <p>And now unicode strings are properly sent to <code>sys.stdout</code> and hence printed properly on the terminal (<code>sys.stdout</code> is attached the terminal).</p> <p>Is this the correct way to write unicode strings in <code>sys.stdout</code> or should I be doing something else?</p> <p><strong>EDIT</strong>: at times--say, when piping the output to <code>less</code>--<code>sys.stdout.encoding</code> will be <code>None</code>. in this case, the above code will fail.</p>
13
2009-09-24T19:02:35Z
13,703,054
<p>This is what I am doing in my application:</p> <p><code>sys.stdout.write(s.encode('utf-8'))</code></p> <p>This is the exact opposite fix for reading UTF-8 names from argv:</p> <pre><code>for file in sys.argv[1:]: file = file.decode('utf-8') </code></pre> <p>This is very ugly (IMHO) as it force you to work with UTF-8.. which is the norm on Linux/Mac, but not on windows... Works for me anyway :)</p>
5
2012-12-04T12:36:40Z
[ "python", "unicode", "osx", "terminal", "stdout" ]
python multiprocessing manager & composite pattern sharing
1,473,625
<p>I'm trying to share a composite structure through a multiprocessing manager but I felt in trouble with a "<strong>RuntimeError: maximum recursion depth exceeded</strong>" when trying to use just one of the Composite class methods.</p> <p>The class is token from <a href="http://code.activestate.com/recipes/498249/#clast" rel="nofollow">code.activestate</a> and tested by me before inclusion into the manager.</p> <p>When retrieving the class into a process and invoking its <strong>addChild()</strong> method I kept the <strong>RunTimeError</strong>, while outside the process it works.</p> <p>The composite class inheritates from a SpecialDict class, that implements a ** <strong>__getattr()__</strong> ** method. </p> <p>Could be possible that while calling <strong>addChild()</strong> the interpreter of python looks for a different ** <strong>__getattr()__</strong> ** because the right one is not proxied by the manager?</p> <p>If so It's not clear to me the right way to make a proxy to that class/method</p> <p>The following code reproduce exactly this condition:</p> <p>1) this is the manager.py:</p> <pre><code>from multiprocessing.managers import BaseManager from CompositeDict import * class PlantPurchaser(): def __init__(self): self.comp = CompositeDict('Comp') def get_cp(self): return self.comp class Manager(): def __init__(self): self.comp = QueuePurchaser().get_cp() BaseManager.register('get_comp', callable=lambda:self.comp) self.m = BaseManager(address=('127.0.0.1', 50000), authkey='abracadabra') self.s = self.m.get_server() self.s.serve_forever() </code></pre> <p>2) I want to use the composite into this consumer.py:</p> <pre><code>from multiprocessing.managers import BaseManager class Consumer(): def __init__(self): BaseManager.register('get_comp') self.m = BaseManager(address=('127.0.0.1', 50000), authkey='abracadabra') self.m.connect() self.comp = self.m.get_comp() ret = self.comp.addChild('consumer') </code></pre> <p>3) run all launching by a controller.py:</p> <pre><code>from multiprocessing import Process class Controller(): def __init__(self): for child in _run_children(): child.join() def _run_children(): from manager import Manager from consumer import Consumer as Consumer procs = ( Process(target=Manager, name='Manager' ), Process(target=Consumer, name='Consumer'), ) for proc in procs: proc.daemon = 1 proc.start() return procs c = Controller() </code></pre> <p>Take a look this <a href="http://stackoverflow.com/questions/1486835">related questions</a> on how to do a proxy for CompositeDict() class as suggested by AlberT.</p> <p>The solution given by <strong>tgray</strong> works but cannot avoid race conditions</p>
1
2009-09-24T19:14:06Z
1,473,700
<p>Python has a default maximum recursion depth of 1000 (or 999, I forget...). But you can change the default behavior thusly:</p> <pre><code>import sys sys.setrecursionlimit(n) </code></pre> <p>Where <code>n</code> is the number of recursions you wish to allow. </p> <p><strong>Edit:</strong></p> <p>The above answer does nothing to solve the root cause of this problem (as pointed out in the comments). It only needs to be used if you are intentionally recursing more than 1000 times. If you are in an infinite loop (like in this problem), you will eventually hit whatever limit you set.</p> <p>To address your actual problem, I re-wrote your code from scratch starting as simply as I could make it and built it up to what I believe is what you want:</p> <pre><code>import sys from multiprocessing import Process from multiprocessing.managers import BaseManager from CompositDict import * class Shared(): def __init__(self): self.comp = CompositeDict('Comp') def get_comp(self): return self.comp def set_comp(self, c): self.comp = c class Manager(): def __init__(self): shared = Shared() BaseManager.register('get_shared', callable=lambda:shared) mgr = BaseManager(address=('127.0.0.1', 50000), authkey='abracadabra') srv = mgr.get_server() srv.serve_forever() class Consumer(): def __init__(self, child_name): BaseManager.register('get_shared') mgr = BaseManager(address=('127.0.0.1', 50000), authkey='abracadabra') mgr.connect() shared = mgr.get_shared() comp = shared.get_comp() child = comp.addChild(child_name) shared.set_comp(comp) print comp class Controller(): def __init__(self): pass def main(self): m = Process(target=Manager, name='Manager') m.daemon = True m.start() consumers = [] for i in xrange(3): p = Process(target=Consumer, name='Consumer', args=('Consumer_' + str(i),)) p.daemon = True consumers.append(p) for c in consumers: c.start() for c in consumers: c.join() return 0 if __name__ == '__main__': con = Controller() sys.exit(con.main()) </code></pre> <p>I did this all in one file, but you shouldn't have any trouble breaking it up.</p> <p>I added a <code>child_name</code> argument to your consumer so that I could check that the <code>CompositDict</code> was getting updated.</p> <p>Note that there is both a getter <em>and</em> a setter for your <code>CompositDict</code> object. When I only had a getter, each Consumer was overwriting the <code>CompositDict</code> when it added a child.</p> <p>This is why I also changed your registered method to <code>get_shared</code> instead of <code>get_comp</code>, as you will want access to the setter as well as the getter within your Consumer class.</p> <p>Also, I don't think you want to try joining your manager process, as it will "serve forever". If you look at the source for the BaseManager (./Lib/multiprocessing/managers.py:Line 144) you'll notice that the <code>serve_forever()</code> function puts you into an infinite loop that is only broken by <code>KeyboardInterrupt</code> or <code>SystemExit</code>.</p> <p>Bottom line is that this code works without any recursive looping (as far as I can tell), but let me know if you still experience your error.</p>
0
2009-09-24T19:27:23Z
[ "python", "multiprocessing", "manager" ]
python multiprocessing manager & composite pattern sharing
1,473,625
<p>I'm trying to share a composite structure through a multiprocessing manager but I felt in trouble with a "<strong>RuntimeError: maximum recursion depth exceeded</strong>" when trying to use just one of the Composite class methods.</p> <p>The class is token from <a href="http://code.activestate.com/recipes/498249/#clast" rel="nofollow">code.activestate</a> and tested by me before inclusion into the manager.</p> <p>When retrieving the class into a process and invoking its <strong>addChild()</strong> method I kept the <strong>RunTimeError</strong>, while outside the process it works.</p> <p>The composite class inheritates from a SpecialDict class, that implements a ** <strong>__getattr()__</strong> ** method. </p> <p>Could be possible that while calling <strong>addChild()</strong> the interpreter of python looks for a different ** <strong>__getattr()__</strong> ** because the right one is not proxied by the manager?</p> <p>If so It's not clear to me the right way to make a proxy to that class/method</p> <p>The following code reproduce exactly this condition:</p> <p>1) this is the manager.py:</p> <pre><code>from multiprocessing.managers import BaseManager from CompositeDict import * class PlantPurchaser(): def __init__(self): self.comp = CompositeDict('Comp') def get_cp(self): return self.comp class Manager(): def __init__(self): self.comp = QueuePurchaser().get_cp() BaseManager.register('get_comp', callable=lambda:self.comp) self.m = BaseManager(address=('127.0.0.1', 50000), authkey='abracadabra') self.s = self.m.get_server() self.s.serve_forever() </code></pre> <p>2) I want to use the composite into this consumer.py:</p> <pre><code>from multiprocessing.managers import BaseManager class Consumer(): def __init__(self): BaseManager.register('get_comp') self.m = BaseManager(address=('127.0.0.1', 50000), authkey='abracadabra') self.m.connect() self.comp = self.m.get_comp() ret = self.comp.addChild('consumer') </code></pre> <p>3) run all launching by a controller.py:</p> <pre><code>from multiprocessing import Process class Controller(): def __init__(self): for child in _run_children(): child.join() def _run_children(): from manager import Manager from consumer import Consumer as Consumer procs = ( Process(target=Manager, name='Manager' ), Process(target=Consumer, name='Consumer'), ) for proc in procs: proc.daemon = 1 proc.start() return procs c = Controller() </code></pre> <p>Take a look this <a href="http://stackoverflow.com/questions/1486835">related questions</a> on how to do a proxy for CompositeDict() class as suggested by AlberT.</p> <p>The solution given by <strong>tgray</strong> works but cannot avoid race conditions</p>
1
2009-09-24T19:14:06Z
1,474,232
<p>Is it possible there is a circular reference between the classes? For example, the outer class has a reference to the composite class, and the composite class has a reference back to the outer class.</p> <p>The multiprocessing manager works well, but when you have large, complicated class structures, then you are likely to run into an error where a type/reference can not be serialized correctly. The other problem is that errors from multiprocessing manager are very cryptic. This makes debugging failure conditions even more difficult.</p>
0
2009-09-24T21:23:40Z
[ "python", "multiprocessing", "manager" ]
python multiprocessing manager & composite pattern sharing
1,473,625
<p>I'm trying to share a composite structure through a multiprocessing manager but I felt in trouble with a "<strong>RuntimeError: maximum recursion depth exceeded</strong>" when trying to use just one of the Composite class methods.</p> <p>The class is token from <a href="http://code.activestate.com/recipes/498249/#clast" rel="nofollow">code.activestate</a> and tested by me before inclusion into the manager.</p> <p>When retrieving the class into a process and invoking its <strong>addChild()</strong> method I kept the <strong>RunTimeError</strong>, while outside the process it works.</p> <p>The composite class inheritates from a SpecialDict class, that implements a ** <strong>__getattr()__</strong> ** method. </p> <p>Could be possible that while calling <strong>addChild()</strong> the interpreter of python looks for a different ** <strong>__getattr()__</strong> ** because the right one is not proxied by the manager?</p> <p>If so It's not clear to me the right way to make a proxy to that class/method</p> <p>The following code reproduce exactly this condition:</p> <p>1) this is the manager.py:</p> <pre><code>from multiprocessing.managers import BaseManager from CompositeDict import * class PlantPurchaser(): def __init__(self): self.comp = CompositeDict('Comp') def get_cp(self): return self.comp class Manager(): def __init__(self): self.comp = QueuePurchaser().get_cp() BaseManager.register('get_comp', callable=lambda:self.comp) self.m = BaseManager(address=('127.0.0.1', 50000), authkey='abracadabra') self.s = self.m.get_server() self.s.serve_forever() </code></pre> <p>2) I want to use the composite into this consumer.py:</p> <pre><code>from multiprocessing.managers import BaseManager class Consumer(): def __init__(self): BaseManager.register('get_comp') self.m = BaseManager(address=('127.0.0.1', 50000), authkey='abracadabra') self.m.connect() self.comp = self.m.get_comp() ret = self.comp.addChild('consumer') </code></pre> <p>3) run all launching by a controller.py:</p> <pre><code>from multiprocessing import Process class Controller(): def __init__(self): for child in _run_children(): child.join() def _run_children(): from manager import Manager from consumer import Consumer as Consumer procs = ( Process(target=Manager, name='Manager' ), Process(target=Consumer, name='Consumer'), ) for proc in procs: proc.daemon = 1 proc.start() return procs c = Controller() </code></pre> <p>Take a look this <a href="http://stackoverflow.com/questions/1486835">related questions</a> on how to do a proxy for CompositeDict() class as suggested by AlberT.</p> <p>The solution given by <strong>tgray</strong> works but cannot avoid race conditions</p>
1
2009-09-24T19:14:06Z
1,476,681
<p>I think the problem is that you have to instruct the Manager on how to manage you object, which is not a standard python type.</p> <p>In other worlds <strong>you have to create a proxy for you CompositeDict</strong></p> <p>You could look at this doc for an example: <a href="http://ruffus.googlecode.com/svn/trunk/doc/html/sharing%5Fdata%5Facross%5Fjobs%5Fexample.html" rel="nofollow">http://ruffus.googlecode.com/svn/trunk/doc/html/sharing_data_across_jobs_example.html</a></p>
0
2009-09-25T11:05:40Z
[ "python", "multiprocessing", "manager" ]
Raising ValidationError from django model's save method?
1,473,888
<p>I need to raise an exception in a model's save method. I'm hoping that an exception exists that will be caught by any django <code>ModelForm</code> that uses this model including the admin forms. </p> <p>I tried raising <code>django.forms.ValidationError</code>, but this seems to be uncaught by the admin forms. The model makes a remote procedure call at save time, and it's not known until this call if the input is valid.</p> <p>Thanks, Pete</p>
10
2009-09-24T20:13:16Z
1,473,979
<p>There's currently no way of performing validation in model save methods. This is however being developed, as a separate model-validation branch, and should be merged into trunk in the next few months.</p> <p>In the meantime, you need to do the validation at the form level. It's quite simple to create a <code>ModelForm</code> subclass with a <code>clean()</code> method which does your remote call and raises the exception accordingly, and use this both in the admin and as the basis for your other forms.</p>
8
2009-09-24T20:29:42Z
[ "python", "django" ]
Raising ValidationError from django model's save method?
1,473,888
<p>I need to raise an exception in a model's save method. I'm hoping that an exception exists that will be caught by any django <code>ModelForm</code> that uses this model including the admin forms. </p> <p>I tried raising <code>django.forms.ValidationError</code>, but this seems to be uncaught by the admin forms. The model makes a remote procedure call at save time, and it's not known until this call if the input is valid.</p> <p>Thanks, Pete</p>
10
2009-09-24T20:13:16Z
12,356,526
<p>Since Django 1.2, this is what I've been doing:</p> <pre><code>class MyModel(models.Model): &lt;...model fields...&gt; def clean(self, *args, **kwargs): if &lt;some constraint not met&gt;: raise ValidationError('You have not met a constraint!') super(MyModel, self).clean(*args, **kwargs) def full_clean(self, *args, **kwargs): return self.clean(*args, **kwargs) def save(self, *args, **kwargs): self.full_clean() super(MyModel, self).save(*args, **kwargs) </code></pre> <p>This has the benefit of working both inside and outside of admin.</p>
9
2012-09-10T17:19:52Z
[ "python", "django" ]
Ghostscript on Google App Engine?
1,474,000
<p>Is it possible to call ghostscript on an App Engine project? I'd like to be able to perform some document conversion using gs (pdf to tiff in particular), and I am not seeing any specific documentation that either rules out this possibility or states how to pull it off.</p> <p>Thanks!</p> <p>Shaheeb R. </p>
0
2009-09-24T20:34:20Z
1,480,188
<p>From some cursory Googling it looks like ghostscript is written mostly in C, so no, you won't be able to run it on App Engine directly. If you have a server available you can run it there and send in documents for conversion, or you could bring up an EC2 instance remotely when you need to do a conversion.</p>
0
2009-09-26T01:28:41Z
[ "python", "google-app-engine", "ghostscript" ]
Django Admin: Ordering of ForeignKey and ManyToManyField relations referencing User
1,474,135
<p>I have an application that makes use of Django's <code>UserProfile</code> to extend the built-in Django <code>User</code> model. Looks a bit like:</p> <pre><code>class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) # Local Stuff image_url_s = models.CharField(max_length=128, blank=True) image_url_m = models.CharField(max_length=128, blank=True) # Admin class Admin: pass </code></pre> <p>I have added a new class to my model:</p> <pre><code>class Team(models.Model): name = models.CharField(max_length=128) manager = models.ForeignKey(User, related_name='manager') members = models.ManyToManyField(User, blank=True) </code></pre> <p>And it is registered into the Admin:</p> <pre><code>class TeamAdmin(admin.ModelAdmin): list_display = ('name', 'manager') admin.site.register(Team, TeamAdmin) </code></pre> <p>Alas, in the admin inteface, when I go to select a manager from the drop-down box, or set team members via the multi-select field, they are ordered by the User numeric ID. For the life of me, I can not figure out how to get these sorted.</p> <p>I have a similar class with:</p> <pre><code>class Meta: ordering = ['name'] </code></pre> <p>That works great! But I don't "own" the <code>User</code> class, and when I try this trick in <code>UserAdmin</code>:</p> <pre><code>class Meta: ordering = ['username'] </code></pre> <p>I get:</p> <p><code>django.core.management.base.CommandError: One or more models did not validate:</code> <code>events.userprofile: "ordering" refers to "username", a field that doesn't exist.</code></p> <p><code>user.username</code> doesn't work either. I could specify, like <code>image_url_s</code> if I wanted to . . . how can I tell the admin to sort my lists of users by <code>username</code>? Thanks!</p>
14
2009-09-24T21:01:23Z
1,474,175
<p>One way would be to define a custom form to use for your Team model in the admin, and override the <code>manager</code> field to use a queryset with the correct ordering:</p> <pre><code>from django import forms class TeamForm(forms.ModelForm): manager = forms.ModelChoiceField(queryset=User.objects.order_by('username')) class Meta: model = Team class TeamAdmin(admin.ModelAdmin): list_display = ('name', 'manager') form = TeamForm </code></pre>
21
2009-09-24T21:10:23Z
[ "python", "django", "sorting", "admin", "user-profile" ]
Django Admin: Ordering of ForeignKey and ManyToManyField relations referencing User
1,474,135
<p>I have an application that makes use of Django's <code>UserProfile</code> to extend the built-in Django <code>User</code> model. Looks a bit like:</p> <pre><code>class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) # Local Stuff image_url_s = models.CharField(max_length=128, blank=True) image_url_m = models.CharField(max_length=128, blank=True) # Admin class Admin: pass </code></pre> <p>I have added a new class to my model:</p> <pre><code>class Team(models.Model): name = models.CharField(max_length=128) manager = models.ForeignKey(User, related_name='manager') members = models.ManyToManyField(User, blank=True) </code></pre> <p>And it is registered into the Admin:</p> <pre><code>class TeamAdmin(admin.ModelAdmin): list_display = ('name', 'manager') admin.site.register(Team, TeamAdmin) </code></pre> <p>Alas, in the admin inteface, when I go to select a manager from the drop-down box, or set team members via the multi-select field, they are ordered by the User numeric ID. For the life of me, I can not figure out how to get these sorted.</p> <p>I have a similar class with:</p> <pre><code>class Meta: ordering = ['name'] </code></pre> <p>That works great! But I don't "own" the <code>User</code> class, and when I try this trick in <code>UserAdmin</code>:</p> <pre><code>class Meta: ordering = ['username'] </code></pre> <p>I get:</p> <p><code>django.core.management.base.CommandError: One or more models did not validate:</code> <code>events.userprofile: "ordering" refers to "username", a field that doesn't exist.</code></p> <p><code>user.username</code> doesn't work either. I could specify, like <code>image_url_s</code> if I wanted to . . . how can I tell the admin to sort my lists of users by <code>username</code>? Thanks!</p>
14
2009-09-24T21:01:23Z
1,474,195
<p>This</p> <pre><code>class Meta: ordering = ['username'] </code></pre> <p>should be </p> <pre><code> ordering = ['user__username'] </code></pre> <p>if it's in your UserProfile admin class. That'll stop the exception, but I don't think it helps you.</p> <p>Ordering the User model as you describe is quite tricky, but see <a href="http://code.djangoproject.com/ticket/6089#comment%3A8">http://code.djangoproject.com/ticket/6089#comment%3A8</a> for a solution.</p>
23
2009-09-24T21:15:58Z
[ "python", "django", "sorting", "admin", "user-profile" ]
Django Admin: Ordering of ForeignKey and ManyToManyField relations referencing User
1,474,135
<p>I have an application that makes use of Django's <code>UserProfile</code> to extend the built-in Django <code>User</code> model. Looks a bit like:</p> <pre><code>class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) # Local Stuff image_url_s = models.CharField(max_length=128, blank=True) image_url_m = models.CharField(max_length=128, blank=True) # Admin class Admin: pass </code></pre> <p>I have added a new class to my model:</p> <pre><code>class Team(models.Model): name = models.CharField(max_length=128) manager = models.ForeignKey(User, related_name='manager') members = models.ManyToManyField(User, blank=True) </code></pre> <p>And it is registered into the Admin:</p> <pre><code>class TeamAdmin(admin.ModelAdmin): list_display = ('name', 'manager') admin.site.register(Team, TeamAdmin) </code></pre> <p>Alas, in the admin inteface, when I go to select a manager from the drop-down box, or set team members via the multi-select field, they are ordered by the User numeric ID. For the life of me, I can not figure out how to get these sorted.</p> <p>I have a similar class with:</p> <pre><code>class Meta: ordering = ['name'] </code></pre> <p>That works great! But I don't "own" the <code>User</code> class, and when I try this trick in <code>UserAdmin</code>:</p> <pre><code>class Meta: ordering = ['username'] </code></pre> <p>I get:</p> <p><code>django.core.management.base.CommandError: One or more models did not validate:</code> <code>events.userprofile: "ordering" refers to "username", a field that doesn't exist.</code></p> <p><code>user.username</code> doesn't work either. I could specify, like <code>image_url_s</code> if I wanted to . . . how can I tell the admin to sort my lists of users by <code>username</code>? Thanks!</p>
14
2009-09-24T21:01:23Z
8,098,599
<p>This might be dangerous for some reason, but this can be done in one line in your project's <code>models.py</code> file:</p> <pre><code>User._meta.ordering=["username"] </code></pre>
3
2011-11-11T18:54:28Z
[ "python", "django", "sorting", "admin", "user-profile" ]
Django Admin: Ordering of ForeignKey and ManyToManyField relations referencing User
1,474,135
<p>I have an application that makes use of Django's <code>UserProfile</code> to extend the built-in Django <code>User</code> model. Looks a bit like:</p> <pre><code>class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) # Local Stuff image_url_s = models.CharField(max_length=128, blank=True) image_url_m = models.CharField(max_length=128, blank=True) # Admin class Admin: pass </code></pre> <p>I have added a new class to my model:</p> <pre><code>class Team(models.Model): name = models.CharField(max_length=128) manager = models.ForeignKey(User, related_name='manager') members = models.ManyToManyField(User, blank=True) </code></pre> <p>And it is registered into the Admin:</p> <pre><code>class TeamAdmin(admin.ModelAdmin): list_display = ('name', 'manager') admin.site.register(Team, TeamAdmin) </code></pre> <p>Alas, in the admin inteface, when I go to select a manager from the drop-down box, or set team members via the multi-select field, they are ordered by the User numeric ID. For the life of me, I can not figure out how to get these sorted.</p> <p>I have a similar class with:</p> <pre><code>class Meta: ordering = ['name'] </code></pre> <p>That works great! But I don't "own" the <code>User</code> class, and when I try this trick in <code>UserAdmin</code>:</p> <pre><code>class Meta: ordering = ['username'] </code></pre> <p>I get:</p> <p><code>django.core.management.base.CommandError: One or more models did not validate:</code> <code>events.userprofile: "ordering" refers to "username", a field that doesn't exist.</code></p> <p><code>user.username</code> doesn't work either. I could specify, like <code>image_url_s</code> if I wanted to . . . how can I tell the admin to sort my lists of users by <code>username</code>? Thanks!</p>
14
2009-09-24T21:01:23Z
23,649,887
<p>For me, the only working solution was to use <a href="https://docs.djangoproject.com/en/1.7/topics/db/models/#proxy-models" rel="nofollow">Proxy Model</a>. As stated in the documentation, you can create own proxy models for even built-in models and customize anything like in regular models:</p> <pre><code>class OrderedUser(User): class Meta: proxy = True ordering = ["username"] def __str__(self): return '%s %s' % (self.first_name, self.last_name) </code></pre> <p>After that, in your model just change Foreign Key to:</p> <pre><code>user = models.OneToOneField(OrderedUser, unique=True) </code></pre> <p>or even more suitable</p> <pre><code>user = models.OneToOneField(OrderedUser, unique = True, parent_link = True) </code></pre>
0
2014-05-14T08:52:46Z
[ "python", "django", "sorting", "admin", "user-profile" ]
python arbitrarily incrementing an iterator inside a loop
1,474,646
<p>I am probably going about this in the wrong manner, but I was wondering how to handle this in python. </p> <p>First some c code:</p> <pre><code>int i; for(i=0;i&lt;100;i++){ if(i == 50) i = i + 10; printf("%i\n", i); } </code></pre> <p>Ok so we never see the 50's... </p> <p>My question is, how can I do something similar in python? For instance:</p> <pre><code>for line in cdata.split('\n'): if exp.match(line): #increment the position of the iterator by 5? pass print line </code></pre> <p>With my limited experience in python, I only have one solution, introduce a counter and another if statement. break the loop until the counter reaches 5 after exp.match(line) is true. </p> <p>There has got to be a better way to do this, hopefully one that does not involve importing another module. </p> <p>Thanks in advance! </p>
32
2009-09-24T23:11:17Z
1,474,675
<p>Not exactly sure I follow your thought process but here is something to feed on..</p> <pre><code>for i in range(len(cdata.split('\n'))): if i in range(50,60): continue line = cdata[i] if exp.match(line): #increment the position of the iterator by 5? pass print line </code></pre> <p>Not sure what you are really after but the range(len(..)) should help you.</p>
1
2009-09-24T23:22:06Z
[ "python", "iterator" ]
python arbitrarily incrementing an iterator inside a loop
1,474,646
<p>I am probably going about this in the wrong manner, but I was wondering how to handle this in python. </p> <p>First some c code:</p> <pre><code>int i; for(i=0;i&lt;100;i++){ if(i == 50) i = i + 10; printf("%i\n", i); } </code></pre> <p>Ok so we never see the 50's... </p> <p>My question is, how can I do something similar in python? For instance:</p> <pre><code>for line in cdata.split('\n'): if exp.match(line): #increment the position of the iterator by 5? pass print line </code></pre> <p>With my limited experience in python, I only have one solution, introduce a counter and another if statement. break the loop until the counter reaches 5 after exp.match(line) is true. </p> <p>There has got to be a better way to do this, hopefully one that does not involve importing another module. </p> <p>Thanks in advance! </p>
32
2009-09-24T23:11:17Z
1,474,683
<p>If you're doing it with numbers a list comprehension can work:</p> <pre><code>for i in [x for x in range(0, 99) if x &lt; 50 and x &gt; 59]: print i </code></pre> <p>Moving an iterator forward is a bit more difficult though. I'd suggest setting your list up beforehand if you don't want to do the counter approach, probably by splitting cdata, then working out the indexes of the matching line and removing that line and the following ones. Apart from that you're stuck with the counter approach which isn't nearly as unpleasant as you make it out to be to be honest.</p> <p>Another option is this:</p> <pre><code>iterator = iter(cdata.split('\n')) for line in iterator: if exp.match(line): for i in range(0, 5): try: iterator.next() except StopIteration: break else: print line </code></pre>
2
2009-09-24T23:24:38Z
[ "python", "iterator" ]
python arbitrarily incrementing an iterator inside a loop
1,474,646
<p>I am probably going about this in the wrong manner, but I was wondering how to handle this in python. </p> <p>First some c code:</p> <pre><code>int i; for(i=0;i&lt;100;i++){ if(i == 50) i = i + 10; printf("%i\n", i); } </code></pre> <p>Ok so we never see the 50's... </p> <p>My question is, how can I do something similar in python? For instance:</p> <pre><code>for line in cdata.split('\n'): if exp.match(line): #increment the position of the iterator by 5? pass print line </code></pre> <p>With my limited experience in python, I only have one solution, introduce a counter and another if statement. break the loop until the counter reaches 5 after exp.match(line) is true. </p> <p>There has got to be a better way to do this, hopefully one that does not involve importing another module. </p> <p>Thanks in advance! </p>
32
2009-09-24T23:11:17Z
1,474,697
<p>You can drop values from an iterator</p> <pre><code>def dropvalues(iterator, vals): for i in xrange(vals): iterator.next() </code></pre> <p>Now just make sure you have an iterator object to work on with <code>lines = iter(cdata.split('\n'))</code>; and loop over it.</p>
1
2009-09-24T23:31:43Z
[ "python", "iterator" ]
python arbitrarily incrementing an iterator inside a loop
1,474,646
<p>I am probably going about this in the wrong manner, but I was wondering how to handle this in python. </p> <p>First some c code:</p> <pre><code>int i; for(i=0;i&lt;100;i++){ if(i == 50) i = i + 10; printf("%i\n", i); } </code></pre> <p>Ok so we never see the 50's... </p> <p>My question is, how can I do something similar in python? For instance:</p> <pre><code>for line in cdata.split('\n'): if exp.match(line): #increment the position of the iterator by 5? pass print line </code></pre> <p>With my limited experience in python, I only have one solution, introduce a counter and another if statement. break the loop until the counter reaches 5 after exp.match(line) is true. </p> <p>There has got to be a better way to do this, hopefully one that does not involve importing another module. </p> <p>Thanks in advance! </p>
32
2009-09-24T23:11:17Z
1,474,751
<p>Maybe with genexps. Not pretty but...</p> <p>Something like that:</p> <pre><code>&gt;&gt;&gt; gx = (line for line in '1 2 x 3 4 5 6 7 x 9 10 11 12 x 1'.split('\n')) &gt;&gt;&gt; for line in gx: ... if line == 'x': ... for i in range(2): ... line = gx.next() ... print line </code></pre> <p>The only problem is to ensure that gx can be next()-ed. The above example purposely generates an exception due to the last x.</p>
0
2009-09-24T23:49:43Z
[ "python", "iterator" ]
python arbitrarily incrementing an iterator inside a loop
1,474,646
<p>I am probably going about this in the wrong manner, but I was wondering how to handle this in python. </p> <p>First some c code:</p> <pre><code>int i; for(i=0;i&lt;100;i++){ if(i == 50) i = i + 10; printf("%i\n", i); } </code></pre> <p>Ok so we never see the 50's... </p> <p>My question is, how can I do something similar in python? For instance:</p> <pre><code>for line in cdata.split('\n'): if exp.match(line): #increment the position of the iterator by 5? pass print line </code></pre> <p>With my limited experience in python, I only have one solution, introduce a counter and another if statement. break the loop until the counter reaches 5 after exp.match(line) is true. </p> <p>There has got to be a better way to do this, hopefully one that does not involve importing another module. </p> <p>Thanks in advance! </p>
32
2009-09-24T23:11:17Z
1,474,848
<p>There is a fantastic package in Python called <a href="http://docs.python.org/library/itertools.html"><code>itertools</code></a>.</p> <p>But before I get into that, it'd serve well to explain how the iteration protocol is implemented in Python. When you want to provide iteration over your container, you specify the <a href="http://docs.python.org/reference/datamodel.html#object.__iter__"><code>__iter__()</code></a> class method that provides an <a href="http://docs.python.org/library/stdtypes.html#iterator-types">iterator type</a>. <a href="http://effbot.org/zone/python-for-statement.htm">"Understanding Python's 'for' statement"</a> is a nice article covering how the <code>for-in</code> statement actually works in Python and provides a nice overview on how the iterator types work.</p> <p>Take a look at the following:</p> <pre><code>&gt;&gt;&gt; sequence = [1, 2, 3, 4, 5] &gt;&gt;&gt; iterator = sequence.__iter__() &gt;&gt;&gt; iterator.next() 1 &gt;&gt;&gt; iterator.next() 2 &gt;&gt;&gt; for number in iterator: print number 3 4 5 </code></pre> <p>Now back to <code>itertools</code>. The package contains functions for various iteration purposes. If you ever need to do special sequencing, this is the first place to look into.</p> <p>At the bottom you can find the <a href="http://docs.python.org/library/itertools.html#recipes">Recipes</a> section that contain <em>recipes for creating an extended toolset using the existing itertools as building blocks</em>.</p> <p>And there's an interesting function that does exactly what you need:</p> <pre><code>def consume(iterator, n): '''Advance the iterator n-steps ahead. If n is none, consume entirely.''' collections.deque(itertools.islice(iterator, n), maxlen=0) </code></pre> <p>Here's a quick, readable, example on how it works <em>(Python 2.5)</em>:</p> <pre><code>&gt;&gt;&gt; import itertools, collections &gt;&gt;&gt; def consume(iterator, n): collections.deque(itertools.islice(iterator, n)) &gt;&gt;&gt; iterator = range(1, 16).__iter__() &gt;&gt;&gt; for number in iterator: if (number == 5): # Disregard 6, 7, 8, 9 (5 doesn't get printed just as well) consume(iterator, 4) else: print number 1 2 3 4 10 11 12 13 14 15 </code></pre>
35
2009-09-25T00:27:11Z
[ "python", "iterator" ]
python arbitrarily incrementing an iterator inside a loop
1,474,646
<p>I am probably going about this in the wrong manner, but I was wondering how to handle this in python. </p> <p>First some c code:</p> <pre><code>int i; for(i=0;i&lt;100;i++){ if(i == 50) i = i + 10; printf("%i\n", i); } </code></pre> <p>Ok so we never see the 50's... </p> <p>My question is, how can I do something similar in python? For instance:</p> <pre><code>for line in cdata.split('\n'): if exp.match(line): #increment the position of the iterator by 5? pass print line </code></pre> <p>With my limited experience in python, I only have one solution, introduce a counter and another if statement. break the loop until the counter reaches 5 after exp.match(line) is true. </p> <p>There has got to be a better way to do this, hopefully one that does not involve importing another module. </p> <p>Thanks in advance! </p>
32
2009-09-24T23:11:17Z
1,474,880
<p>I can't parse the question vary well because there's this block of confusing and irrelevant C code. Please delete it.</p> <p>Focusing on just the Python code and the question about how to skip 5 lines...</p> <pre><code>lineIter= iter( cdata.splitlines() ) for line in lineIter: if exp.match(line): for count in range(5): line = lineIter.next() print line </code></pre>
-5
2009-09-25T00:41:40Z
[ "python", "iterator" ]
python arbitrarily incrementing an iterator inside a loop
1,474,646
<p>I am probably going about this in the wrong manner, but I was wondering how to handle this in python. </p> <p>First some c code:</p> <pre><code>int i; for(i=0;i&lt;100;i++){ if(i == 50) i = i + 10; printf("%i\n", i); } </code></pre> <p>Ok so we never see the 50's... </p> <p>My question is, how can I do something similar in python? For instance:</p> <pre><code>for line in cdata.split('\n'): if exp.match(line): #increment the position of the iterator by 5? pass print line </code></pre> <p>With my limited experience in python, I only have one solution, introduce a counter and another if statement. break the loop until the counter reaches 5 after exp.match(line) is true. </p> <p>There has got to be a better way to do this, hopefully one that does not involve importing another module. </p> <p>Thanks in advance! </p>
32
2009-09-24T23:11:17Z
1,474,881
<h3><a href="http://docs.python.org/library/itertools.html#itertools.islice">itertools.islice</a>:</h3> <pre><code>lines = iter(cdata.splitlines()) for line in lines: if exp.match(line): #increment the position of the iterator by 5 for _ in itertools.islice(lines, 4): pass continue # skip 1+4 lines print line </code></pre> <p>For example, if <code>exp</code>, <code>cdata</code> are:</p> <pre><code>exp = re.compile(r"skip5") cdata = """ before skip skip5 1 never see it 2 ditto 3 .. 4 .. 5 after skip 6 """ </code></pre> <p>Then the output is:</p> <pre> before skip 5 after skip 6 </pre> <h3>Python implementation of the C example</h3> <pre><code>i = 0 while i &lt; 100: if i == 50: i += 10 print i i += 1 </code></pre> <p>As @[Glenn Maynard] pointed out in <a href="http://stackoverflow.com/questions/1474646/python-arbitrarily-incrementing-an-iterator-inside-a-loop/1474848#1474848">the comment</a> if you need to do a very large jumps such as i += 100000000 then you should use explicit <code>while</code> loop instead of just skipping steps in a <code>for</code> loop.</p> <p>Here's the example that uses explicit <code>while</code> loop instead <code>islice</code>:</p> <pre><code>lines = cdata.splitlines() i = 0 while i &lt; len(lines): if exp.match(lines[i]): #increment the position of the iterator by 5 i += 5 else: print lines[i] i += 1 </code></pre> <p>This example produces the same output as the above <code>islice</code> example.</p>
16
2009-09-25T00:42:07Z
[ "python", "iterator" ]
python arbitrarily incrementing an iterator inside a loop
1,474,646
<p>I am probably going about this in the wrong manner, but I was wondering how to handle this in python. </p> <p>First some c code:</p> <pre><code>int i; for(i=0;i&lt;100;i++){ if(i == 50) i = i + 10; printf("%i\n", i); } </code></pre> <p>Ok so we never see the 50's... </p> <p>My question is, how can I do something similar in python? For instance:</p> <pre><code>for line in cdata.split('\n'): if exp.match(line): #increment the position of the iterator by 5? pass print line </code></pre> <p>With my limited experience in python, I only have one solution, introduce a counter and another if statement. break the loop until the counter reaches 5 after exp.match(line) is true. </p> <p>There has got to be a better way to do this, hopefully one that does not involve importing another module. </p> <p>Thanks in advance! </p>
32
2009-09-24T23:11:17Z
1,476,998
<p>for your example, as you're working with lists (indexable sequences) and not with iterators, I would recommend the following:</p> <pre><code>lines = cdata.split("\n") for line in lines[:50]+lines[60:]: print line </code></pre> <p>that's not the most efficient since it potentially constructs 3 new lists (but if the skipped part is bigger that the processed part, it could be more efficient than the other options), but it's quite clean and explicit.</p> <p>If you don't mind to use the itertools module, you can convert the lists to sequences easily:</p> <pre><code>from itertools import chain, islice for line in chain(islice(lines, None, 50), islice(lines, 60,None)): print line </code></pre>
0
2009-09-25T12:21:18Z
[ "python", "iterator" ]
Python variables
1,474,719
<p>I'm trying to create a basic program that will generate a number based on variables entered by the user. The formula is </p> <pre><code>a = b / (c * d) </code></pre> <p>This is a formula for finding specific heat, whereas <code>b=energy</code>, <code>c=mass</code>, and <code>d= change in temperature</code>.</p> <p>So my problem is that I'm not making this program for myself, otherwise I could just assign each variable a number- like:</p> <pre><code>b= 1200 c= 13 d= 2 </code></pre> <p>And then do <code>a = a = b / (c * d)</code>.</p> <p>My goal though, is to create a program for others who don't already know the formula- so that they can simply enter the numbers themselves. Example- I want <code>b = X</code>. <code>X</code> is the number entered by the user of the program. However, I have to define <code>X</code> as a variable first- I want it to be unknown- or based on what a person enters. I don't want <code>b</code>, <code>c</code>, or <code>d</code> to have assigned values. It's a very basic scripting process I know, but I'm new to Python.</p>
2
2009-09-24T23:39:08Z
1,474,731
<pre><code>b = float(raw_input("Please enter a value: ")) a = b / (c*d) print a </code></pre> <p><code>raw_input()</code> prompts the user for input, assuming you're running this in the console</p> <p><code>float()</code> attempts to convert the parameter (in this case, the user input) to a float. the rest of it should be pretty straightforward.</p> <p>Give that a try. Welcome to Python :)</p>
0
2009-09-24T23:43:18Z
[ "python" ]
Python variables
1,474,719
<p>I'm trying to create a basic program that will generate a number based on variables entered by the user. The formula is </p> <pre><code>a = b / (c * d) </code></pre> <p>This is a formula for finding specific heat, whereas <code>b=energy</code>, <code>c=mass</code>, and <code>d= change in temperature</code>.</p> <p>So my problem is that I'm not making this program for myself, otherwise I could just assign each variable a number- like:</p> <pre><code>b= 1200 c= 13 d= 2 </code></pre> <p>And then do <code>a = a = b / (c * d)</code>.</p> <p>My goal though, is to create a program for others who don't already know the formula- so that they can simply enter the numbers themselves. Example- I want <code>b = X</code>. <code>X</code> is the number entered by the user of the program. However, I have to define <code>X</code> as a variable first- I want it to be unknown- or based on what a person enters. I don't want <code>b</code>, <code>c</code>, or <code>d</code> to have assigned values. It's a very basic scripting process I know, but I'm new to Python.</p>
2
2009-09-24T23:39:08Z
1,474,732
<p>The most simple approach is to precede the formula with the fragment</p> <pre><code>b = input("Enter b:") c = input("Enter c:") d = input("Enter d:") </code></pre> <p>A few things to note:</p> <ul> <li>this will require console IO, so you best start the script from a console</li> <li>input() causes the string entered to be eval()'ed, meaning that it gets processes as if it was a Python expression. This is useful for numbers, but may have confusing side effects; consider using <code>raw_input()</code>, along with <code>float()</code> instead.</li> </ul>
4
2009-09-24T23:44:04Z
[ "python" ]
Python variables
1,474,719
<p>I'm trying to create a basic program that will generate a number based on variables entered by the user. The formula is </p> <pre><code>a = b / (c * d) </code></pre> <p>This is a formula for finding specific heat, whereas <code>b=energy</code>, <code>c=mass</code>, and <code>d= change in temperature</code>.</p> <p>So my problem is that I'm not making this program for myself, otherwise I could just assign each variable a number- like:</p> <pre><code>b= 1200 c= 13 d= 2 </code></pre> <p>And then do <code>a = a = b / (c * d)</code>.</p> <p>My goal though, is to create a program for others who don't already know the formula- so that they can simply enter the numbers themselves. Example- I want <code>b = X</code>. <code>X</code> is the number entered by the user of the program. However, I have to define <code>X</code> as a variable first- I want it to be unknown- or based on what a person enters. I don't want <code>b</code>, <code>c</code>, or <code>d</code> to have assigned values. It's a very basic scripting process I know, but I'm new to Python.</p>
2
2009-09-24T23:39:08Z
1,474,738
<p>I think you want something like this:</p> <pre><code>b = float(raw_input("Energy? ")) c = float(raw_input("Mass? ")) d = float(raw_input("Change in temperature? ")) print "Specific heat: %f" % (b / (c * d)) </code></pre> <ul> <li>raw_input() prompts the user and returns the inputted value</li> <li>float() converts the value to a float (if possible; if not, this will throw an exception and terminate the program)</li> <li>the "%f" in the last line formats the argument as a floating-point value, where "the argument" is the value of the expression following the % outside of the string (i.e. '(b / (c * d))')</li> </ul>
6
2009-09-24T23:44:59Z
[ "python" ]
Python variables
1,474,719
<p>I'm trying to create a basic program that will generate a number based on variables entered by the user. The formula is </p> <pre><code>a = b / (c * d) </code></pre> <p>This is a formula for finding specific heat, whereas <code>b=energy</code>, <code>c=mass</code>, and <code>d= change in temperature</code>.</p> <p>So my problem is that I'm not making this program for myself, otherwise I could just assign each variable a number- like:</p> <pre><code>b= 1200 c= 13 d= 2 </code></pre> <p>And then do <code>a = a = b / (c * d)</code>.</p> <p>My goal though, is to create a program for others who don't already know the formula- so that they can simply enter the numbers themselves. Example- I want <code>b = X</code>. <code>X</code> is the number entered by the user of the program. However, I have to define <code>X</code> as a variable first- I want it to be unknown- or based on what a person enters. I don't want <code>b</code>, <code>c</code>, or <code>d</code> to have assigned values. It's a very basic scripting process I know, but I'm new to Python.</p>
2
2009-09-24T23:39:08Z
29,723,299
<p>this is a really simple way to do it and easy to understand</p> <pre><code>b= float(raw_input("Enter the energy")) c= float(raw_input("Enter the mass")) d= float(raw_input("Enter change in temperature")) a = b / (c * d) print a </code></pre>
0
2015-04-18T21:53:34Z
[ "python" ]
Google App Engine get PolyModel as child class
1,474,868
<p>When I run Google App Engine likeso:</p> <pre><code> from google.appengine.ext import db from google.appengine.ext.db import polymodel class Father(polymodel.PolyModel): def hello(self): print "Father says hi" class Son(Father): def hello(self): print "Spawn says hi" </code></pre> <p>When I run, e.g.</p> <pre><code> s = Son() s.put() son_from_father = Father.get_by_id(s.key().id()) son_from_father.hello() </code></pre> <p>This prints "Father says hi". I would expect this to print "Son says hi". Does anyone know how to make this do what's expected, here?</p> <p><strong>EDIT</strong>:</p> <p>The problem was, ultimately, that I was saving Spawn objects as Father objects. GAE was happy to do even though the Father objects (in my application) have fewer properties. GAE didn't complain because I (silently) removed any values not in Model.properties() from the data being saved.</p> <p>I've fixed the improper type saving and added a check for extra values not being saved (which was helpfully a TODO comment right where that check should happen). The check I do for data when saving is basically:</p> <pre><code>def save_obj(obj, data, Model): for prop in Model.properties(): # checks/other things happen in this loop setattr(obj, prop, data.get(prop)) extra_data = set(data).difference(Model.properties()) if extra_data: logging.debug("Extra data!") </code></pre> <p>The posts here were helpful - thank you. GAE is working as expected, now that I'm using it as directed. :)</p>
0
2009-09-25T00:34:40Z
1,475,187
<p>You did a "Father.get..." so you created an object from the Father class. So why wouldn't it say "Father says hi". </p> <p>If you Father class had lastname and firstname, and your Son class had middle name, you won't get the middle name unless you specifically retrieve the 'Son' record. </p> <p>If you want to do a polymorphic type query, here's one way to do it. I know it works with attributes, but haven't tried it with methods. </p> <pre><code> fatherList = Father.all().fetch(1000) counter = 0 #I'm using lower case father for object and upper case Father for your class... for father in fatherList: counter += 1 if isinstance(father,Son): self.response.out.write("display a Son field or do a Son method") if isinstance(father,Daughter): self.response.out.write("display a Daughter field or do a Daughter method") </code></pre> <p>Neal Walters</p>
-1
2009-09-25T02:47:39Z
[ "python", "google-app-engine", "polymodel" ]
Google App Engine get PolyModel as child class
1,474,868
<p>When I run Google App Engine likeso:</p> <pre><code> from google.appengine.ext import db from google.appengine.ext.db import polymodel class Father(polymodel.PolyModel): def hello(self): print "Father says hi" class Son(Father): def hello(self): print "Spawn says hi" </code></pre> <p>When I run, e.g.</p> <pre><code> s = Son() s.put() son_from_father = Father.get_by_id(s.key().id()) son_from_father.hello() </code></pre> <p>This prints "Father says hi". I would expect this to print "Son says hi". Does anyone know how to make this do what's expected, here?</p> <p><strong>EDIT</strong>:</p> <p>The problem was, ultimately, that I was saving Spawn objects as Father objects. GAE was happy to do even though the Father objects (in my application) have fewer properties. GAE didn't complain because I (silently) removed any values not in Model.properties() from the data being saved.</p> <p>I've fixed the improper type saving and added a check for extra values not being saved (which was helpfully a TODO comment right where that check should happen). The check I do for data when saving is basically:</p> <pre><code>def save_obj(obj, data, Model): for prop in Model.properties(): # checks/other things happen in this loop setattr(obj, prop, data.get(prop)) extra_data = set(data).difference(Model.properties()) if extra_data: logging.debug("Extra data!") </code></pre> <p>The posts here were helpful - thank you. GAE is working as expected, now that I'm using it as directed. :)</p>
0
2009-09-25T00:34:40Z
1,475,548
<p>I can't reproduce your problem -- indeed, your code just dies with an import error (<code>PolyModel</code> is not in module <code>db</code>) on my GAE (version 1.2.5). Once I've fixed things enough to let the code run...:</p> <pre><code>import wsgiref.handlers from google.appengine.ext import webapp from google.appengine.ext.db import polymodel class Father(polymodel.PolyModel): def hello(self): return "Father says hi" class Son(Father): def hello(self): return "Spawn says hi" class MainHandler(webapp.RequestHandler): def get(self): s = Son() s.put() son_from_father = Father.get_by_id(s.key().id()) x = son_from_father.hello() self.response.out.write(x) def main(): application = webapp.WSGIApplication([('/', MainHandler)], debug=True) wsgiref.handlers.CGIHandler().run(application) if __name__ == '__main__': main() </code></pre> <p>...I see "Spawn says hi" as expected. What App Engine release do you have? What happen if you use exactly the code I'm giving?</p>
1
2009-09-25T05:17:55Z
[ "python", "google-app-engine", "polymodel" ]
BitString error on Windows XP?
1,475,033
<p>Scott, I'd like to thank you for your BitString program. I am working on interpreting data from a neutron detector, and I've found that this module is just the tool I need. Unfortunately, I have yet to get the module to successfully pass test-bitstring.py. I'm running Windows XP and Python 3.1. I've downloaded your file bitstring-0.4.1.zip from your website and extracted both bitstring.py and test-bitstring.py into the \lib folder of my Python directory. Upon running test-bitstring.py, I get 11 errors. :(</p> <p>I've triple-checked that I have downloaded the correct version, and that both of the .py files successfully made it to me \lib folder. Is there a known complication using Windows with BitString? It is probably something I am doing, but I'm at a loss as to where to go from here. In your documentation, you explicitly say to contact you if the version is correct and the errors persist. I'm fairly certain that I'm missing something obvious, but I wanted to check that this is not some sort of compatibility issue? </p> <p>Thank you for taking the time to read this. Sorry to bother you, as I'm sure you get questions about this quite a lot. If you get the chance at all to get back to me, I'm very interested in why you think it might fail the test. Thanks again!</p>
0
2009-09-25T01:40:50Z
1,475,275
<p>I just tested that bitstring-0.4.1 's test-bitstring.py works flawlessly on both Python 3.0 and Python 3.1, on a Windows XP host.</p> <p>The 3.1 version, specifically, this is what happens.</p> <pre><code>'3.1.1 (r311:74483, Aug 17 2009, 17:02:12) [MSC v.1500 32 bit (Intel)]' c:\python31\python test_bitstring.py ................................................................................ ................................................................................ .................................................... ---------------------------------------------------------------------- Ran 212 tests in 0.297s OK </code></pre> <p>OP should provide more details, in particular the list of the 11 failed tests (or at least a few of them, as they probably fail for similar reasons.</p>
2
2009-09-25T03:26:14Z
[ "python", "windows-xp", "python-3.x", "bitstring" ]
BitString error on Windows XP?
1,475,033
<p>Scott, I'd like to thank you for your BitString program. I am working on interpreting data from a neutron detector, and I've found that this module is just the tool I need. Unfortunately, I have yet to get the module to successfully pass test-bitstring.py. I'm running Windows XP and Python 3.1. I've downloaded your file bitstring-0.4.1.zip from your website and extracted both bitstring.py and test-bitstring.py into the \lib folder of my Python directory. Upon running test-bitstring.py, I get 11 errors. :(</p> <p>I've triple-checked that I have downloaded the correct version, and that both of the .py files successfully made it to me \lib folder. Is there a known complication using Windows with BitString? It is probably something I am doing, but I'm at a loss as to where to go from here. In your documentation, you explicitly say to contact you if the version is correct and the errors persist. I'm fairly certain that I'm missing something obvious, but I wanted to check that this is not some sort of compatibility issue? </p> <p>Thank you for taking the time to read this. Sorry to bother you, as I'm sure you get questions about this quite a lot. If you get the chance at all to get back to me, I'm very interested in why you think it might fail the test. Thanks again!</p>
0
2009-09-25T01:40:50Z
1,475,709
<p>feel free to email me queries like this (that's what I meant when I said contact me in the documentation) - I'm somewhat surprised to find a direct question to me on S.O., but I just happened to see it!</p> <p>You should update to the <a href="http://code.google.com/p/python-bitstring/downloads/list" rel="nofollow">latest version for Python 3</a> (1.0.1). I think the problem was a strange platform dependent issue with <code>struct.unpack</code> that was fixed in <a href="http://code.google.com/p/python-bitstring/source/detail?r=445&amp;path=/trunk/bitstring.py" rel="nofollow">rev. 445</a>.</p>
1
2009-09-25T06:24:25Z
[ "python", "windows-xp", "python-3.x", "bitstring" ]
Easiest way to turn a list into an HTML table in python?
1,475,123
<p>lets say I have a list like so:</p> <pre><code>['one','two','three','four','five','six','seven','eight','nine'] </code></pre> <p>and I want to experiment with turning this data into a HTML table of various dimensions:</p> <pre><code>one two three four five six seven eight nine </code></pre> <p>or</p> <pre><code>one four seven two five eight three six nine </code></pre> <p>or</p> <pre><code>one two three four five six seven eight nine </code></pre> <p>Is there a library that can handle this without needing to do crazy list splicing or nested for loops? My google searches reveal that there are a few HTML libraries, but I don't have the time to go through each one to see if they can handle tables very well. Has anyone ever had to do this? If so how did you do it?</p>
6
2009-09-25T02:23:41Z
1,475,148
<p>Well there are several templating libraries around (Genshi is one I like but there are many others).</p> <p>Alternatively you could do something like:</p> <pre><code>def print_table(data, row_length): print '&lt;table&gt;' counter = 0 for element in data: if counter % row_length == 0: print '&lt;tr&gt;' print '&lt;td&gt;%s&lt;/td&gt;' % element counter += 1 if counter % row_length == 0: print '&lt;/tr&gt;' if counter % row_length != 0: for i in range(0, row_length - counter % row_length): print '&lt;td&gt;&amp;nbsp;&lt;/td&gt;' print '&lt;/tr&gt;' print '&lt;/table&gt;' </code></pre>
2
2009-09-25T02:33:15Z
[ "python", "html-table", "html-generation" ]
Easiest way to turn a list into an HTML table in python?
1,475,123
<p>lets say I have a list like so:</p> <pre><code>['one','two','three','four','five','six','seven','eight','nine'] </code></pre> <p>and I want to experiment with turning this data into a HTML table of various dimensions:</p> <pre><code>one two three four five six seven eight nine </code></pre> <p>or</p> <pre><code>one four seven two five eight three six nine </code></pre> <p>or</p> <pre><code>one two three four five six seven eight nine </code></pre> <p>Is there a library that can handle this without needing to do crazy list splicing or nested for loops? My google searches reveal that there are a few HTML libraries, but I don't have the time to go through each one to see if they can handle tables very well. Has anyone ever had to do this? If so how did you do it?</p>
6
2009-09-25T02:23:41Z
1,475,453
<p>I would decompose your problem into two parts:</p> <ul> <li>given a "flat list", produce a list of sublists where the sublists are of a given length and the overall list may be walked into either a "row major" order (your first and third example) or "column major" (your second example);</li> <li>given a list of sublists with string items, produce an HTML table out of it.</li> </ul> <p>I think the two tasks are really very distinct and there's nothing to gain (and much to lose) in mushing them up, so I would be astonished if any well-designed library did such mushing.</p> <p>For point 1, row-major is easy:</p> <pre><code>def row_major(alist, sublen): return [alist[i:i+sublen] for i in range(0, len(alist), sublen)] </code></pre> <p>and column-major not that bad:</p> <pre><code>def col_major(alist, sublen): numrows = (len(alist)+sublen-1) // sublen return [alist[i::sublen] for i in range(numrows)] </code></pre> <p>for example...:</p> <pre><code>L = ['one','two','three','four','five','six','seven','eight','nine'] for r in row_major(L, 3): print r print for r in col_major(L, 3): print r for r in row_major(L, 4): print r </code></pre> <p>produces your three desired results (one list per row, not in HTML form yet;-).</p> <p>The second half of the problem -- produce an HTML table from a list of lists of strings:</p> <pre><code>def html_table(lol): print '&lt;table&gt;' for sublist in lol: print ' &lt;tr&gt;&lt;td&gt;' print ' &lt;/td&gt;&lt;td&gt;'.join(sublist) print ' &lt;/td&gt;&lt;/tr&gt;' print '&lt;/table&gt;' </code></pre> <p>If you want to get it as a single string rather than print it out, change each <code>print</code> into <code>yield</code> and use <code>'\n'.join(html_table(lol))</code>.</p> <p>Now you have two simple, useful, usable and reusable building blocks -- having them separate will come in handy whenever you want to present your data as anything BUT an HTML table, and also whenever the list-of-lists to present as an HTML table comes from any other way of building it. Putting them together is easy to do in your application code, but of course it's also easy to do a simple "glue routine", e.g., assuming the <code>yield</code>-based version of <code>html_table</code> and that a single string result is desired:</p> <pre><code>def list_to_html_table(alist, sublength, column_major=False): if column_major: lol = col_major(alist, sublength) else: lol = row_major(alist, sublength) return ''.join(html_table(lol)) </code></pre> <p>Isn't this building-blocks approach really nicer and more pleasant, as well as more productive, than programming in terms of big blobs of mushed-up glue...?-)</p>
19
2009-09-25T04:36:28Z
[ "python", "html-table", "html-generation" ]
Easiest way to turn a list into an HTML table in python?
1,475,123
<p>lets say I have a list like so:</p> <pre><code>['one','two','three','four','five','six','seven','eight','nine'] </code></pre> <p>and I want to experiment with turning this data into a HTML table of various dimensions:</p> <pre><code>one two three four five six seven eight nine </code></pre> <p>or</p> <pre><code>one four seven two five eight three six nine </code></pre> <p>or</p> <pre><code>one two three four five six seven eight nine </code></pre> <p>Is there a library that can handle this without needing to do crazy list splicing or nested for loops? My google searches reveal that there are a few HTML libraries, but I don't have the time to go through each one to see if they can handle tables very well. Has anyone ever had to do this? If so how did you do it?</p>
6
2009-09-25T02:23:41Z
1,476,000
<p>Maybe manipulate template is easier for toy codes, =p</p> <pre><code>def get_html_tbl(seq, col_count): if len(seq) % col_count: seq.extend([''] * (col_count - len(seq) % col_count)) tbl_template = '&lt;table&gt;%s&lt;/table&gt;' % ('&lt;tr&gt;%s&lt;/tr&gt;' % ('&lt;td&gt;%s&lt;/td&gt;' * col_count) * (len(seq)/col_count)) return tbl_template % tuple(seq) </code></pre>
0
2009-09-25T08:03:23Z
[ "python", "html-table", "html-generation" ]
Easiest way to turn a list into an HTML table in python?
1,475,123
<p>lets say I have a list like so:</p> <pre><code>['one','two','three','four','five','six','seven','eight','nine'] </code></pre> <p>and I want to experiment with turning this data into a HTML table of various dimensions:</p> <pre><code>one two three four five six seven eight nine </code></pre> <p>or</p> <pre><code>one four seven two five eight three six nine </code></pre> <p>or</p> <pre><code>one two three four five six seven eight nine </code></pre> <p>Is there a library that can handle this without needing to do crazy list splicing or nested for loops? My google searches reveal that there are a few HTML libraries, but I don't have the time to go through each one to see if they can handle tables very well. Has anyone ever had to do this? If so how did you do it?</p>
6
2009-09-25T02:23:41Z
25,163,013
<p>Just for future reference, I implemented a small Python module called <strong>simpletable</strong> to provide easy HTML table generation. It also that deals with the issue described in this question.</p> <p>The usage is as simple as below:</p> <pre><code>import simpletable test_data = [str(x) for x in range(20)] formatted_data = simpletable.fit_data_to_columns(test_data, 5) table = simpletable.SimpleTable(formatted_data) html_page = simpletable.HTMLPage(table) html_page.save("test_page.html") </code></pre> <p>Since it does not require third-party packages, you can just get the code from <a href="https://github.com/matheusportela/simpletable" rel="nofollow">my repository</a> and use it in your projects.</p>
2
2014-08-06T14:27:49Z
[ "python", "html-table", "html-generation" ]
what happens to a python object when you throw an exception from it
1,475,193
<p>My class contains a socket that connects to a server. Some of the methods of the class can throw an exception. The script I'm running contains an outer loop that catches the exception, logs an error, and creates a new class instance that tries to reconnect to the server.</p> <p>Problem is that the server only handles one connection at a time (by design) and the "old" socket is still connected. So the new connection attempt hangs the script. I can work around this by forcing the old socket closed, but I wonder: why doesn't the socket automatically close?</p> <p>When it is "stuck", netstat shows two sockets connected to the port. The server is waiting for input from the first socket though, it isn't handling the new one yet.</p> <p>I run this against a dummy server that replies "error\n" to every incoming line.</p> <p>EDIT: see my comment on <a href="http://stackoverflow.com/questions/1475193/what-happens-to-a-python-object-when-you-throw-an-exception-from-it/1475198#1475198">Mark Rushakoff's answer below</a>. An assert(False) [that I subsequently catch] from within the exception handler seems to force the socket closed.</p> <pre><code>import socket class MyException(Exception): pass class MyClient(object): def __init__(self, port): self.sock = socket.create_connection(('localhost', port)) self.sockfile = self.sock.makefile() def do_stuff(self): self._send("do_stuff\n") response = self._receive() if response != "ok\n": raise MyException() return response def _send(self, cmd): self.sockfile.write(cmd) self.sockfile.flush() def _receive(self): return self.sockfile.readline() def connect(): c = MyClient(9989) # On the second iteration, do_stuff() tries to send data and # hangs indefinitely. print c.do_stuff() if __name__ == '__main__': for _ in xrange(3): try: connect() except MyException, e: print 'Caught:', e # This would be the workaround if I had access to the # MyClient object: #c.sock.close() #c.sockfile.close() </code></pre> <p>EDIT: Here's the (ugly) server code:</p> <pre><code>import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) s.bind(('localhost', 9989)) s.listen(5) (c,a) = s.accept() f = c.makefile() print f.readline() f.write('error\n') f.flush() (c2,a) = s.accept() f = c.makefile() print f.readline() s.close() </code></pre>
2
2009-09-25T02:49:51Z
1,475,198
<p>This is an artifact of garbage collection. Even though the object is <em>out of scope</em>, it is not necessarily <em>collected</em> and therefore <em>destroyed</em> until a garbage collection run occurs -- this is not like C++ where a destructor is called as soon as an object loses scope.</p> <p>You can probably work around this particular issue by changing <code>connect</code> to </p> <pre><code>def connect(): try: c = MyClient(9989) # On the second iteration, do_stuff() tries to send data and # hangs indefinitely. print c.do_stuff() finally: c.sock.close() c.sockfile.close() </code></pre> <p>Alternatively, you could define <code>__enter__</code> and <code>__exit__</code> for <code>MyClient</code>, and do <a href="http://effbot.org/zone/python-with-statement.htm" rel="nofollow">a with statement</a>:</p> <pre><code>def connect(): with MyClient(9989) as c: print c.do_stuff() </code></pre> <p>Which is effectively the same as a try-finally.</p>
5
2009-09-25T02:54:02Z
[ "python", "exception", "garbage-collection", "sockets" ]
what happens to a python object when you throw an exception from it
1,475,193
<p>My class contains a socket that connects to a server. Some of the methods of the class can throw an exception. The script I'm running contains an outer loop that catches the exception, logs an error, and creates a new class instance that tries to reconnect to the server.</p> <p>Problem is that the server only handles one connection at a time (by design) and the "old" socket is still connected. So the new connection attempt hangs the script. I can work around this by forcing the old socket closed, but I wonder: why doesn't the socket automatically close?</p> <p>When it is "stuck", netstat shows two sockets connected to the port. The server is waiting for input from the first socket though, it isn't handling the new one yet.</p> <p>I run this against a dummy server that replies "error\n" to every incoming line.</p> <p>EDIT: see my comment on <a href="http://stackoverflow.com/questions/1475193/what-happens-to-a-python-object-when-you-throw-an-exception-from-it/1475198#1475198">Mark Rushakoff's answer below</a>. An assert(False) [that I subsequently catch] from within the exception handler seems to force the socket closed.</p> <pre><code>import socket class MyException(Exception): pass class MyClient(object): def __init__(self, port): self.sock = socket.create_connection(('localhost', port)) self.sockfile = self.sock.makefile() def do_stuff(self): self._send("do_stuff\n") response = self._receive() if response != "ok\n": raise MyException() return response def _send(self, cmd): self.sockfile.write(cmd) self.sockfile.flush() def _receive(self): return self.sockfile.readline() def connect(): c = MyClient(9989) # On the second iteration, do_stuff() tries to send data and # hangs indefinitely. print c.do_stuff() if __name__ == '__main__': for _ in xrange(3): try: connect() except MyException, e: print 'Caught:', e # This would be the workaround if I had access to the # MyClient object: #c.sock.close() #c.sockfile.close() </code></pre> <p>EDIT: Here's the (ugly) server code:</p> <pre><code>import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) s.bind(('localhost', 9989)) s.listen(5) (c,a) = s.accept() f = c.makefile() print f.readline() f.write('error\n') f.flush() (c2,a) = s.accept() f = c.makefile() print f.readline() s.close() </code></pre>
2
2009-09-25T02:49:51Z
1,475,289
<p>Ok, here's the final version. Explicitly close the socket objects when something gets borked.</p> <pre><code>import socket class MyException(Exception): pass class MyClient(object): def __init__(self, port): self.sock = socket.create_connection(('localhost', port)) self.sockfile = self.sock.makefile() def close(self): self.sock.close() self.sockfile.close() def do_stuff(self): self._send("do_stuff\n") response = self._receive() if response != "ok\n": raise MyException() return response def _send(self, cmd): self.sockfile.write(cmd) self.sockfile.flush() def _receive(self): return self.sockfile.readline() def connect(): try: c = MyClient(9989) print c.do_stuff() except MyException: print 'Caught MyException' finally: c.close() if __name__ == '__main__': for _ in xrange(2): connect() </code></pre>
0
2009-09-25T03:33:52Z
[ "python", "exception", "garbage-collection", "sockets" ]
what happens to a python object when you throw an exception from it
1,475,193
<p>My class contains a socket that connects to a server. Some of the methods of the class can throw an exception. The script I'm running contains an outer loop that catches the exception, logs an error, and creates a new class instance that tries to reconnect to the server.</p> <p>Problem is that the server only handles one connection at a time (by design) and the "old" socket is still connected. So the new connection attempt hangs the script. I can work around this by forcing the old socket closed, but I wonder: why doesn't the socket automatically close?</p> <p>When it is "stuck", netstat shows two sockets connected to the port. The server is waiting for input from the first socket though, it isn't handling the new one yet.</p> <p>I run this against a dummy server that replies "error\n" to every incoming line.</p> <p>EDIT: see my comment on <a href="http://stackoverflow.com/questions/1475193/what-happens-to-a-python-object-when-you-throw-an-exception-from-it/1475198#1475198">Mark Rushakoff's answer below</a>. An assert(False) [that I subsequently catch] from within the exception handler seems to force the socket closed.</p> <pre><code>import socket class MyException(Exception): pass class MyClient(object): def __init__(self, port): self.sock = socket.create_connection(('localhost', port)) self.sockfile = self.sock.makefile() def do_stuff(self): self._send("do_stuff\n") response = self._receive() if response != "ok\n": raise MyException() return response def _send(self, cmd): self.sockfile.write(cmd) self.sockfile.flush() def _receive(self): return self.sockfile.readline() def connect(): c = MyClient(9989) # On the second iteration, do_stuff() tries to send data and # hangs indefinitely. print c.do_stuff() if __name__ == '__main__': for _ in xrange(3): try: connect() except MyException, e: print 'Caught:', e # This would be the workaround if I had access to the # MyClient object: #c.sock.close() #c.sockfile.close() </code></pre> <p>EDIT: Here's the (ugly) server code:</p> <pre><code>import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) s.bind(('localhost', 9989)) s.listen(5) (c,a) = s.accept() f = c.makefile() print f.readline() f.write('error\n') f.flush() (c2,a) = s.accept() f = c.makefile() print f.readline() s.close() </code></pre>
2
2009-09-25T02:49:51Z
1,475,305
<p>The garbage collector can be flagged to clean up by setting the relevant object to None.</p>
0
2009-09-25T03:38:37Z
[ "python", "exception", "garbage-collection", "sockets" ]
what happens to a python object when you throw an exception from it
1,475,193
<p>My class contains a socket that connects to a server. Some of the methods of the class can throw an exception. The script I'm running contains an outer loop that catches the exception, logs an error, and creates a new class instance that tries to reconnect to the server.</p> <p>Problem is that the server only handles one connection at a time (by design) and the "old" socket is still connected. So the new connection attempt hangs the script. I can work around this by forcing the old socket closed, but I wonder: why doesn't the socket automatically close?</p> <p>When it is "stuck", netstat shows two sockets connected to the port. The server is waiting for input from the first socket though, it isn't handling the new one yet.</p> <p>I run this against a dummy server that replies "error\n" to every incoming line.</p> <p>EDIT: see my comment on <a href="http://stackoverflow.com/questions/1475193/what-happens-to-a-python-object-when-you-throw-an-exception-from-it/1475198#1475198">Mark Rushakoff's answer below</a>. An assert(False) [that I subsequently catch] from within the exception handler seems to force the socket closed.</p> <pre><code>import socket class MyException(Exception): pass class MyClient(object): def __init__(self, port): self.sock = socket.create_connection(('localhost', port)) self.sockfile = self.sock.makefile() def do_stuff(self): self._send("do_stuff\n") response = self._receive() if response != "ok\n": raise MyException() return response def _send(self, cmd): self.sockfile.write(cmd) self.sockfile.flush() def _receive(self): return self.sockfile.readline() def connect(): c = MyClient(9989) # On the second iteration, do_stuff() tries to send data and # hangs indefinitely. print c.do_stuff() if __name__ == '__main__': for _ in xrange(3): try: connect() except MyException, e: print 'Caught:', e # This would be the workaround if I had access to the # MyClient object: #c.sock.close() #c.sockfile.close() </code></pre> <p>EDIT: Here's the (ugly) server code:</p> <pre><code>import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) s.bind(('localhost', 9989)) s.listen(5) (c,a) = s.accept() f = c.makefile() print f.readline() f.write('error\n') f.flush() (c2,a) = s.accept() f = c.makefile() print f.readline() s.close() </code></pre>
2
2009-09-25T02:49:51Z
1,476,261
<p>Can you really handle the Exception in connect()?</p> <p>I think you should provide a MyClient.close() method, and write connect() like this:</p> <pre><code>def connect():     try:         c = MyClient(9989)         print c.do_stuff()     finally:         c.close() </code></pre> <p>This is in complete analogy with file-like objects (and the with statement)</p>
1
2009-09-25T09:10:03Z
[ "python", "exception", "garbage-collection", "sockets" ]
global counter in Django Application?
1,475,264
<p>I was wondering if there is "global counter" in Django application, like the way I store "global counter" in Servlet Context scope in Tomcat.</p> <p>something like </p> <p>getServletContext().getAttribute("counter"); counter++;</p>
0
2009-09-25T03:18:24Z
1,475,314
<p>When you write a django application (or any wsgi application, for that matter), you don't know beforehand if your application will end up running standalone on a single server, or multithreaded, or multiprocessed, or even in multiple separate machines as part of a load balancing strategy.</p> <p>If you're going to make the constraint "<em>my application only works on single-process servers</em>" then you can use something like this:</p> <pre><code>from django import settings settings.counter += 1 </code></pre> <p>However that constraint is often not feasible. So you must use external storage to your counter. </p> <p>If you want to keep it on memory, maybe a memcached </p> <p>Maybe you just log the requests to this view. So when you want the counter just count the number of entries in the log.</p> <p>The log could be file-based, or it could be a table in the database, just define a new model on your <code>models.py</code>.</p>
1
2009-09-25T03:40:05Z
[ "python", "django" ]
How do you bind a language (python, for example) to another (say, C++)?
1,475,637
<p>I'm far from a python expert but I hear this one all the time, about its C/C++ bindings. How does this concept work, and how does Python (and Java) bind to C-based APIs like OpenGL? This stuff has always been a mystery to me.</p>
15
2009-09-25T05:55:40Z
1,475,650
<p>Generally these languages have a way to load extensions written in C. The Java interface is called JNI (Java Native Interface). Python has comprehensive <a href="http://docs.python.org/extending/index.html" rel="nofollow">documentation</a> about its extension interface.</p> <p>Another option for Python is the <a href="http://docs.python.org/library/ctypes.html" rel="nofollow">ctypes</a> module which allows you to work with dynamically loadable C libraries without having to write custom extension code.</p>
3
2009-09-25T05:59:11Z
[ "java", "python", "binding" ]
How do you bind a language (python, for example) to another (say, C++)?
1,475,637
<p>I'm far from a python expert but I hear this one all the time, about its C/C++ bindings. How does this concept work, and how does Python (and Java) bind to C-based APIs like OpenGL? This stuff has always been a mystery to me.</p>
15
2009-09-25T05:55:40Z
1,475,673
<p>For Perl, there are two ways to call C++ subroutines:</p> <ul> <li><p><a href="http://search.cpan.org/~nwclark/perl-5.8.8/pod/perlxs.pod" rel="nofollow">Perl XS (eXternal Subroutine)</a> (See also <a href="http://en.wikipedia.org/wiki/XS%5F%28Perl%29" rel="nofollow">Wiki</a>) - allows calling subroutines from other languages (mainly, but not exclusively, C) from Perl by compiling C code into modules usable from Perl.</p></li> <li><p><a href="http://www.swig.org/" rel="nofollow">SWIG (Simplified wrapper and interface generator)</a> is a software development tool that connects programs written in C and C++ with a variety of high-level / scripting languages including Perl, PHP, Python, Tcl and Ruby (<em>though it seems SWIG's origins are bindings with Python</em>). </p> <p><a href="http://www.dabeaz.com/SwigMaster/index.html" rel="nofollow">This is a paper that goes into details of how SWIG works</a>, if it was your interest to understand what happens under the hood. </p></li> </ul>
1
2009-09-25T06:08:17Z
[ "java", "python", "binding" ]
How do you bind a language (python, for example) to another (say, C++)?
1,475,637
<p>I'm far from a python expert but I hear this one all the time, about its C/C++ bindings. How does this concept work, and how does Python (and Java) bind to C-based APIs like OpenGL? This stuff has always been a mystery to me.</p>
15
2009-09-25T05:55:40Z
1,475,687
<p>There are basically two ways of integrating c/c++ with python:</p> <ul> <li>extending: accessing c/c++ from python</li> <li>embedding: accessing the python interpreter from c/c++</li> </ul> <p>What you mention is the first case. Its usually achieved by writing <em>wrapper functions</em> that serves as <em>glue code</em> between the different languages that converts the function arguments and data types to match the needed language. Usually a tool called <a href="http://www.swig.org/" rel="nofollow">SWIG</a> is used to generate this glue code.<br></p> <p>For an extensive explanation, see this <a href="http://realmike.org/python/extending%5Fpython.htm" rel="nofollow">tutorial</a>.</p>
1
2009-09-25T06:14:26Z
[ "java", "python", "binding" ]
How do you bind a language (python, for example) to another (say, C++)?
1,475,637
<p>I'm far from a python expert but I hear this one all the time, about its C/C++ bindings. How does this concept work, and how does Python (and Java) bind to C-based APIs like OpenGL? This stuff has always been a mystery to me.</p>
15
2009-09-25T05:55:40Z
1,475,717
<h3>Interpreters Written in C89 with Reflection, Who Knew?</h3> <hr> <p>I have a feeling you are looking for an explanation of the mechanism and not a link to the API or instructions on how to code it. So, as I understand it . . .</p> <p>The main interpreter is typically written in C and is dynamically linked. In a dynamically linked environment, even C89 has a certain amount of reflective behavior. In particular, the <code>dlopen(3)</code> and <code>dlsym(3)</code> calls will load a dynamic (typically ELF) library and look up the address of a symbol named by a string. Give that address, the interpreter can call a function. Even if statically linked, the interpreter can know the address of C functions whose names are compiled into it.</p> <p>So then, it's just a simple matter of having the interpreted code tell the interpreter to call a particular native function in a particular native library.</p> <p>The mechanism can be modular. An extension library for the interpreter, written in the script, can itself invoke the bare hooks for <code>dlopen(3)</code> and <code>dlsym(3)</code> and hook up to a new library that the interpreter never knew about.</p> <p>For passing simple objects by value, a few prototype functions will typically allow various calls. But for structured data objects (imagine stat(2)) the wrapper module needs to know the layout of the data. At some point, either when packaging the extension module or when installing it, a C interface module includes the appropriate header files and in conjunction with handwritten code constructs an interface object. This is why you may need to install something like <code>libsqlite3-dev</code> even if you already had <code>sqlite3</code> on your system; only the <code>-dev</code> package has the .h files needed to recompile the linkage code.</p> <p>I suppose we could sum this up by saying: <em>"it's done with brute force and ignorance"</em>. :-)</p>
11
2009-09-25T06:26:11Z
[ "java", "python", "binding" ]
How do you bind a language (python, for example) to another (say, C++)?
1,475,637
<p>I'm far from a python expert but I hear this one all the time, about its C/C++ bindings. How does this concept work, and how does Python (and Java) bind to C-based APIs like OpenGL? This stuff has always been a mystery to me.</p>
15
2009-09-25T05:55:40Z
1,475,816
<p>The concepts below can be generalized relatively easily, however I'm going to refer specifically to C and Python a lot for clarity.</p> <p><strong>Calling C from Python</strong></p> <p>This can work because most lower level languages/architectures/operating systems have well-defined Application Binary Interfaces which specify all the low-level details of how applications interact with each other and the operating system. As an example here is the ABI for x86-64(AMD64): <a href="http://www.x86-64.org/documentation/abi-0.99.pdf" rel="nofollow">AMD64 System V Application Binary Interface</a> . It specifies all the details of things like calling conventions for functions and linking against C object files.</p> <p>With this information, it's up to the language implementors to </p> <ol> <li><p>Implement the ABI of the language you wish to call into </p></li> <li><p>Provide an interface via the language/library to access the implementation</p></li> </ol> <p>(1) is actually almost gotten for free in most languages due to the sole fact their interpreters/compilers are coded in C, which obviously supports the C ABI :). This is also why there is difficulty in calling C code from implementations of languages not coded in C, for example IronPython (Python implementation in C#) and PyPy (Python implementation in Python) do not have particularly good support for calling C code, though I believe there has been some work in regard to this in IronPython.</p> <p>So to make this concrete, let's assume we have CPython (The standard implementation of Python, done in C). We get (1) for free since our interpreter is written in C and we can access C libraries from our interpreter in the same way we would from any other C program (dlopen,LoadLibrary, whatever). Now we need to offer a way for people writing in our language to access these facilities. Python does this via <a href="http://docs.python.org/c-api/" rel="nofollow">The Python C/C++ API</a> or <a href="http://docs.python.org/library/ctypes.html" rel="nofollow">ctypes</a>. Whenever a programmer writes code using these APIs, we can execute the appropriate library loading/calling code to call into the libraries.</p> <p><strong>Calling Python from C</strong></p> <p>This direction is actually a bit simpler to explain. Continuing from the previous example, our interpreter, CPython is nothing more than a program written in C, so it can export functions and be compiled as a library/linked against by any program we want to write in C. CPython exports a set of C functions for accessing/running Python program and we can just call these functions to run Python code from our application. For example one of the functions exported by the CPython library is:</p> <pre><code>PyObject* PyRun_StringFlags(const char *str, int start, PyObject *globals, PyObject *locals, PyCompilerFlags *flags)¶ </code></pre> <blockquote> <p>Return value: New reference.</p> <p>Execute Python source code from str in the context specified by the dictionaries globals and locals with the compiler flags specified by flags. The parameter start specifies the start token that should be used to parse the source code.</p> </blockquote> <p>We can literally execute Python code by passing this function a string containing valid Python code (and some other details necessary for execution.) See <a href="http://docs.python.org/extending/embedding.html" rel="nofollow">Embedding Python in another application</a> for details.</p>
2
2009-09-25T06:58:07Z
[ "java", "python", "binding" ]
How do you bind a language (python, for example) to another (say, C++)?
1,475,637
<p>I'm far from a python expert but I hear this one all the time, about its C/C++ bindings. How does this concept work, and how does Python (and Java) bind to C-based APIs like OpenGL? This stuff has always been a mystery to me.</p>
15
2009-09-25T05:55:40Z
1,478,058
<p>The main general concept is known as <a href="http://en.wikipedia.org/wiki/Foreign%5Ffunction%5Finterface" rel="nofollow">FFI</a>, "Foreign Function Interface" -- for Java it's JNI, for Python it's the "Python C API", for Perl it's XS, etc, etc, but I think it's important to give you the general term of art to help you research it more thoroughly.</p> <p>Given a FFI, you can write (e.g.) C programs that respect it directly, and/or you can have code generators that produce such C code from metainformation they receive and/or introspect from code written in other languages (often with some help, e.g., to drive the SWIG code generator you typically decorate the info that's in a <code>.h</code> C header file with extra info that's SWIG-specific to get a better wrapper).</p> <p>There are also special languages such as <a href="http://www.cython.org/" rel="nofollow">Cython</a>, an "extended subset" of Python that's geared towards easy generation of FFI code while matching much of Python's syntax and semantics -- may often be the easiest way for mostly-Python programmers to write a Python extension module that compiles down to speedy machine code and maybe uses some existing C-callable libraries.</p> <p>The <a href="http://docs.python.org/library/ctypes.html" rel="nofollow"><code>ctypes</code></a> approach is different from the traditional FFI approaches, though it self-describes as a "foreign function library for Python" -- it relies on the foreign code being available in a DLL (or equivalent, such as an <code>.so</code> dynamic library in Linux), and generates and executes code at run-time to reach into such dynamically loaded C code (typically all done via explicit programming in Python -- I don't know of ctypes wrappers based on introspection and ctypes-code generation, yet). Handy to avoid having to install anything special for simple tasks of accessing existing DLLs with Python, but I think it doesn't scale up as well as the FFI "linker-based" approaches (as it requires more runtime exertion, etc, etc). I don't know of any other implementation of such an approach, targeting other languages, beyond ctypes for Python (I imagine some do exist, given today's prevalence of DLL and .so packaging, and would be curious to learn about them).</p>
6
2009-09-25T15:37:38Z
[ "java", "python", "binding" ]
tail -f in python with no time.sleep
1,475,950
<p>I need to emulate "tail -f" in python, but I don't want to use time.sleep in the reading loop. I want something more elegant like some kind of blocking read, or select.select with timeout, but python 2.6 "select" documentation specifically says: "it cannot be used on regular files to determine whether a file has grown since it was last read." Any other way? In a few days if no solution is given I will read tail's C source code to try to figure it out. I hope they don't use sleep, hehe Thanks.</p> <p>MarioR</p>
24
2009-09-25T07:45:08Z
1,475,971
<p>Why don't you just use <code>subprocess.call</code> on <code>tail</code> itself?</p> <pre><code>subproces.call(['tail', '-f', filename]) </code></pre> <p><strong>Edit:</strong> Fixed to eliminate extra shell process.</p> <p><strong>Edit2:</strong> Fixed to eliminate deprecated <code>os.popen</code> and thus the need to interpolate parameters, escape espaces and other stuff, and then run a shell process.</p>
-2
2009-09-25T07:53:20Z
[ "python" ]
tail -f in python with no time.sleep
1,475,950
<p>I need to emulate "tail -f" in python, but I don't want to use time.sleep in the reading loop. I want something more elegant like some kind of blocking read, or select.select with timeout, but python 2.6 "select" documentation specifically says: "it cannot be used on regular files to determine whether a file has grown since it was last read." Any other way? In a few days if no solution is given I will read tail's C source code to try to figure it out. I hope they don't use sleep, hehe Thanks.</p> <p>MarioR</p>
24
2009-09-25T07:45:08Z
1,475,976
<p>When reading from a file, your only choice is sleep (<a href="http://git.savannah.gnu.org/cgit/coreutils.git/tree/src/tail.c#n877" rel="nofollow">see the source code</a>). If you read from a pipe, you can simply read since the read will block until there is data ready.</p> <p>The reason for this is that the OS doesn't support the notion "wait for someone to write to a file". Only recently, some filesystems added an API where you can listen for changes made to a file but tail is too old to use this API and it's also not available everywhere.</p>
10
2009-09-25T07:53:40Z
[ "python" ]
tail -f in python with no time.sleep
1,475,950
<p>I need to emulate "tail -f" in python, but I don't want to use time.sleep in the reading loop. I want something more elegant like some kind of blocking read, or select.select with timeout, but python 2.6 "select" documentation specifically says: "it cannot be used on regular files to determine whether a file has grown since it was last read." Any other way? In a few days if no solution is given I will read tail's C source code to try to figure it out. I hope they don't use sleep, hehe Thanks.</p> <p>MarioR</p>
24
2009-09-25T07:45:08Z
1,476,006
<p>(update) Either use FS monitors tools </p> <ul> <li>For <a href="http://pyinotify.sourceforge.net/">linux</a></li> <li>For <a href="http://timgolden.me.uk/python/win32%5Fhow%5Fdo%5Fi/watch%5Fdirectory%5Ffor%5Fchanges.html">Windows</a></li> <li>For <a href="http://pypi.python.org/pypi/pyobjc-framework-FSEvents/2.2b2">Mac</a></li> </ul> <p>Or a single sleep usage (which I would you consider as much more elegant).</p> <pre><code>import time def follow(thefile): thefile.seek(0,2) # Go to the end of the file while True: line = thefile.readline() if not line: time.sleep(0.1) # Sleep briefly continue yield line logfile = open("access-log") loglines = follow(logfile) for line in loglines: print line </code></pre>
31
2009-09-25T08:05:04Z
[ "python" ]
tail -f in python with no time.sleep
1,475,950
<p>I need to emulate "tail -f" in python, but I don't want to use time.sleep in the reading loop. I want something more elegant like some kind of blocking read, or select.select with timeout, but python 2.6 "select" documentation specifically says: "it cannot be used on regular files to determine whether a file has grown since it was last read." Any other way? In a few days if no solution is given I will read tail's C source code to try to figure it out. I hope they don't use sleep, hehe Thanks.</p> <p>MarioR</p>
24
2009-09-25T07:45:08Z
1,476,039
<p>IMO you should use sleep, it works on all platform and code will be simple</p> <p>Otherwise you can use platform specific APIs which can tell you when file change e.g. on window use <a href="http://msdn.microsoft.com/en-us/library/aa364417%28VS.85%29.aspx" rel="nofollow">FindFirstChangeNotification</a> on folder and watch for FILE_NOTIFY_CHANGE_LAST_WRITE events</p> <p>On linux i think you can use <a href="http://www.ibm.com/developerworks/linux/library/l-inotify.html" rel="nofollow">i-notify</a></p> <p>On Mac OSX use <a href="http://en.wikipedia.org/wiki/FSEvents" rel="nofollow">FSEvents</a></p>
0
2009-09-25T08:13:03Z
[ "python" ]