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
Why is there module search path instead of typing the directory name + typing the file name?
1,177,513
<p>Is there an advantage? What is it?</p>
2
2009-07-24T13:06:21Z
1,177,526
<p>So that everyone doesn't need to have <em>exactly</em> the same file structure on their hard drive? <code>import C:\Python\lib\module\</code> probably wouldn't work too well on my Mac...</p> <p>Edit: Also, what the heck are you talking about with the working directory? You can <em>certainly</em> use modules outside the working directory, as long as they're on the <code>PYTHONPATH</code>.</p>
6
2009-07-24T13:08:43Z
[ "python", "import", "module-search-path" ]
Change current process environment's LD_LIBRARY_PATH
1,178,094
<p>Is it possible to change environment variables of current process? </p> <p>More specifically in a python script I want to change <code>LD_LIBRARY_PATH</code> so that on import of a module 'x' which depends on some <code>xyz.so</code>, <code>xyz.so</code> is taken from my given path in LD_LIBRARY_PATH </p> <p>is there any other way to dynamically change path from where library is loaded?</p> <p><strong>Edit</strong>: I think I need to mention that I have already tried thing like os.environ["LD_LIBRARY_PATH"] = mypath os.putenv('LD_LIBRARY_PATH', mypath)</p> <p>but these modify the env. for spawned sub-process, not the current process, and module loading doesn't consider the new LD_LIBRARY_PATH</p> <p><strong>Edit2</strong>, so question is can we change environment or something so the library loader sees it and loads from there?</p>
18
2009-07-24T14:33:06Z
1,178,117
<p>well, the environment variables are stored in the dictionary os.environ, so if you want to change , you can do</p> <pre><code>os.environ["PATH"] = "/usr/bin" </code></pre>
-4
2009-07-24T14:37:50Z
[ "python", "shared-libraries", "environment-variables" ]
Change current process environment's LD_LIBRARY_PATH
1,178,094
<p>Is it possible to change environment variables of current process? </p> <p>More specifically in a python script I want to change <code>LD_LIBRARY_PATH</code> so that on import of a module 'x' which depends on some <code>xyz.so</code>, <code>xyz.so</code> is taken from my given path in LD_LIBRARY_PATH </p> <p>is there any other way to dynamically change path from where library is loaded?</p> <p><strong>Edit</strong>: I think I need to mention that I have already tried thing like os.environ["LD_LIBRARY_PATH"] = mypath os.putenv('LD_LIBRARY_PATH', mypath)</p> <p>but these modify the env. for spawned sub-process, not the current process, and module loading doesn't consider the new LD_LIBRARY_PATH</p> <p><strong>Edit2</strong>, so question is can we change environment or something so the library loader sees it and loads from there?</p>
18
2009-07-24T14:33:06Z
1,178,878
<p>In my experience trying to change the way the loader works for a running Python is very tricky; probably OS/version dependent; may not work. One work-around that might help in some circumstances is to launch a sub-process that changes the environment parameter using a shell script and then launch a new Python using the shell.</p>
0
2009-07-24T16:55:45Z
[ "python", "shared-libraries", "environment-variables" ]
Change current process environment's LD_LIBRARY_PATH
1,178,094
<p>Is it possible to change environment variables of current process? </p> <p>More specifically in a python script I want to change <code>LD_LIBRARY_PATH</code> so that on import of a module 'x' which depends on some <code>xyz.so</code>, <code>xyz.so</code> is taken from my given path in LD_LIBRARY_PATH </p> <p>is there any other way to dynamically change path from where library is loaded?</p> <p><strong>Edit</strong>: I think I need to mention that I have already tried thing like os.environ["LD_LIBRARY_PATH"] = mypath os.putenv('LD_LIBRARY_PATH', mypath)</p> <p>but these modify the env. for spawned sub-process, not the current process, and module loading doesn't consider the new LD_LIBRARY_PATH</p> <p><strong>Edit2</strong>, so question is can we change environment or something so the library loader sees it and loads from there?</p>
18
2009-07-24T14:33:06Z
1,186,194
<p>The reason</p> <pre><code>os.environ["LD_LIBRARY_PATH"] = ... </code></pre> <p>doesn't work is simple: this environment variable controls behavior of the dynamic loader (<code>ld-linux.so.2</code> on Linux, <code>ld.so.1</code> on Solaris), but the loader only looks at <code>LD_LIBRARY_PATH</code> once at process startup. Changing the value of <code>LD_LIBRARY_PATH</code> in the current process <em>after</em> that point has no effect (just as the answer to <a href="http://stackoverflow.com/questions/856116/changing-ldlibrarypath-at-runtime-for-ctypes">this</a> question says).</p> <p>You do have some options:<br></p> <p>A. If you know that you are going to need <code>xyz.so</code> from <code>/some/path</code>, and control the execution of python script from the start, then simply set <code>LD_LIBRARY_PATH</code> to your liking (after checking that it is not already so set), and re-execute yourself. This is what <code>Java</code> does.</p> <p>B. You can import <code>/some/path/xyz.so</code> via its absolute path <em>before</em> importing <code>x.so</code>. When you then import <code>x.so</code>, the loader will discover that it has already loaded <code>xyz.so</code>, and will use the already loaded module instead of searching for it again.</p> <p>C. If you build <code>x.so</code> yourself, you can add <code>-Wl,-rpath=/some/path</code> to its link line, and then importing <code>x.so</code> will cause the loader to look for dependent modules in <code>/some/path</code>.</p>
29
2009-07-27T02:33:05Z
[ "python", "shared-libraries", "environment-variables" ]
Change current process environment's LD_LIBRARY_PATH
1,178,094
<p>Is it possible to change environment variables of current process? </p> <p>More specifically in a python script I want to change <code>LD_LIBRARY_PATH</code> so that on import of a module 'x' which depends on some <code>xyz.so</code>, <code>xyz.so</code> is taken from my given path in LD_LIBRARY_PATH </p> <p>is there any other way to dynamically change path from where library is loaded?</p> <p><strong>Edit</strong>: I think I need to mention that I have already tried thing like os.environ["LD_LIBRARY_PATH"] = mypath os.putenv('LD_LIBRARY_PATH', mypath)</p> <p>but these modify the env. for spawned sub-process, not the current process, and module loading doesn't consider the new LD_LIBRARY_PATH</p> <p><strong>Edit2</strong>, so question is can we change environment or something so the library loader sees it and loads from there?</p>
18
2009-07-24T14:33:06Z
16,517,435
<p>Based on the answer from Employed Russian, this is what works for me</p> <pre><code>oracle_libs = os.environ['ORACLE_HOME']+"/lib/" rerun = True if not 'LD_LIBRARY_PATH' in os.environ: os.environ['LD_LIBRARY_PATH'] = ":"+oracle_libs elif not oracle_libs in os.environ.get('LD_LIBRARY_PATH'): os.environ['LD_LIBRARY_PATH'] += ":"+oracle_libs else: rerun = False if rerun: os.execve(os.path.realpath(__file__), sys.argv, os.environ) </code></pre>
7
2013-05-13T08:10:32Z
[ "python", "shared-libraries", "environment-variables" ]
In Python 2.4, how can I strip out characters after ';'?
1,178,335
<p>Let's say I'm parsing a file, which uses <code>;</code> as the comment character. I don't want to parse comments. So if I a line looks like this:</p> <pre><code>example.com. 600 IN MX 8 s1b9.example.net ; hello! </code></pre> <p>Is there an easier/more-elegant way to strip chars out other than this:</p> <pre><code>rtr = '' for line in file: trig = False for char in line: if not trig and char != ';': rtr += char else: trig = True if rtr[max(rtr)] != '\n': rtr += '\n' </code></pre>
18
2009-07-24T15:15:17Z
1,178,356
<p>just do a split on the line by comment then get the first element eg</p> <pre><code>line.split(";")[0] </code></pre>
10
2009-07-24T15:18:36Z
[ "python", "string", "python-2.4" ]
In Python 2.4, how can I strip out characters after ';'?
1,178,335
<p>Let's say I'm parsing a file, which uses <code>;</code> as the comment character. I don't want to parse comments. So if I a line looks like this:</p> <pre><code>example.com. 600 IN MX 8 s1b9.example.net ; hello! </code></pre> <p>Is there an easier/more-elegant way to strip chars out other than this:</p> <pre><code>rtr = '' for line in file: trig = False for char in line: if not trig and char != ';': rtr += char else: trig = True if rtr[max(rtr)] != '\n': rtr += '\n' </code></pre>
18
2009-07-24T15:15:17Z
1,178,360
<p>I'd recommend saying</p> <pre><code>line.split(";")[0] </code></pre> <p>which will give you a string of all characters up to but not including the first ";" character. If no ";" character is present, then it will give you the entire line.</p>
67
2009-07-24T15:18:42Z
[ "python", "string", "python-2.4" ]
In Python 2.4, how can I strip out characters after ';'?
1,178,335
<p>Let's say I'm parsing a file, which uses <code>;</code> as the comment character. I don't want to parse comments. So if I a line looks like this:</p> <pre><code>example.com. 600 IN MX 8 s1b9.example.net ; hello! </code></pre> <p>Is there an easier/more-elegant way to strip chars out other than this:</p> <pre><code>rtr = '' for line in file: trig = False for char in line: if not trig and char != ';': rtr += char else: trig = True if rtr[max(rtr)] != '\n': rtr += '\n' </code></pre>
18
2009-07-24T15:15:17Z
1,178,365
<p>For Python 2.5 or greater, I would use the <a href="http://docs.python.org/library/stdtypes.html?highlight=partition#str.partition" rel="nofollow"><code>partition</code></a> method:</p> <pre><code>rtr = line.partition(';')[0].rstrip() + '\n' </code></pre>
4
2009-07-24T15:19:50Z
[ "python", "string", "python-2.4" ]
In Python 2.4, how can I strip out characters after ';'?
1,178,335
<p>Let's say I'm parsing a file, which uses <code>;</code> as the comment character. I don't want to parse comments. So if I a line looks like this:</p> <pre><code>example.com. 600 IN MX 8 s1b9.example.net ; hello! </code></pre> <p>Is there an easier/more-elegant way to strip chars out other than this:</p> <pre><code>rtr = '' for line in file: trig = False for char in line: if not trig and char != ';': rtr += char else: trig = True if rtr[max(rtr)] != '\n': rtr += '\n' </code></pre>
18
2009-07-24T15:15:17Z
1,178,423
<pre><code>file = open(r'c:\temp\test.txt', 'r') for line in file: print line.split(";")[0].strip() </code></pre>
2
2009-07-24T15:27:49Z
[ "python", "string", "python-2.4" ]
In Python 2.4, how can I strip out characters after ';'?
1,178,335
<p>Let's say I'm parsing a file, which uses <code>;</code> as the comment character. I don't want to parse comments. So if I a line looks like this:</p> <pre><code>example.com. 600 IN MX 8 s1b9.example.net ; hello! </code></pre> <p>Is there an easier/more-elegant way to strip chars out other than this:</p> <pre><code>rtr = '' for line in file: trig = False for char in line: if not trig and char != ';': rtr += char else: trig = True if rtr[max(rtr)] != '\n': rtr += '\n' </code></pre>
18
2009-07-24T15:15:17Z
1,178,529
<p>Reading, splitting, stripping, and joining lines with newline all in one line of python:</p> <pre><code>rtr = '\n'.join(line.split(';')[0].strip() for line in open(r'c:\temp\test.txt', 'r')) </code></pre>
1
2009-07-24T15:46:47Z
[ "python", "string", "python-2.4" ]
In Python 2.4, how can I strip out characters after ';'?
1,178,335
<p>Let's say I'm parsing a file, which uses <code>;</code> as the comment character. I don't want to parse comments. So if I a line looks like this:</p> <pre><code>example.com. 600 IN MX 8 s1b9.example.net ; hello! </code></pre> <p>Is there an easier/more-elegant way to strip chars out other than this:</p> <pre><code>rtr = '' for line in file: trig = False for char in line: if not trig and char != ';': rtr += char else: trig = True if rtr[max(rtr)] != '\n': rtr += '\n' </code></pre>
18
2009-07-24T15:15:17Z
1,178,634
<p>I have not tested this with python but I use similar code else where.</p> <pre><code>import re content = open(r'c:\temp\test.txt', 'r').read() content = re.sub(";.+", "\n") </code></pre>
-2
2009-07-24T16:06:21Z
[ "python", "string", "python-2.4" ]
In Python 2.4, how can I strip out characters after ';'?
1,178,335
<p>Let's say I'm parsing a file, which uses <code>;</code> as the comment character. I don't want to parse comments. So if I a line looks like this:</p> <pre><code>example.com. 600 IN MX 8 s1b9.example.net ; hello! </code></pre> <p>Is there an easier/more-elegant way to strip chars out other than this:</p> <pre><code>rtr = '' for line in file: trig = False for char in line: if not trig and char != ';': rtr += char else: trig = True if rtr[max(rtr)] != '\n': rtr += '\n' </code></pre>
18
2009-07-24T15:15:17Z
1,179,125
<p>So you'll want to split the line on the first semicolon, take everything before it, strip off any lingering whitespace, and append a newline character.</p> <pre><code>rtr = line.split(";", 1)[0].rstrip() + '\n' </code></pre> <p><strong>Links to Documentation:</strong></p> <ul> <li><a href="http://docs.python.org/library/string.html#string.split" rel="nofollow">split</a></li> <li><a href="http://docs.python.org/library/string.html#string.rstrip" rel="nofollow">rstrip</a></li> </ul>
2
2009-07-24T17:46:50Z
[ "python", "string", "python-2.4" ]
In Python 2.4, how can I strip out characters after ';'?
1,178,335
<p>Let's say I'm parsing a file, which uses <code>;</code> as the comment character. I don't want to parse comments. So if I a line looks like this:</p> <pre><code>example.com. 600 IN MX 8 s1b9.example.net ; hello! </code></pre> <p>Is there an easier/more-elegant way to strip chars out other than this:</p> <pre><code>rtr = '' for line in file: trig = False for char in line: if not trig and char != ';': rtr += char else: trig = True if rtr[max(rtr)] != '\n': rtr += '\n' </code></pre>
18
2009-07-24T15:15:17Z
1,183,356
<p>Here is another way :</p> <pre> In [6]: line = "foo;bar" In [7]: line[:line.find(";")] + "\n" Out[7]: 'foo\n' </pre>
0
2009-07-25T23:34:54Z
[ "python", "string", "python-2.4" ]
How can I create bound methods with type()?
1,178,337
<p>I am dynamically generating a function and assigning it to a class. This is a simple/minimal example of what I am trying to achieve:</p> <pre><code>def echo(obj): print obj.hello class Foo(object): hello = "Hello World" spam = type("Spam", (Foo, ), {"echo":echo}) spam.echo() </code></pre> <p>Results in this error</p> <pre><code>Traceback (most recent call last): File "&lt;input&gt;", line 1, in &lt;module&gt; TypeError: unbound method echo() must be called with Spam instance as first argument (got nothing instead) </code></pre> <p>I know if I used the <code>@staticmethod</code> decorator that I can pass <code>spam</code> in as a parameter to echo, but that is not possible for me in my use case.</p> <p>How would I get the <code>echo</code> function to be bound to <code>Spam</code> and access <code>self</code>? Is it possible at all?</p>
1
2009-07-24T15:16:30Z
1,178,371
<p>So far, you only have created a class. You also need to create objects, i.e. instances of that class:</p> <pre><code>Spam = type("Spam", (Foo, ), {"echo":echo}) spam = Spam() spam.echo() </code></pre> <p>If you really want this to be a method on the class, rather than an instance method, wrap it with classmethod (instead of staticmethod).</p>
8
2009-07-24T15:21:28Z
[ "python" ]
How to store arbitrary number of fields in django model?
1,178,551
<p>I'm new to python/django. I need to store an arbitrary number of fields in a django model. I'm wondering if django has something that takes care of this.</p> <p>Typically, I would store some XML in a column to do this. Does django offer some classes that makes this easy to do whether it be XML or some other(better) method?</p> <p>Thanks, Pete</p>
1
2009-07-24T15:51:28Z
1,178,624
<p>There are a lot of approaches to solve this problem, and depending on your situation any of them might work. You could certainly use a TextField to store XML or JSON or any other form of text. In combination with Python's pickle feature you can do some neater stuff.</p> <p>You might look at the Django Pickle Field definition on DjangoSnippets: <a href="http://www.djangosnippets.org/snippets/513/">http://www.djangosnippets.org/snippets/513/</a></p> <p>That allows you to dump Python dictionaries into fields and does some manipulation so that when you reference those fields you can get easy access to the dictionaries without any need to re-parse XML or anything.</p> <p>I imagine you could also explore writing a custom field definition that would do a similar thing for other serialization formats, although I'm not sure how useful that would be.</p> <p>Or you could simply refactor your model to take advantage of ManyToMany fields. You can create a model for a generic key,value pair, then on your primary model you would have a M2M reference to that generic key,value model. In that way you could leverage more of the Django ORM to reference data, etc. </p>
11
2009-07-24T16:03:44Z
[ "python", "django", "django-models" ]
How to store arbitrary number of fields in django model?
1,178,551
<p>I'm new to python/django. I need to store an arbitrary number of fields in a django model. I'm wondering if django has something that takes care of this.</p> <p>Typically, I would store some XML in a column to do this. Does django offer some classes that makes this easy to do whether it be XML or some other(better) method?</p> <p>Thanks, Pete</p>
1
2009-07-24T15:51:28Z
1,178,652
<p>There is a XML field available: <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#xmlfield" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/models/fields/#xmlfield</a></p> <p>But it would force you to do extra parsing on the resulting query. (Which I think you'll have to do to some degree...)</p> <p>I've considered just dumping a list, unicode(mycolumnlist), into a single char field and having just a set number of indexed charfields after that like:</p> <pre><code>class DumbFlexModel(models.Model): available_fields = models.CharField() field1 = models.CharField() field2 = models.CharField() field3 = models.CharField() ... </code></pre> <p>That way you could at least perform a contains query on available_fields to filter results to only those with the field your trying to get vaules for, but then the position is arbitrary, so you'd still have to go through each result and process available_fields get get the position of the value.</p> <p>Or maybe dumping a serialized (<em>pickle.dumps()</em>) list of dictionaries?</p> <p>I'm interested in other suggestions.</p>
0
2009-07-24T16:09:45Z
[ "python", "django", "django-models" ]
Python: encryption as means to prevent data tampering
1,178,789
<p>Many of my company's clients use our data acquisition software in a research basis. Due to the nature of research in general, some of the clients ask that data is encrypted to prevent tampering -- there could be serious ramifications if their data was shown to be falsified.</p> <p>Some of our <em>binary</em> software encrypts output files with a password stored in the source, that looks like random characters. At the software level, we are able to open up encrypted files for read-only operations. If someone <em>really</em> wanted to find out the password so that they could alter data, it would be possible, but it would be a lot of work. </p> <p>I'm looking into using Python for rapid development of another piece of software. To duplicate the functionality of encryption to defeat/discourage data tampering, the best idea I've come up with so far is to just use <code>ctypes</code> with a DLL for file reading/writing operations, so that the method of encryption and decryption is "sufficiently" obfuscated.</p> <p>We are well aware that an "uncrackable" method is unattainable, but at the same time I'm obviously not comfortable with just having the encryption/decryption approaches sitting there in plain text in the Python source code. A "very strong discouragement of data tampering" would be good enough, I think.</p> <p><strong>What would be the best approach to attain a happy medium of encryption or other proof of data integrity using Python?</strong> I saw <a href="http://stackoverflow.com/questions/609127/generating-a-tamper-proof-signature-of-some-data">another post</a> talking about generating a "tamper proof signature", but if a signature was generated in pure Python then it would be trivial to generate a signature for any arbitrary data. We <em>might</em> be able to phone home to prove data integrity, but that seems like a major inconvenience for everyone involved.</p>
1
2009-07-24T16:39:15Z
1,178,816
<p>If you are embedding passwords somewhere, you are already hosed. You can't guarantee anything.</p> <p>However, you could use public key/private key encryption to make sure the data hasn't been tampered with.</p> <p>The way it works is this:</p> <ol> <li>You generate a public key / private key pair.</li> <li>Keep the private key secure, distribute the public key.</li> <li>Hash the data and then sign the hash with the private key.</li> <li>Use the public key to verify the hash.</li> </ol> <p>This effectively renders the data read-only outside your company, and provides your program a simple way to verify that the data hasn't been modified without distributing passwords.</p>
3
2009-07-24T16:45:37Z
[ "python", "encryption", "data-integrity", "tampering" ]
Python: encryption as means to prevent data tampering
1,178,789
<p>Many of my company's clients use our data acquisition software in a research basis. Due to the nature of research in general, some of the clients ask that data is encrypted to prevent tampering -- there could be serious ramifications if their data was shown to be falsified.</p> <p>Some of our <em>binary</em> software encrypts output files with a password stored in the source, that looks like random characters. At the software level, we are able to open up encrypted files for read-only operations. If someone <em>really</em> wanted to find out the password so that they could alter data, it would be possible, but it would be a lot of work. </p> <p>I'm looking into using Python for rapid development of another piece of software. To duplicate the functionality of encryption to defeat/discourage data tampering, the best idea I've come up with so far is to just use <code>ctypes</code> with a DLL for file reading/writing operations, so that the method of encryption and decryption is "sufficiently" obfuscated.</p> <p>We are well aware that an "uncrackable" method is unattainable, but at the same time I'm obviously not comfortable with just having the encryption/decryption approaches sitting there in plain text in the Python source code. A "very strong discouragement of data tampering" would be good enough, I think.</p> <p><strong>What would be the best approach to attain a happy medium of encryption or other proof of data integrity using Python?</strong> I saw <a href="http://stackoverflow.com/questions/609127/generating-a-tamper-proof-signature-of-some-data">another post</a> talking about generating a "tamper proof signature", but if a signature was generated in pure Python then it would be trivial to generate a signature for any arbitrary data. We <em>might</em> be able to phone home to prove data integrity, but that seems like a major inconvenience for everyone involved.</p>
1
2009-07-24T16:39:15Z
1,178,819
<p>As a general principle, you don't want to use encryption to protect against tampering, instead you want to use a digital signature. Encryption gives you <strong>confidentiality</strong>, but you are after <strong>integrity</strong>.</p> <p>Compute a hash value over your data and either store the hash value in a place where you know it cannot be tampered with or digitally sign it.</p> <p>In your case, it seems like you want to ensure that only your software can have generated the files? Like you say, there cannot exist a really secure way to do this when your users have access to the software since they can tear it apart and find any secret keys you include. Given that constraint, I think your idea of using a DLL is about as good as you can do it.</p>
12
2009-07-24T16:46:22Z
[ "python", "encryption", "data-integrity", "tampering" ]
Python: encryption as means to prevent data tampering
1,178,789
<p>Many of my company's clients use our data acquisition software in a research basis. Due to the nature of research in general, some of the clients ask that data is encrypted to prevent tampering -- there could be serious ramifications if their data was shown to be falsified.</p> <p>Some of our <em>binary</em> software encrypts output files with a password stored in the source, that looks like random characters. At the software level, we are able to open up encrypted files for read-only operations. If someone <em>really</em> wanted to find out the password so that they could alter data, it would be possible, but it would be a lot of work. </p> <p>I'm looking into using Python for rapid development of another piece of software. To duplicate the functionality of encryption to defeat/discourage data tampering, the best idea I've come up with so far is to just use <code>ctypes</code> with a DLL for file reading/writing operations, so that the method of encryption and decryption is "sufficiently" obfuscated.</p> <p>We are well aware that an "uncrackable" method is unattainable, but at the same time I'm obviously not comfortable with just having the encryption/decryption approaches sitting there in plain text in the Python source code. A "very strong discouragement of data tampering" would be good enough, I think.</p> <p><strong>What would be the best approach to attain a happy medium of encryption or other proof of data integrity using Python?</strong> I saw <a href="http://stackoverflow.com/questions/609127/generating-a-tamper-proof-signature-of-some-data">another post</a> talking about generating a "tamper proof signature", but if a signature was generated in pure Python then it would be trivial to generate a signature for any arbitrary data. We <em>might</em> be able to phone home to prove data integrity, but that seems like a major inconvenience for everyone involved.</p>
1
2009-07-24T16:39:15Z
1,188,900
<p>Here's another issue. Presumably, your data acquisition software is collecting data from some external source (like some sort of measuring device), then doing whatever processsing is necessary on the raw data and storing the results. Regardless of what method you use in your program, another possible attack vector would be to feed in bad data to the program, and the program itself has no way of knowing that you are feeding in made up data rather than data that came from the measuring device. But this might not be fixable.</p> <p>Another possible attack vector (and probably the one you are concerned about is tampering with the data on the computer after it has been stored. Here's an idea to mitigate that risk: set up a separate server (this could either be something your company would run, or more likely it would be something the client would set up) with a password protected web service that allows a user to add (but not remove) data records. Then have your program, when it collects data, send it to the server (using the password/connection string which is stored in the program). Have your program only write the data to the local machine if it receives confirmation that the data has been successfully stored on the server.</p> <p>Now suppose an attacker tries to tamper with the data on the client. If he can reverse engineer the program then he can of course still send it to the server for storage, just as the program did. But the server will still have the original data, so the tampering will be detectable because the server will end up with both the original and modified data - the client won't be able to erase the original records. (The client program of course does not need to know how to erase records on the server.)</p>
0
2009-07-27T15:37:28Z
[ "python", "encryption", "data-integrity", "tampering" ]
exit failed script run (python)
1,178,989
<p>I have seen several questions about exiting a script after a task is successfully completed, but is there a way to do the same for a script which has failed? I am writing a testing script which just checks that a camera is functioning correctly. If the first test fails it is more than likely that the following tests will also fail; therefore, I want the first failure to invoke an exit and provide output to screen letting me know that there was an error.</p> <p>I hope this is enough information; let me know if more details are required to help me.</p> <p>Thank you!</p>
4
2009-07-24T17:22:47Z
1,179,002
<p>Are you just looking for the <a href="http://docs.python.org/library/sys.html#sys.exit"><code>exit()</code></a> function?</p> <pre><code>import sys if 1 &lt; 0: print &gt;&gt; sys.stderr, "Something is seriously wrong." sys.exit(1) </code></pre> <p>The (optional) parameter of <code>exit()</code> is the return code the script will return to the shell. Usually values different than 0 signal an error.</p>
15
2009-07-24T17:25:19Z
[ "python", "exception", "exit" ]
exit failed script run (python)
1,178,989
<p>I have seen several questions about exiting a script after a task is successfully completed, but is there a way to do the same for a script which has failed? I am writing a testing script which just checks that a camera is functioning correctly. If the first test fails it is more than likely that the following tests will also fail; therefore, I want the first failure to invoke an exit and provide output to screen letting me know that there was an error.</p> <p>I hope this is enough information; let me know if more details are required to help me.</p> <p>Thank you!</p>
4
2009-07-24T17:22:47Z
1,179,014
<p>You can use <a href="http://docs.python.org/library/sys.html#sys.exit" rel="nofollow"><code>sys.exit()</code></a> to exit. However, if any code higher up catches the <a href="http://docs.python.org/library/exceptions.html#exceptions.SystemExit" rel="nofollow"><code>SystemExit</code></a> exception, it won't exit.</p>
3
2009-07-24T17:26:44Z
[ "python", "exception", "exit" ]
exit failed script run (python)
1,178,989
<p>I have seen several questions about exiting a script after a task is successfully completed, but is there a way to do the same for a script which has failed? I am writing a testing script which just checks that a camera is functioning correctly. If the first test fails it is more than likely that the following tests will also fail; therefore, I want the first failure to invoke an exit and provide output to screen letting me know that there was an error.</p> <p>I hope this is enough information; let me know if more details are required to help me.</p> <p>Thank you!</p>
4
2009-07-24T17:22:47Z
1,179,060
<p>You can raise exceptions to identify error conditions. Your top-level code can catch those exceptions and handle them appropriately. You can use <a href="http://docs.python.org/library/sys.html#sys.exit" rel="nofollow">sys.exit</a> to exit. E.g., in Python 2.x:</p> <pre><code>import sys class CameraInitializationError(StandardError): pass def camera_test_1(): pass def camera_test_2(): raise CameraInitializationError('Failed to initialize camera') if __name__ == '__main__': try: camera_test_1() camera_test_2() print 'Camera successfully initialized' except CameraInitializationError, e: print &gt;&gt;sys.stderr, 'ERROR: %s' % e sys.exit(1) </code></pre>
1
2009-07-24T17:36:29Z
[ "python", "exception", "exit" ]
exit failed script run (python)
1,178,989
<p>I have seen several questions about exiting a script after a task is successfully completed, but is there a way to do the same for a script which has failed? I am writing a testing script which just checks that a camera is functioning correctly. If the first test fails it is more than likely that the following tests will also fail; therefore, I want the first failure to invoke an exit and provide output to screen letting me know that there was an error.</p> <p>I hope this is enough information; let me know if more details are required to help me.</p> <p>Thank you!</p>
4
2009-07-24T17:22:47Z
1,180,611
<p>You want to check the return code from the c++ program you are running, and exit if it indicates failure. In the code below, /bin/false and /bin/true are programs that exit with error and success codes, respectively. Replace them with your own program.</p> <pre><code>import os import sys status = os.system('/bin/true') if status != 0: # Failure occurred, exit. print 'true returned error' sys.exit(1) status = os.system('/bin/false') if status != 0: # Failure occurred, exit. print 'false returned error' sys.exit(1) </code></pre> <p>This assumes that the program you're running exits with zero on success, nonzero on failure.</p>
0
2009-07-24T23:10:33Z
[ "python", "exception", "exit" ]
Suggestions for python assert function
1,179,096
<p>I'm using assert multiple times throughout multiple scripts, I was wondering if anyone has any suggestions on a better way to achieve this instead of the functions I have created below.</p> <pre><code>def assert_validation(expected, actual, type='', message=''): if type == '==': assert expected == actual, 'Expected: %s, Actual: %s, %s' %(expected, actual, message) elif type == '!=': assert expected != actual, 'Expected: %s, Actual: %s, %s' %(expected, actual, message) elif type == '&lt;=': assert expected &lt;= actual, 'Expected: %s, Actual: %s, %s' %(expected, actual, message) elif type == '&gt;=': assert expected &gt;= actual, 'Expected: %s, Actual: %s, %s' %(expected, actual, message) def assert_str_validation(expected, actual, type='', message=''): if type == '==': assert str(expected) == str(actual), 'Expected: %s, Actual: %s, %s' %(expected, actual, message) elif type == '!=': assert str(expected) != str(actual), 'Expected: %s, Actual: %s, %s' %(expected, actual, message) elif type == '&lt;=': assert str(expected) &lt;= str(actual), 'Expected: %s, Actual: %s, %s' %(expected, actual, message) elif type == '&gt;=': assert str(expected) &gt;= str(actual), 'Expected: %s, Actual: %s, %s' %(expected, actual, message) </code></pre>
1
2009-07-24T17:42:33Z
1,179,195
<p>Well this is certainly shorter... can you really not just use <code>assert expected == actual</code> or whatever in the scripts themselves?</p> <pre><code>def assert_validation(expected, actual, type='', message='', trans=(lambda x: x)): m = { '==': (lambda e, a: e == a), '!=': (lambda e, a: e != a), '&lt;=': (lambda e, a: e &lt;= a), '&gt;=': (lambda e, a: e &gt;= a), } assert m[type](trans(expected), trans(actual)), 'Expected: %s, Actual: %s, %s' % (expected, actual, message) def assert_str_validation(expected, actual, type='', message=''): assert_validation(expected, actual, type, message, trans=str) </code></pre>
11
2009-07-24T17:58:11Z
[ "python", "assert" ]
Overriding inherited behavior
1,179,213
<p>I am using Multi-table inheritance for an object, and I need to limit the choices of the parent object foreign key references to only the rules that apply the child system.</p> <pre><code>from schedule.models import Event, Rule class AirShowRule(Rule): """ Inheritance of the schedule.Rule """ rule_type = models.TextField(default='onAir') class AirShow(Event): station = models.ForeignKey(Station) image = models.ImageField(upload_to='images/airshow', null=True, blank= True) thumb_image = models.ImageField(upload_to='images/airshow', null=True, blank= True) </code></pre> <p>Now, in the admin, I only want the AirShowRule(s) to be the choices for an AirShow(Event). What I get is all the rules that are in the schedule.event system.</p> <p>I am inheriting from django-schedule found at <a href="http://code.google.com/p/django-schedule/" rel="nofollow">http://code.google.com/p/django-schedule/</a></p>
0
2009-07-24T18:00:58Z
1,180,532
<p>I looked into the structure of the classes listed, and you should add this:</p> <pre><code>class AirShow(Event): ... your stuff... rule = models.ForeignKey(AirShowRule, null = True, blank = True, verbose_name="VERBOSE NAME", help_text="HELP TEXT") </code></pre> <p>that should get everything straight (<strong>changed to "AirShowRule" from "Rule"</strong>)</p> <p>*you should also make sure that you implement <strong>AirShowRule</strong> more completely as I imagine you aren't overriding rule_type, and if you are, I don't think it'll do all that you want*</p> <p>*see: <a href="http://code.google.com/p/django-schedule/source/browse/trunk/schedule/models.py#23" rel="nofollow">models.py:23</a></p> <p>...this line was taken from <a href="http://code.google.com/p/django-schedule/source/browse/trunk/schedule/models.py#103" rel="nofollow">models.py:103</a> with the modification of the arguments: verbose___name &amp; help_text (probably optional, but I'll leave that for you to inspect)</p> <p><strong>Be aware that I haven't used these modules before, but this should give you a push to keep going :)</strong></p>
1
2009-07-24T22:39:51Z
[ "python", "django-models" ]
Expat parsing in python 3
1,179,305
<pre><code>import xml.parsers.expat def start_element(name, attrs): print('Start element:', name, attrs) def end_element(name): print('End element:', name) def character_data(data): print('Character data: %s' % data) parser = xml.parsers.expat.ParserCreate() parser.StartElementHandler = start_element parser.EndElementHandler = end_element parser.CharacterDataHandler = character_data parser.ParseFile(open('sample.xml')) </code></pre> <p>The above works in python 2.6 but not in python 3.0 - any ideas to make it work in python 3 much appreciated. The error I get on the <code>ParseFile</code> line is <code>TypeError: read() did not return a bytes object (type=str)</code></p>
4
2009-07-24T18:19:40Z
1,179,454
<p>you need to open that file as binary:</p> <pre><code>parser.ParseFile(open('sample.xml', 'rb')) </code></pre>
7
2009-07-24T18:47:07Z
[ "python", "python-3.x", "python-2.6" ]
Expat parsing in python 3
1,179,305
<pre><code>import xml.parsers.expat def start_element(name, attrs): print('Start element:', name, attrs) def end_element(name): print('End element:', name) def character_data(data): print('Character data: %s' % data) parser = xml.parsers.expat.ParserCreate() parser.StartElementHandler = start_element parser.EndElementHandler = end_element parser.CharacterDataHandler = character_data parser.ParseFile(open('sample.xml')) </code></pre> <p>The above works in python 2.6 but not in python 3.0 - any ideas to make it work in python 3 much appreciated. The error I get on the <code>ParseFile</code> line is <code>TypeError: read() did not return a bytes object (type=str)</code></p>
4
2009-07-24T18:19:40Z
27,694,193
<p>I ran into this problem while trying to use the <a href="https://github.com/martinblech/xmltodict" rel="nofollow">xmltodict</a> module with Python 3. Under Python 2.7 I had no problems but under Python 3 I got this same error. The solution is the same that was suggested by @SilentGhost:</p> <pre><code>import xmltodict def convert(xml_file, xml_attribs=True): with open(xml_file, "rb") as f: # notice the "rb" mode d = xmltodict.parse(f, xml_attribs=xml_attribs) return d </code></pre>
1
2014-12-29T18:39:17Z
[ "python", "python-3.x", "python-2.6" ]
What does keyword CONSTRAINT do in this CREATE TABLE statement
1,179,352
<p>I'm learning how to use sqlite3 with python. The example in the text book I am following is a database where each Country record has a Region, Country, and Population. </p> <p>The book says:</p> <blockquote> <p>The following snippet uses the CONSTRAINT keyword to specify that no two entries in the table being created will ever have the same values for region and country:</p> </blockquote> <pre><code>&gt;&gt;&gt; cur.execute(''' CREATE TABLE PopByCountry( Region TEXT NOT NULL, Country TEXT NOT NULL, Population INTEGER NOT NULL, CONSTRAINT Country_Key PRIMARY KEY (Region, Country)) ''') </code></pre> <p>Please could you explain what <code>CONSTRAINT Country_Key</code> does here. If I remove it, the PRIMARY KEY statement alone seems to ensure that each country has a unique name for that region.</p>
3
2009-07-24T18:28:44Z
1,179,367
<p>Country_key is simply giving a name to the constraint. If you do not do this the name will be generated for you. This is useful when there are several constraints on the table and you need to drop one of them.</p> <p>As an example for dropping the constraint:</p> <pre><code>ALTER TABLE PopByCountry DROP CONSTRAINT Country_Key </code></pre>
5
2009-07-24T18:31:15Z
[ "python", "sql" ]
What does keyword CONSTRAINT do in this CREATE TABLE statement
1,179,352
<p>I'm learning how to use sqlite3 with python. The example in the text book I am following is a database where each Country record has a Region, Country, and Population. </p> <p>The book says:</p> <blockquote> <p>The following snippet uses the CONSTRAINT keyword to specify that no two entries in the table being created will ever have the same values for region and country:</p> </blockquote> <pre><code>&gt;&gt;&gt; cur.execute(''' CREATE TABLE PopByCountry( Region TEXT NOT NULL, Country TEXT NOT NULL, Population INTEGER NOT NULL, CONSTRAINT Country_Key PRIMARY KEY (Region, Country)) ''') </code></pre> <p>Please could you explain what <code>CONSTRAINT Country_Key</code> does here. If I remove it, the PRIMARY KEY statement alone seems to ensure that each country has a unique name for that region.</p>
3
2009-07-24T18:28:44Z
1,179,387
<p>If you omit CONSTRAINT Contry_Key from the statement, SQL server will generate a name for your PRIMARY KEY constraint for you (the PRIMARY KEY is a type of constraint).</p> <p>By specifically putting CONSTRAINT in the query you are essentially specifying a name for your primary key constraint.</p>
1
2009-07-24T18:35:11Z
[ "python", "sql" ]
Add text to Existing PDF using Python
1,180,115
<p><br> I need to add some extra text to an existing PDF using Python, what is the best way to go about this and what extra modules will I need to install.</p> <p>Note: Ideally I would like to be able to run this on both Windows and Linux, but at a push Linux only will do.</p> <p>Thanks in advance.<br> Richard.</p> <p>Edit: pyPDF and ReportLab look good but neither one will allow me to edit an existing PDF, are there any other options?</p>
50
2009-07-24T20:58:31Z
1,180,127
<p>You may have better luck breaking the problem down into converting PDF into an editable format, writing your changes, then converting it back into PDF. I don't know of a library that lets you directly edit PDF but there are plenty of converters between DOC and PDF for example.</p>
0
2009-07-24T21:03:21Z
[ "python", "pdf" ]
Add text to Existing PDF using Python
1,180,115
<p><br> I need to add some extra text to an existing PDF using Python, what is the best way to go about this and what extra modules will I need to install.</p> <p>Note: Ideally I would like to be able to run this on both Windows and Linux, but at a push Linux only will do.</p> <p>Thanks in advance.<br> Richard.</p> <p>Edit: pyPDF and ReportLab look good but neither one will allow me to edit an existing PDF, are there any other options?</p>
50
2009-07-24T20:58:31Z
1,180,167
<p>Have you tried <a href="http://pybrary.net/pyPdf/" rel="nofollow">pyPdf</a> ?</p> <p>Sorry, it doesn’t have the ability to modify a page’s content.</p>
0
2009-07-24T21:13:14Z
[ "python", "pdf" ]
Add text to Existing PDF using Python
1,180,115
<p><br> I need to add some extra text to an existing PDF using Python, what is the best way to go about this and what extra modules will I need to install.</p> <p>Note: Ideally I would like to be able to run this on both Windows and Linux, but at a push Linux only will do.</p> <p>Thanks in advance.<br> Richard.</p> <p>Edit: pyPDF and ReportLab look good but neither one will allow me to edit an existing PDF, are there any other options?</p>
50
2009-07-24T20:58:31Z
1,180,176
<p>If you're on Windows, this might work:</p> <p><a href="http://www.colorpilot.com/pdfcreatorpilotmanual/How_to_create_or_edit_PDF_with_Python_4.html" rel="nofollow">PDF Creator Pilot</a></p> <p>There's also a whitepaper of a PDF creation and editing framework in Python. It's a little dated, but maybe can give you some useful info:</p> <p><a href="http://legacy.python.org/workshops/2002-02/papers/17/index.htm" rel="nofollow">Using Python as PDF Editing and Processing Framework</a></p>
1
2009-07-24T21:14:54Z
[ "python", "pdf" ]
Add text to Existing PDF using Python
1,180,115
<p><br> I need to add some extra text to an existing PDF using Python, what is the best way to go about this and what extra modules will I need to install.</p> <p>Note: Ideally I would like to be able to run this on both Windows and Linux, but at a push Linux only will do.</p> <p>Thanks in advance.<br> Richard.</p> <p>Edit: pyPDF and ReportLab look good but neither one will allow me to edit an existing PDF, are there any other options?</p>
50
2009-07-24T20:58:31Z
2,180,841
<p>I know this is an older post, but I spent a long time trying to find a solution. I came across a decent one using only ReportLab and PyPDF so I thought I'd share:</p> <ol> <li>read your PDF using PdfFileReader(), we'll call this <em>input</em></li> <li>create a new pdf containing your text to add using ReportLab, save this as a string object</li> <li>read the string object using PdfFileReader(), we'll call this <em>text</em></li> <li>create a new PDF object using PdfFileWriter(), we'll call this <em>output</em></li> <li>iterate through <em>input</em> and apply .mergePage(<em>text</em>.getPage(0)) for each page you want the text added to, then use <em>output</em>.addPage() to add the modified pages to a new document</li> </ol> <p>This works well for simple text additions. See PyPDF's sample for watermarking a document.</p> <p>Here is some code to answer the question below:</p> <pre><code>packet = StringIO.StringIO() can = canvas.Canvas(packet, pagesize=letter) &lt;do something with canvas&gt; can.save() packet.seek(0) input = PdfFileReader(packet) </code></pre> <p>From here you can merge the pages of the input file with another document</p>
56
2010-02-01T23:28:31Z
[ "python", "pdf" ]
Add text to Existing PDF using Python
1,180,115
<p><br> I need to add some extra text to an existing PDF using Python, what is the best way to go about this and what extra modules will I need to install.</p> <p>Note: Ideally I would like to be able to run this on both Windows and Linux, but at a push Linux only will do.</p> <p>Thanks in advance.<br> Richard.</p> <p>Edit: pyPDF and ReportLab look good but neither one will allow me to edit an existing PDF, are there any other options?</p>
50
2009-07-24T20:58:31Z
17,538,003
<p>Here is a complete answer that I found elsewhere:</p> <pre><code>from pyPdf import PdfFileWriter, PdfFileReader import StringIO from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import letter packet = StringIO.StringIO() # create a new PDF with Reportlab can = canvas.Canvas(packet, pagesize=letter) can.drawString(10, 100, "Hello world") can.save() #move to the beginning of the StringIO buffer packet.seek(0) new_pdf = PdfFileReader(packet) # read your existing PDF existing_pdf = PdfFileReader(file("original.pdf", "rb")) output = PdfFileWriter() # add the "watermark" (which is the new pdf) on the existing page page = existing_pdf.getPage(0) page.mergePage(new_pdf.getPage(0)) output.addPage(page) # finally, write "output" to a real file outputStream = file("destination.pdf", "wb") output.write(outputStream) outputStream.close() </code></pre>
42
2013-07-09T00:16:42Z
[ "python", "pdf" ]
Add text to Existing PDF using Python
1,180,115
<p><br> I need to add some extra text to an existing PDF using Python, what is the best way to go about this and what extra modules will I need to install.</p> <p>Note: Ideally I would like to be able to run this on both Windows and Linux, but at a push Linux only will do.</p> <p>Thanks in advance.<br> Richard.</p> <p>Edit: pyPDF and ReportLab look good but neither one will allow me to edit an existing PDF, are there any other options?</p>
50
2009-07-24T20:58:31Z
22,196,937
<p><a href="https://github.com/coherentgraphics/cpdf-binaries" rel="nofollow">cpdf</a> will do the job from the command-line. It isn't python, though (afaik):</p> <pre><code>cpdf -add-text "Line of text" input.pdf -o output .pdf </code></pre>
1
2014-03-05T11:51:36Z
[ "python", "pdf" ]
Add text to Existing PDF using Python
1,180,115
<p><br> I need to add some extra text to an existing PDF using Python, what is the best way to go about this and what extra modules will I need to install.</p> <p>Note: Ideally I would like to be able to run this on both Windows and Linux, but at a push Linux only will do.</p> <p>Thanks in advance.<br> Richard.</p> <p>Edit: pyPDF and ReportLab look good but neither one will allow me to edit an existing PDF, are there any other options?</p>
50
2009-07-24T20:58:31Z
31,353,531
<p><a href="https://github.com/pmaupin/pdfrw/" rel="nofollow">pdfrw</a> will let you read in pages from an existing PDF and draw them to a reportlab canvas (similar to drawing an image). There are examples for this in the pdfrw <a href="https://github.com/pmaupin/pdfrw/tree/master/examples/rl1" rel="nofollow">examples/rl1</a> subdirectory on github. Disclaimer: I am the pdfrw author.</p>
1
2015-07-11T04:47:00Z
[ "python", "pdf" ]
Best way to sort 1M records in Python
1,180,240
<p>I have a service that runs that takes a list of about 1,000,000 dictionaries and does the following</p> <pre><code>myHashTable = {} myLists = { 'hits':{}, 'misses':{}, 'total':{} } sorted = { 'hits':[], 'misses':[], 'total':[] } for item in myList: id = item.pop('id') myHashTable[id] = item for k, v in item.iteritems(): myLists[k][id] = v </code></pre> <p>So, if I had the following list of dictionaries:</p> <pre><code>[ {'id':'id1', 'hits':200, 'misses':300, 'total':400}, {'id':'id2', 'hits':300, 'misses':100, 'total':500}, {'id':'id3', 'hits':100, 'misses':400, 'total':600} ] </code></pre> <p>I end up with</p> <pre><code>myHashTable = { 'id1': {'hits':200, 'misses':300, 'total':400}, 'id2': {'hits':300, 'misses':100, 'total':500}, 'id3': {'hits':100, 'misses':400, 'total':600} } </code></pre> <p>and</p> <pre><code>myLists = { 'hits': {'id1':200, 'id2':300, 'id3':100}, 'misses': {'id1':300, 'id2':100, 'id3':400}, 'total': {'id1':400, 'id2':500, 'id3':600} } </code></pre> <p>I then need to sort all of the data in each of the myLists dictionaries.</p> <p>What I doing currently is something like the following:</p> <pre><code>def doSort(key): sorted[key] = sorted(myLists[key].items(), key=operator.itemgetter(1), reverse=True) which would yield, in the case of misses: [('id3', 400), ('id1', 300), ('id2', 200)] </code></pre> <p>This works great when I have up to 100,000 records or so, but with 1,000,000 it is taking at least 5 - 10 minutes to sort each with a total of 16 (my original list of dictionaries actually has 17 fields including id which is popped)</p> <blockquote> <p><strong>* EDIT *</strong> This service is a ThreadingTCPServer which has a method allowing a client to connect and add new data. The new data may include new records (meaning dictionaries with unique 'id's to what is already in memory) or modified records (meaning the same 'id' with different data for the other key value pairs</p> <p>So, once this is running I would pass in </p> <pre><code>[ {'id':'id1', 'hits':205, 'misses':305, 'total':480}, {'id':'id4', 'hits':30, 'misses':40, 'total':60}, {'id':'id5', 'hits':50, 'misses':90, 'total':20 ] </code></pre> <p>I have been using dictionaries to store the data so that I don't end up with duplicates. After the dictionaries are updated with the new/modified data I resort each of them.</p> <p><strong>* END EDIT *</strong></p> </blockquote> <p>So, what is the best way for me to sort these? Is there a better method?</p>
7
2009-07-24T21:25:24Z
1,180,254
<pre><code>sorted(myLists[key], key=mylists[key].get, reverse=True) </code></pre> <p>should save you some time, though not a lot.</p>
0
2009-07-24T21:30:02Z
[ "python" ]
Best way to sort 1M records in Python
1,180,240
<p>I have a service that runs that takes a list of about 1,000,000 dictionaries and does the following</p> <pre><code>myHashTable = {} myLists = { 'hits':{}, 'misses':{}, 'total':{} } sorted = { 'hits':[], 'misses':[], 'total':[] } for item in myList: id = item.pop('id') myHashTable[id] = item for k, v in item.iteritems(): myLists[k][id] = v </code></pre> <p>So, if I had the following list of dictionaries:</p> <pre><code>[ {'id':'id1', 'hits':200, 'misses':300, 'total':400}, {'id':'id2', 'hits':300, 'misses':100, 'total':500}, {'id':'id3', 'hits':100, 'misses':400, 'total':600} ] </code></pre> <p>I end up with</p> <pre><code>myHashTable = { 'id1': {'hits':200, 'misses':300, 'total':400}, 'id2': {'hits':300, 'misses':100, 'total':500}, 'id3': {'hits':100, 'misses':400, 'total':600} } </code></pre> <p>and</p> <pre><code>myLists = { 'hits': {'id1':200, 'id2':300, 'id3':100}, 'misses': {'id1':300, 'id2':100, 'id3':400}, 'total': {'id1':400, 'id2':500, 'id3':600} } </code></pre> <p>I then need to sort all of the data in each of the myLists dictionaries.</p> <p>What I doing currently is something like the following:</p> <pre><code>def doSort(key): sorted[key] = sorted(myLists[key].items(), key=operator.itemgetter(1), reverse=True) which would yield, in the case of misses: [('id3', 400), ('id1', 300), ('id2', 200)] </code></pre> <p>This works great when I have up to 100,000 records or so, but with 1,000,000 it is taking at least 5 - 10 minutes to sort each with a total of 16 (my original list of dictionaries actually has 17 fields including id which is popped)</p> <blockquote> <p><strong>* EDIT *</strong> This service is a ThreadingTCPServer which has a method allowing a client to connect and add new data. The new data may include new records (meaning dictionaries with unique 'id's to what is already in memory) or modified records (meaning the same 'id' with different data for the other key value pairs</p> <p>So, once this is running I would pass in </p> <pre><code>[ {'id':'id1', 'hits':205, 'misses':305, 'total':480}, {'id':'id4', 'hits':30, 'misses':40, 'total':60}, {'id':'id5', 'hits':50, 'misses':90, 'total':20 ] </code></pre> <p>I have been using dictionaries to store the data so that I don't end up with duplicates. After the dictionaries are updated with the new/modified data I resort each of them.</p> <p><strong>* END EDIT *</strong></p> </blockquote> <p>So, what is the best way for me to sort these? Is there a better method?</p>
7
2009-07-24T21:25:24Z
1,180,255
<p>Honestly, the best way is to not use Python. If performance is a major concern for this, use a faster language.</p>
-4
2009-07-24T21:30:13Z
[ "python" ]
Best way to sort 1M records in Python
1,180,240
<p>I have a service that runs that takes a list of about 1,000,000 dictionaries and does the following</p> <pre><code>myHashTable = {} myLists = { 'hits':{}, 'misses':{}, 'total':{} } sorted = { 'hits':[], 'misses':[], 'total':[] } for item in myList: id = item.pop('id') myHashTable[id] = item for k, v in item.iteritems(): myLists[k][id] = v </code></pre> <p>So, if I had the following list of dictionaries:</p> <pre><code>[ {'id':'id1', 'hits':200, 'misses':300, 'total':400}, {'id':'id2', 'hits':300, 'misses':100, 'total':500}, {'id':'id3', 'hits':100, 'misses':400, 'total':600} ] </code></pre> <p>I end up with</p> <pre><code>myHashTable = { 'id1': {'hits':200, 'misses':300, 'total':400}, 'id2': {'hits':300, 'misses':100, 'total':500}, 'id3': {'hits':100, 'misses':400, 'total':600} } </code></pre> <p>and</p> <pre><code>myLists = { 'hits': {'id1':200, 'id2':300, 'id3':100}, 'misses': {'id1':300, 'id2':100, 'id3':400}, 'total': {'id1':400, 'id2':500, 'id3':600} } </code></pre> <p>I then need to sort all of the data in each of the myLists dictionaries.</p> <p>What I doing currently is something like the following:</p> <pre><code>def doSort(key): sorted[key] = sorted(myLists[key].items(), key=operator.itemgetter(1), reverse=True) which would yield, in the case of misses: [('id3', 400), ('id1', 300), ('id2', 200)] </code></pre> <p>This works great when I have up to 100,000 records or so, but with 1,000,000 it is taking at least 5 - 10 minutes to sort each with a total of 16 (my original list of dictionaries actually has 17 fields including id which is popped)</p> <blockquote> <p><strong>* EDIT *</strong> This service is a ThreadingTCPServer which has a method allowing a client to connect and add new data. The new data may include new records (meaning dictionaries with unique 'id's to what is already in memory) or modified records (meaning the same 'id' with different data for the other key value pairs</p> <p>So, once this is running I would pass in </p> <pre><code>[ {'id':'id1', 'hits':205, 'misses':305, 'total':480}, {'id':'id4', 'hits':30, 'misses':40, 'total':60}, {'id':'id5', 'hits':50, 'misses':90, 'total':20 ] </code></pre> <p>I have been using dictionaries to store the data so that I don't end up with duplicates. After the dictionaries are updated with the new/modified data I resort each of them.</p> <p><strong>* END EDIT *</strong></p> </blockquote> <p>So, what is the best way for me to sort these? Is there a better method?</p>
7
2009-07-24T21:25:24Z
1,180,274
<p>What you really want is an ordered container, instead of an unordered one. That would implicitly sort the results as they're inserted. The standard data structure for this is a tree.</p> <p>However, there doesn't seem to be one of these in Python. I can't explain that; this is a core, fundamental data type in any language. Python's dict and set are both unordered containers, which map to the basic data structure of a hash table. It should definitely have an optimized tree data structure; there are many things you can do with them that are impossible with a hash table, and they're quite tricky to implement well, so people generally don't want to be doing it themselves.</p> <p>(There's also nothing mapping to a linked list, which also should be a core data type. No, a deque is not equivalent.)</p> <p>I don't have an existing ordered container implementation to point you to (and it should probably be implemented natively, not in Python), but hopefully this will point you in the right direction.</p> <p>A good tree implementation should support iterating across a range by value ("iterate all values from [2,100] in order"), find next/prev value from any other node in O(1), efficient range extraction ("delete all values in [2,100] and return them in a new tree"), etc. If anyone has a well-optimized data structure like this for Python, I'd love to know about it. (Not all operations fit nicely in Python's data model; for example, to get next/prev value from another value, you need a reference to a node, not the value itself.)</p>
4
2009-07-24T21:34:45Z
[ "python" ]
Best way to sort 1M records in Python
1,180,240
<p>I have a service that runs that takes a list of about 1,000,000 dictionaries and does the following</p> <pre><code>myHashTable = {} myLists = { 'hits':{}, 'misses':{}, 'total':{} } sorted = { 'hits':[], 'misses':[], 'total':[] } for item in myList: id = item.pop('id') myHashTable[id] = item for k, v in item.iteritems(): myLists[k][id] = v </code></pre> <p>So, if I had the following list of dictionaries:</p> <pre><code>[ {'id':'id1', 'hits':200, 'misses':300, 'total':400}, {'id':'id2', 'hits':300, 'misses':100, 'total':500}, {'id':'id3', 'hits':100, 'misses':400, 'total':600} ] </code></pre> <p>I end up with</p> <pre><code>myHashTable = { 'id1': {'hits':200, 'misses':300, 'total':400}, 'id2': {'hits':300, 'misses':100, 'total':500}, 'id3': {'hits':100, 'misses':400, 'total':600} } </code></pre> <p>and</p> <pre><code>myLists = { 'hits': {'id1':200, 'id2':300, 'id3':100}, 'misses': {'id1':300, 'id2':100, 'id3':400}, 'total': {'id1':400, 'id2':500, 'id3':600} } </code></pre> <p>I then need to sort all of the data in each of the myLists dictionaries.</p> <p>What I doing currently is something like the following:</p> <pre><code>def doSort(key): sorted[key] = sorted(myLists[key].items(), key=operator.itemgetter(1), reverse=True) which would yield, in the case of misses: [('id3', 400), ('id1', 300), ('id2', 200)] </code></pre> <p>This works great when I have up to 100,000 records or so, but with 1,000,000 it is taking at least 5 - 10 minutes to sort each with a total of 16 (my original list of dictionaries actually has 17 fields including id which is popped)</p> <blockquote> <p><strong>* EDIT *</strong> This service is a ThreadingTCPServer which has a method allowing a client to connect and add new data. The new data may include new records (meaning dictionaries with unique 'id's to what is already in memory) or modified records (meaning the same 'id' with different data for the other key value pairs</p> <p>So, once this is running I would pass in </p> <pre><code>[ {'id':'id1', 'hits':205, 'misses':305, 'total':480}, {'id':'id4', 'hits':30, 'misses':40, 'total':60}, {'id':'id5', 'hits':50, 'misses':90, 'total':20 ] </code></pre> <p>I have been using dictionaries to store the data so that I don't end up with duplicates. After the dictionaries are updated with the new/modified data I resort each of them.</p> <p><strong>* END EDIT *</strong></p> </blockquote> <p>So, what is the best way for me to sort these? Is there a better method?</p>
7
2009-07-24T21:25:24Z
1,180,275
<p>If you have a fixed number of fields, use tuples instead of dictionaries. Place the field you want to sort on in first position, and just use <code>mylist.sort()</code></p>
1
2009-07-24T21:34:58Z
[ "python" ]
Best way to sort 1M records in Python
1,180,240
<p>I have a service that runs that takes a list of about 1,000,000 dictionaries and does the following</p> <pre><code>myHashTable = {} myLists = { 'hits':{}, 'misses':{}, 'total':{} } sorted = { 'hits':[], 'misses':[], 'total':[] } for item in myList: id = item.pop('id') myHashTable[id] = item for k, v in item.iteritems(): myLists[k][id] = v </code></pre> <p>So, if I had the following list of dictionaries:</p> <pre><code>[ {'id':'id1', 'hits':200, 'misses':300, 'total':400}, {'id':'id2', 'hits':300, 'misses':100, 'total':500}, {'id':'id3', 'hits':100, 'misses':400, 'total':600} ] </code></pre> <p>I end up with</p> <pre><code>myHashTable = { 'id1': {'hits':200, 'misses':300, 'total':400}, 'id2': {'hits':300, 'misses':100, 'total':500}, 'id3': {'hits':100, 'misses':400, 'total':600} } </code></pre> <p>and</p> <pre><code>myLists = { 'hits': {'id1':200, 'id2':300, 'id3':100}, 'misses': {'id1':300, 'id2':100, 'id3':400}, 'total': {'id1':400, 'id2':500, 'id3':600} } </code></pre> <p>I then need to sort all of the data in each of the myLists dictionaries.</p> <p>What I doing currently is something like the following:</p> <pre><code>def doSort(key): sorted[key] = sorted(myLists[key].items(), key=operator.itemgetter(1), reverse=True) which would yield, in the case of misses: [('id3', 400), ('id1', 300), ('id2', 200)] </code></pre> <p>This works great when I have up to 100,000 records or so, but with 1,000,000 it is taking at least 5 - 10 minutes to sort each with a total of 16 (my original list of dictionaries actually has 17 fields including id which is popped)</p> <blockquote> <p><strong>* EDIT *</strong> This service is a ThreadingTCPServer which has a method allowing a client to connect and add new data. The new data may include new records (meaning dictionaries with unique 'id's to what is already in memory) or modified records (meaning the same 'id' with different data for the other key value pairs</p> <p>So, once this is running I would pass in </p> <pre><code>[ {'id':'id1', 'hits':205, 'misses':305, 'total':480}, {'id':'id4', 'hits':30, 'misses':40, 'total':60}, {'id':'id5', 'hits':50, 'misses':90, 'total':20 ] </code></pre> <p>I have been using dictionaries to store the data so that I don't end up with duplicates. After the dictionaries are updated with the new/modified data I resort each of them.</p> <p><strong>* END EDIT *</strong></p> </blockquote> <p>So, what is the best way for me to sort these? Is there a better method?</p>
7
2009-07-24T21:25:24Z
1,180,281
<p>I would look into using a different sorting algorithm. Something like a Merge Sort might work. Break the list up into smaller lists and sort them individually. Then loop.</p> <p>Pseudo code:</p> <pre><code>list1 = [] // sorted separately list2 = [] // sorted separately // Recombine sorted lists result = [] while (list1.hasMoreElements || list2.hasMoreElements): if (! list1.hasMoreElements): result.addAll(list2) break elseif (! list2.hasMoreElements): result.AddAll(list1) break if (list1.peek &lt; list2.peek): result.add(list1.pop) else: result.add(list2.pop) </code></pre>
0
2009-07-24T21:37:14Z
[ "python" ]
Best way to sort 1M records in Python
1,180,240
<p>I have a service that runs that takes a list of about 1,000,000 dictionaries and does the following</p> <pre><code>myHashTable = {} myLists = { 'hits':{}, 'misses':{}, 'total':{} } sorted = { 'hits':[], 'misses':[], 'total':[] } for item in myList: id = item.pop('id') myHashTable[id] = item for k, v in item.iteritems(): myLists[k][id] = v </code></pre> <p>So, if I had the following list of dictionaries:</p> <pre><code>[ {'id':'id1', 'hits':200, 'misses':300, 'total':400}, {'id':'id2', 'hits':300, 'misses':100, 'total':500}, {'id':'id3', 'hits':100, 'misses':400, 'total':600} ] </code></pre> <p>I end up with</p> <pre><code>myHashTable = { 'id1': {'hits':200, 'misses':300, 'total':400}, 'id2': {'hits':300, 'misses':100, 'total':500}, 'id3': {'hits':100, 'misses':400, 'total':600} } </code></pre> <p>and</p> <pre><code>myLists = { 'hits': {'id1':200, 'id2':300, 'id3':100}, 'misses': {'id1':300, 'id2':100, 'id3':400}, 'total': {'id1':400, 'id2':500, 'id3':600} } </code></pre> <p>I then need to sort all of the data in each of the myLists dictionaries.</p> <p>What I doing currently is something like the following:</p> <pre><code>def doSort(key): sorted[key] = sorted(myLists[key].items(), key=operator.itemgetter(1), reverse=True) which would yield, in the case of misses: [('id3', 400), ('id1', 300), ('id2', 200)] </code></pre> <p>This works great when I have up to 100,000 records or so, but with 1,000,000 it is taking at least 5 - 10 minutes to sort each with a total of 16 (my original list of dictionaries actually has 17 fields including id which is popped)</p> <blockquote> <p><strong>* EDIT *</strong> This service is a ThreadingTCPServer which has a method allowing a client to connect and add new data. The new data may include new records (meaning dictionaries with unique 'id's to what is already in memory) or modified records (meaning the same 'id' with different data for the other key value pairs</p> <p>So, once this is running I would pass in </p> <pre><code>[ {'id':'id1', 'hits':205, 'misses':305, 'total':480}, {'id':'id4', 'hits':30, 'misses':40, 'total':60}, {'id':'id5', 'hits':50, 'misses':90, 'total':20 ] </code></pre> <p>I have been using dictionaries to store the data so that I don't end up with duplicates. After the dictionaries are updated with the new/modified data I resort each of them.</p> <p><strong>* END EDIT *</strong></p> </blockquote> <p>So, what is the best way for me to sort these? Is there a better method?</p>
7
2009-07-24T21:25:24Z
1,180,286
<p>You may find this related answer from Guido: <a href="http://neopythonic.blogspot.com/2008/10/sorting-million-32-bit-integers-in-2mb.html">Sorting a million 32-bit integers in 2MB of RAM using Python</a></p>
12
2009-07-24T21:38:22Z
[ "python" ]
Best way to sort 1M records in Python
1,180,240
<p>I have a service that runs that takes a list of about 1,000,000 dictionaries and does the following</p> <pre><code>myHashTable = {} myLists = { 'hits':{}, 'misses':{}, 'total':{} } sorted = { 'hits':[], 'misses':[], 'total':[] } for item in myList: id = item.pop('id') myHashTable[id] = item for k, v in item.iteritems(): myLists[k][id] = v </code></pre> <p>So, if I had the following list of dictionaries:</p> <pre><code>[ {'id':'id1', 'hits':200, 'misses':300, 'total':400}, {'id':'id2', 'hits':300, 'misses':100, 'total':500}, {'id':'id3', 'hits':100, 'misses':400, 'total':600} ] </code></pre> <p>I end up with</p> <pre><code>myHashTable = { 'id1': {'hits':200, 'misses':300, 'total':400}, 'id2': {'hits':300, 'misses':100, 'total':500}, 'id3': {'hits':100, 'misses':400, 'total':600} } </code></pre> <p>and</p> <pre><code>myLists = { 'hits': {'id1':200, 'id2':300, 'id3':100}, 'misses': {'id1':300, 'id2':100, 'id3':400}, 'total': {'id1':400, 'id2':500, 'id3':600} } </code></pre> <p>I then need to sort all of the data in each of the myLists dictionaries.</p> <p>What I doing currently is something like the following:</p> <pre><code>def doSort(key): sorted[key] = sorted(myLists[key].items(), key=operator.itemgetter(1), reverse=True) which would yield, in the case of misses: [('id3', 400), ('id1', 300), ('id2', 200)] </code></pre> <p>This works great when I have up to 100,000 records or so, but with 1,000,000 it is taking at least 5 - 10 minutes to sort each with a total of 16 (my original list of dictionaries actually has 17 fields including id which is popped)</p> <blockquote> <p><strong>* EDIT *</strong> This service is a ThreadingTCPServer which has a method allowing a client to connect and add new data. The new data may include new records (meaning dictionaries with unique 'id's to what is already in memory) or modified records (meaning the same 'id' with different data for the other key value pairs</p> <p>So, once this is running I would pass in </p> <pre><code>[ {'id':'id1', 'hits':205, 'misses':305, 'total':480}, {'id':'id4', 'hits':30, 'misses':40, 'total':60}, {'id':'id5', 'hits':50, 'misses':90, 'total':20 ] </code></pre> <p>I have been using dictionaries to store the data so that I don't end up with duplicates. After the dictionaries are updated with the new/modified data I resort each of them.</p> <p><strong>* END EDIT *</strong></p> </blockquote> <p>So, what is the best way for me to sort these? Is there a better method?</p>
7
2009-07-24T21:25:24Z
1,180,313
<p>Others have provided some excellent advices, try them out. </p> <p>As a general advice, in situations like that you need to profile your code. Know exactly where most of the time is spent. Bottlenecks hide well, in places you least expect them to be.<br> If there is a lot of number crunching involved then a JIT compiler like the (now-dead) psyco might also help. When processing takes minutes or hours 2x speed-up really counts.</p> <ul> <li><a href="http://docs.python.org/library/profile.html" rel="nofollow">http://docs.python.org/library/profile.html</a></li> <li><a href="http://www.vrplumber.com/programming/runsnakerun/" rel="nofollow">http://www.vrplumber.com/programming/runsnakerun/</a> </li> <li><a href="http://psyco.sourceforge.net/" rel="nofollow">http://psyco.sourceforge.net/</a></li> </ul>
1
2009-07-24T21:43:50Z
[ "python" ]
Best way to sort 1M records in Python
1,180,240
<p>I have a service that runs that takes a list of about 1,000,000 dictionaries and does the following</p> <pre><code>myHashTable = {} myLists = { 'hits':{}, 'misses':{}, 'total':{} } sorted = { 'hits':[], 'misses':[], 'total':[] } for item in myList: id = item.pop('id') myHashTable[id] = item for k, v in item.iteritems(): myLists[k][id] = v </code></pre> <p>So, if I had the following list of dictionaries:</p> <pre><code>[ {'id':'id1', 'hits':200, 'misses':300, 'total':400}, {'id':'id2', 'hits':300, 'misses':100, 'total':500}, {'id':'id3', 'hits':100, 'misses':400, 'total':600} ] </code></pre> <p>I end up with</p> <pre><code>myHashTable = { 'id1': {'hits':200, 'misses':300, 'total':400}, 'id2': {'hits':300, 'misses':100, 'total':500}, 'id3': {'hits':100, 'misses':400, 'total':600} } </code></pre> <p>and</p> <pre><code>myLists = { 'hits': {'id1':200, 'id2':300, 'id3':100}, 'misses': {'id1':300, 'id2':100, 'id3':400}, 'total': {'id1':400, 'id2':500, 'id3':600} } </code></pre> <p>I then need to sort all of the data in each of the myLists dictionaries.</p> <p>What I doing currently is something like the following:</p> <pre><code>def doSort(key): sorted[key] = sorted(myLists[key].items(), key=operator.itemgetter(1), reverse=True) which would yield, in the case of misses: [('id3', 400), ('id1', 300), ('id2', 200)] </code></pre> <p>This works great when I have up to 100,000 records or so, but with 1,000,000 it is taking at least 5 - 10 minutes to sort each with a total of 16 (my original list of dictionaries actually has 17 fields including id which is popped)</p> <blockquote> <p><strong>* EDIT *</strong> This service is a ThreadingTCPServer which has a method allowing a client to connect and add new data. The new data may include new records (meaning dictionaries with unique 'id's to what is already in memory) or modified records (meaning the same 'id' with different data for the other key value pairs</p> <p>So, once this is running I would pass in </p> <pre><code>[ {'id':'id1', 'hits':205, 'misses':305, 'total':480}, {'id':'id4', 'hits':30, 'misses':40, 'total':60}, {'id':'id5', 'hits':50, 'misses':90, 'total':20 ] </code></pre> <p>I have been using dictionaries to store the data so that I don't end up with duplicates. After the dictionaries are updated with the new/modified data I resort each of them.</p> <p><strong>* END EDIT *</strong></p> </blockquote> <p>So, what is the best way for me to sort these? Is there a better method?</p>
7
2009-07-24T21:25:24Z
1,180,367
<p>Glenn Maynard is correct that a sorted mapping would be appropriate here. This is one for python: <a href="http://wiki.zope.org/ZODB/guide/node6.html#SECTION000630000000000000000" rel="nofollow">http://wiki.zope.org/ZODB/guide/node6.html#SECTION000630000000000000000</a></p>
0
2009-07-24T21:54:18Z
[ "python" ]
Best way to sort 1M records in Python
1,180,240
<p>I have a service that runs that takes a list of about 1,000,000 dictionaries and does the following</p> <pre><code>myHashTable = {} myLists = { 'hits':{}, 'misses':{}, 'total':{} } sorted = { 'hits':[], 'misses':[], 'total':[] } for item in myList: id = item.pop('id') myHashTable[id] = item for k, v in item.iteritems(): myLists[k][id] = v </code></pre> <p>So, if I had the following list of dictionaries:</p> <pre><code>[ {'id':'id1', 'hits':200, 'misses':300, 'total':400}, {'id':'id2', 'hits':300, 'misses':100, 'total':500}, {'id':'id3', 'hits':100, 'misses':400, 'total':600} ] </code></pre> <p>I end up with</p> <pre><code>myHashTable = { 'id1': {'hits':200, 'misses':300, 'total':400}, 'id2': {'hits':300, 'misses':100, 'total':500}, 'id3': {'hits':100, 'misses':400, 'total':600} } </code></pre> <p>and</p> <pre><code>myLists = { 'hits': {'id1':200, 'id2':300, 'id3':100}, 'misses': {'id1':300, 'id2':100, 'id3':400}, 'total': {'id1':400, 'id2':500, 'id3':600} } </code></pre> <p>I then need to sort all of the data in each of the myLists dictionaries.</p> <p>What I doing currently is something like the following:</p> <pre><code>def doSort(key): sorted[key] = sorted(myLists[key].items(), key=operator.itemgetter(1), reverse=True) which would yield, in the case of misses: [('id3', 400), ('id1', 300), ('id2', 200)] </code></pre> <p>This works great when I have up to 100,000 records or so, but with 1,000,000 it is taking at least 5 - 10 minutes to sort each with a total of 16 (my original list of dictionaries actually has 17 fields including id which is popped)</p> <blockquote> <p><strong>* EDIT *</strong> This service is a ThreadingTCPServer which has a method allowing a client to connect and add new data. The new data may include new records (meaning dictionaries with unique 'id's to what is already in memory) or modified records (meaning the same 'id' with different data for the other key value pairs</p> <p>So, once this is running I would pass in </p> <pre><code>[ {'id':'id1', 'hits':205, 'misses':305, 'total':480}, {'id':'id4', 'hits':30, 'misses':40, 'total':60}, {'id':'id5', 'hits':50, 'misses':90, 'total':20 ] </code></pre> <p>I have been using dictionaries to store the data so that I don't end up with duplicates. After the dictionaries are updated with the new/modified data I resort each of them.</p> <p><strong>* END EDIT *</strong></p> </blockquote> <p>So, what is the best way for me to sort these? Is there a better method?</p>
7
2009-07-24T21:25:24Z
1,180,373
<p>This seems to be pretty fast.</p> <pre><code>raw= [ {'id':'id1', 'hits':200, 'misses':300, 'total':400}, {'id':'id2', 'hits':300, 'misses':100, 'total':500}, {'id':'id3', 'hits':100, 'misses':400, 'total':600} ] hits= [ (r['hits'],r['id']) for r in raw ] hits.sort() misses = [ (r['misses'],r['id']) for r in raw ] misses.sort() total = [ (r['total'],r['id']) for r in raw ] total.sort() </code></pre> <p>Yes, it makes three passes through the raw data. I think it's faster than pulling out the data in one pass.</p>
1
2009-07-24T21:55:14Z
[ "python" ]
Best way to sort 1M records in Python
1,180,240
<p>I have a service that runs that takes a list of about 1,000,000 dictionaries and does the following</p> <pre><code>myHashTable = {} myLists = { 'hits':{}, 'misses':{}, 'total':{} } sorted = { 'hits':[], 'misses':[], 'total':[] } for item in myList: id = item.pop('id') myHashTable[id] = item for k, v in item.iteritems(): myLists[k][id] = v </code></pre> <p>So, if I had the following list of dictionaries:</p> <pre><code>[ {'id':'id1', 'hits':200, 'misses':300, 'total':400}, {'id':'id2', 'hits':300, 'misses':100, 'total':500}, {'id':'id3', 'hits':100, 'misses':400, 'total':600} ] </code></pre> <p>I end up with</p> <pre><code>myHashTable = { 'id1': {'hits':200, 'misses':300, 'total':400}, 'id2': {'hits':300, 'misses':100, 'total':500}, 'id3': {'hits':100, 'misses':400, 'total':600} } </code></pre> <p>and</p> <pre><code>myLists = { 'hits': {'id1':200, 'id2':300, 'id3':100}, 'misses': {'id1':300, 'id2':100, 'id3':400}, 'total': {'id1':400, 'id2':500, 'id3':600} } </code></pre> <p>I then need to sort all of the data in each of the myLists dictionaries.</p> <p>What I doing currently is something like the following:</p> <pre><code>def doSort(key): sorted[key] = sorted(myLists[key].items(), key=operator.itemgetter(1), reverse=True) which would yield, in the case of misses: [('id3', 400), ('id1', 300), ('id2', 200)] </code></pre> <p>This works great when I have up to 100,000 records or so, but with 1,000,000 it is taking at least 5 - 10 minutes to sort each with a total of 16 (my original list of dictionaries actually has 17 fields including id which is popped)</p> <blockquote> <p><strong>* EDIT *</strong> This service is a ThreadingTCPServer which has a method allowing a client to connect and add new data. The new data may include new records (meaning dictionaries with unique 'id's to what is already in memory) or modified records (meaning the same 'id' with different data for the other key value pairs</p> <p>So, once this is running I would pass in </p> <pre><code>[ {'id':'id1', 'hits':205, 'misses':305, 'total':480}, {'id':'id4', 'hits':30, 'misses':40, 'total':60}, {'id':'id5', 'hits':50, 'misses':90, 'total':20 ] </code></pre> <p>I have been using dictionaries to store the data so that I don't end up with duplicates. After the dictionaries are updated with the new/modified data I resort each of them.</p> <p><strong>* END EDIT *</strong></p> </blockquote> <p>So, what is the best way for me to sort these? Is there a better method?</p>
7
2009-07-24T21:25:24Z
1,180,503
<p>Instead of trying to keep your list ordered, maybe you can get by with a heap queue. It lets you push any item, keeping the 'smallest' one at <code>h[0]</code>, and popping this item (and 'bubbling' the next smallest) is an <code>O(nlogn)</code> operation.</p> <p>so, just ask yourself: </p> <ul> <li><p>do i need the whole list ordered all the time? : use an ordered structure (like Zope's BTree package, as <a href="http://stackoverflow.com/questions/1180240/best-way-to-sort-1m-records-in-python/1180367#1180367">mentioned</a> by Ealdwulf)</p></li> <li><p>or the whole list ordered but only after a day's work of random insertions?: use sort like you're doing, or like <a href="http://stackoverflow.com/questions/1180240/best-way-to-sort-1m-records-in-python/1180373#1180373">S.Lott's answer</a></p></li> <li><p>or just a few 'smallest' items at any moment? : use <code>heapq</code></p></li> </ul>
1
2009-07-24T22:32:29Z
[ "python" ]
Best way to sort 1M records in Python
1,180,240
<p>I have a service that runs that takes a list of about 1,000,000 dictionaries and does the following</p> <pre><code>myHashTable = {} myLists = { 'hits':{}, 'misses':{}, 'total':{} } sorted = { 'hits':[], 'misses':[], 'total':[] } for item in myList: id = item.pop('id') myHashTable[id] = item for k, v in item.iteritems(): myLists[k][id] = v </code></pre> <p>So, if I had the following list of dictionaries:</p> <pre><code>[ {'id':'id1', 'hits':200, 'misses':300, 'total':400}, {'id':'id2', 'hits':300, 'misses':100, 'total':500}, {'id':'id3', 'hits':100, 'misses':400, 'total':600} ] </code></pre> <p>I end up with</p> <pre><code>myHashTable = { 'id1': {'hits':200, 'misses':300, 'total':400}, 'id2': {'hits':300, 'misses':100, 'total':500}, 'id3': {'hits':100, 'misses':400, 'total':600} } </code></pre> <p>and</p> <pre><code>myLists = { 'hits': {'id1':200, 'id2':300, 'id3':100}, 'misses': {'id1':300, 'id2':100, 'id3':400}, 'total': {'id1':400, 'id2':500, 'id3':600} } </code></pre> <p>I then need to sort all of the data in each of the myLists dictionaries.</p> <p>What I doing currently is something like the following:</p> <pre><code>def doSort(key): sorted[key] = sorted(myLists[key].items(), key=operator.itemgetter(1), reverse=True) which would yield, in the case of misses: [('id3', 400), ('id1', 300), ('id2', 200)] </code></pre> <p>This works great when I have up to 100,000 records or so, but with 1,000,000 it is taking at least 5 - 10 minutes to sort each with a total of 16 (my original list of dictionaries actually has 17 fields including id which is popped)</p> <blockquote> <p><strong>* EDIT *</strong> This service is a ThreadingTCPServer which has a method allowing a client to connect and add new data. The new data may include new records (meaning dictionaries with unique 'id's to what is already in memory) or modified records (meaning the same 'id' with different data for the other key value pairs</p> <p>So, once this is running I would pass in </p> <pre><code>[ {'id':'id1', 'hits':205, 'misses':305, 'total':480}, {'id':'id4', 'hits':30, 'misses':40, 'total':60}, {'id':'id5', 'hits':50, 'misses':90, 'total':20 ] </code></pre> <p>I have been using dictionaries to store the data so that I don't end up with duplicates. After the dictionaries are updated with the new/modified data I resort each of them.</p> <p><strong>* END EDIT *</strong></p> </blockquote> <p>So, what is the best way for me to sort these? Is there a better method?</p>
7
2009-07-24T21:25:24Z
1,180,755
<p>I've done some quick profiling of both the original way and SLott's proposal. In neither case does it take 5-10 minutes per field. The actual sorting is not the problem. It looks like most of the time is spent in slinging data around and transforming it. Also, my memory usage is skyrocketing - my python is over 350 megs of ram! are you sure you're not using up all your ram and paging to disk? Even with my crappy 3 year old power saving processor laptop, I am seeing results way less than 5-10 minutes per key sorted for a million items. What I can't explain is the variability in the actual sort() calls. I know python sort is extra good at sorting partially sorted lists, so maybe his list is getting partially sorted in the transform from the raw data to the list to be sorted.</p> <p>Here's the results for slott's method:</p> <pre><code>done creating data done transform. elapsed: 16.5160000324 sorting one key slott's way takes 1.29699993134 </code></pre> <p>here's the code to get those results:</p> <pre><code>starttransform = time.time() hits= [ (r['hits'],r['id']) for r in myList ] endtransform = time.time() print "done transform. elapsed: " + str(endtransform - starttransform) hits.sort() endslottsort = time.time() print "sorting one key slott's way takes " + str(endslottsort - endtransform) </code></pre> <p>Now the results for the original method, or at least a close version with some instrumentation added:</p> <pre><code>done creating data done transform. elapsed: 8.125 about to get stuff to be sorted done getting data. elapsed time: 37.5939998627 about to sort key hits done sorting on key &lt;hits&gt; elapsed time: 5.54699993134 </code></pre> <p>Here's the code:</p> <pre><code>for k, v in myLists.iteritems(): time1 = time.time() print "about to get stuff to be sorted " tobesorted = myLists[k].items() time2 = time.time() print "done getting data. elapsed time: " + str(time2-time1) print "about to sort key " + str(k) mysorted[k] = tobesorted.sort( key=itemgetter(1)) time3 = time.time() print "done sorting on key &lt;" + str(k) + "&gt; elapsed time: " + str(time3-time2) </code></pre>
0
2009-07-25T00:09:35Z
[ "python" ]
Static vs instance methods of str in Python
1,180,303
<p>So, I have learnt that strings have a center method.</p> <pre><code>&gt;&gt;&gt; 'a'.center(3) ' a ' </code></pre> <p>Then I have noticed that I can do the same thing using the 'str' object which is a type, since</p> <pre><code>&gt;&gt;&gt; type(str) &lt;type 'type'&gt; </code></pre> <p>Using this 'type' object I could access the string methods like they were static functions.</p> <pre><code>&gt;&gt;&gt; str.center('a',5) ' a ' </code></pre> <p>Alas! This violates the zen of python.</p> <p><strong>There should be one-- and preferably only one --obvious way to do it.</strong></p> <p>Even the types of these two methods are different.</p> <pre><code>&gt;&gt;&gt; type(str.center) &lt;type 'method_descriptor'&gt; &gt;&gt;&gt; type('Ni!'.center) &lt;type 'builtin_function_or_method'&gt; </code></pre> <p>Now,</p> <ol> <li>Is this an example of how classes in python should be designed?</li> <li>Why are the types different?</li> <li>What is a method_descriptor and why should I bother?</li> </ol> <p><strong>Thanks for the answers!</strong></p>
4
2009-07-24T21:41:32Z
1,180,322
<p>That's simply how classes in Python work:</p> <pre><code>class C: def method(self, arg): print "In C.method, with", arg o = C() o.method(1) C.method(o, 1) # Prints: # In C.method, with 1 # In C.method, with 1 </code></pre> <p>When you say <code>o.method(1)</code> you can think of it as a shorthand for <code>C.method(o, 1)</code>. A <code>method_descriptor</code> is part of the machinery that makes that work.</p>
15
2009-07-24T21:45:16Z
[ "python", "string" ]
Static vs instance methods of str in Python
1,180,303
<p>So, I have learnt that strings have a center method.</p> <pre><code>&gt;&gt;&gt; 'a'.center(3) ' a ' </code></pre> <p>Then I have noticed that I can do the same thing using the 'str' object which is a type, since</p> <pre><code>&gt;&gt;&gt; type(str) &lt;type 'type'&gt; </code></pre> <p>Using this 'type' object I could access the string methods like they were static functions.</p> <pre><code>&gt;&gt;&gt; str.center('a',5) ' a ' </code></pre> <p>Alas! This violates the zen of python.</p> <p><strong>There should be one-- and preferably only one --obvious way to do it.</strong></p> <p>Even the types of these two methods are different.</p> <pre><code>&gt;&gt;&gt; type(str.center) &lt;type 'method_descriptor'&gt; &gt;&gt;&gt; type('Ni!'.center) &lt;type 'builtin_function_or_method'&gt; </code></pre> <p>Now,</p> <ol> <li>Is this an example of how classes in python should be designed?</li> <li>Why are the types different?</li> <li>What is a method_descriptor and why should I bother?</li> </ol> <p><strong>Thanks for the answers!</strong></p>
4
2009-07-24T21:41:32Z
1,180,356
<p>To expand on RichieHindle's answer:</p> <p>In Python, all methods on a class idiomatically take a "self" parameter. For example:</p> <pre><code>def method(self, arg): pass </code></pre> <p>That "self" argument tells Python what instance of the class the method is being called on. When you call a method on a class instance, this is typically passed implicitly for you:</p> <pre><code>o.method(1) </code></pre> <p>However, you also have the option of using the class Object, and explicitly passing in the class instance:</p> <pre><code>C.method(o, 1) </code></pre> <p>To to use your string example, str.center is a method on the str object:</p> <pre><code>"hi".center(5) </code></pre> <p>is equivalent to:</p> <pre><code>str.center("hi", 5) </code></pre> <p>You are passing in the str instance "hi" to the object, explicitly doing what's normally implicit.</p>
4
2009-07-24T21:53:02Z
[ "python", "string" ]
Static vs instance methods of str in Python
1,180,303
<p>So, I have learnt that strings have a center method.</p> <pre><code>&gt;&gt;&gt; 'a'.center(3) ' a ' </code></pre> <p>Then I have noticed that I can do the same thing using the 'str' object which is a type, since</p> <pre><code>&gt;&gt;&gt; type(str) &lt;type 'type'&gt; </code></pre> <p>Using this 'type' object I could access the string methods like they were static functions.</p> <pre><code>&gt;&gt;&gt; str.center('a',5) ' a ' </code></pre> <p>Alas! This violates the zen of python.</p> <p><strong>There should be one-- and preferably only one --obvious way to do it.</strong></p> <p>Even the types of these two methods are different.</p> <pre><code>&gt;&gt;&gt; type(str.center) &lt;type 'method_descriptor'&gt; &gt;&gt;&gt; type('Ni!'.center) &lt;type 'builtin_function_or_method'&gt; </code></pre> <p>Now,</p> <ol> <li>Is this an example of how classes in python should be designed?</li> <li>Why are the types different?</li> <li>What is a method_descriptor and why should I bother?</li> </ol> <p><strong>Thanks for the answers!</strong></p>
4
2009-07-24T21:41:32Z
1,180,424
<blockquote> <p>There should be one-- and preferably only one --obvious way to do it.</p> </blockquote> <p>Philosophically speaking, there <em>is</em> only one obvious way to do it: 'a'.center(3). The fact that there is an unobvious way of calling any method (i.e. the well-explained-by-previous-commentors o.method(x) and Type.method(o, x)) which is useful in many contexts is perfectly in line with the zen of python.</p> <p>Your homework assignment is to read Guido's <a href="http://neopythonic.blogspot.com/2008/10/why-explicit-self-has-to-stay.html">Why the Explicit Self Has to Stay</a>.</p>
8
2009-07-24T22:07:39Z
[ "python", "string" ]
Static vs instance methods of str in Python
1,180,303
<p>So, I have learnt that strings have a center method.</p> <pre><code>&gt;&gt;&gt; 'a'.center(3) ' a ' </code></pre> <p>Then I have noticed that I can do the same thing using the 'str' object which is a type, since</p> <pre><code>&gt;&gt;&gt; type(str) &lt;type 'type'&gt; </code></pre> <p>Using this 'type' object I could access the string methods like they were static functions.</p> <pre><code>&gt;&gt;&gt; str.center('a',5) ' a ' </code></pre> <p>Alas! This violates the zen of python.</p> <p><strong>There should be one-- and preferably only one --obvious way to do it.</strong></p> <p>Even the types of these two methods are different.</p> <pre><code>&gt;&gt;&gt; type(str.center) &lt;type 'method_descriptor'&gt; &gt;&gt;&gt; type('Ni!'.center) &lt;type 'builtin_function_or_method'&gt; </code></pre> <p>Now,</p> <ol> <li>Is this an example of how classes in python should be designed?</li> <li>Why are the types different?</li> <li>What is a method_descriptor and why should I bother?</li> </ol> <p><strong>Thanks for the answers!</strong></p>
4
2009-07-24T21:41:32Z
1,181,460
<p>Method descriptor is a normal class with <code>__get__</code>, <code>__set__</code> and <code>__del__</code> methods.</p> <p>When, e.g., <code>__get__</code> is called, it is passed 2 or 3 arguments:</p> <ul> <li><code>self</code>, which is the descriptor class itself,</li> <li><code>inst</code>, which is the caller objet to which the "described" method should be bound,</li> <li><code>cls</code>, which can be <code>None</code>.</li> </ul> <p>To illustrate method_descriptor machinery, let me give this example:</p> <pre><code>class Descriptor(object): def __init__(self, m): self._meth=m def __get__(self, inst, cls=None): if cls is None: cls=type(inst) delattr(cls,self._meth.func_name) def _inst_meth(*a): return self._meth(inst,*a) return _inst_meth def instanceonlymethod(f): return Descriptor(f) class Test(object): def meth_1(self,*a): return '-'.join(str(i) for i in a) @instanceonlymethod def meth_2(self,*a): return '-'.join(str(i) for i in a) t=Test() print t.meth_1(2,3,4,5) #returns: 2-3-4-5 print Test.meth_1(t,1,2,3,4) #returns: 1-2-3-4 print t.meth_2(2,3,4,5) #returns: 2-3-4-5 try: print Test.meth_2(t,1,2,3,4) except Exception, why: #for 2.6, see changes print why #returns: type object 'Test' has no attribute 'meth_2' </code></pre> <p>Now, when you call <code>Test.meth_2(t, 1,2,3,4)</code>, it won't work.</p>
1
2009-07-25T07:14:39Z
[ "python", "string" ]
Static vs instance methods of str in Python
1,180,303
<p>So, I have learnt that strings have a center method.</p> <pre><code>&gt;&gt;&gt; 'a'.center(3) ' a ' </code></pre> <p>Then I have noticed that I can do the same thing using the 'str' object which is a type, since</p> <pre><code>&gt;&gt;&gt; type(str) &lt;type 'type'&gt; </code></pre> <p>Using this 'type' object I could access the string methods like they were static functions.</p> <pre><code>&gt;&gt;&gt; str.center('a',5) ' a ' </code></pre> <p>Alas! This violates the zen of python.</p> <p><strong>There should be one-- and preferably only one --obvious way to do it.</strong></p> <p>Even the types of these two methods are different.</p> <pre><code>&gt;&gt;&gt; type(str.center) &lt;type 'method_descriptor'&gt; &gt;&gt;&gt; type('Ni!'.center) &lt;type 'builtin_function_or_method'&gt; </code></pre> <p>Now,</p> <ol> <li>Is this an example of how classes in python should be designed?</li> <li>Why are the types different?</li> <li>What is a method_descriptor and why should I bother?</li> </ol> <p><strong>Thanks for the answers!</strong></p>
4
2009-07-24T21:41:32Z
1,182,880
<pre><code>'a'.center(3) == str.center('a',3) </code></pre> <p>There <em>is</em> only one way to do it.</p>
2
2009-07-25T19:44:33Z
[ "python", "string" ]
Activate a virtualenv via fabric as deploy user
1,180,411
<p>I want to run my fabric script locally, which will in turn, log into my server, switch user to deploy, activate the projects .virtualenv, which will change dir to the project and issue a git pull.</p> <pre><code>def git_pull(): sudo('su deploy') # here i need to switch to the virtualenv run('git pull') </code></pre> <p>I typically use the workon command from virtualenvwrapper which sources the activate file and the postactivate file will put me in the project folder. In this case, it seems that because fabric runs from within shell, control is give over to fabric, so I can't use bash's source built-in to '$source ~/.virtualenv/myvenv/bin/activate'</p> <p>Anybody have an example and explanation of how they have done this?</p>
115
2009-07-24T22:03:57Z
1,180,665
<p>Right now, you can do what I do, which is kludgy but works perfectly well* (this usage assumes you're using virtualenvwrapper -- which you should be -- but you can easily substitute in the rather longer 'source' call you mentioned, if not):</p> <pre><code>def task(): workon = 'workon myvenv &amp;&amp; ' run(workon + 'git pull') run(workon + 'do other stuff, etc') </code></pre> <p>Since version 1.0, Fabric has a <a href="http://docs.fabfile.org/en/1.11/api/core/context_managers.html?highlight=prefix#fabric.context_managers.prefix" rel="nofollow"><code>prefix</code> context manager</a> which uses this technique so you can for example:</p> <pre><code>def task(): with prefix('workon myvenv'): run('git pull') run('do other stuff, etc') </code></pre> <hr> <p>* There are bound to be cases where using the <code>command1 &amp;&amp; command2</code> approach may blow up on you, such as when <code>command1</code> fails (<code>command2</code> will never run) or if <code>command1</code> isn't properly escaped and contains special shell characters, and so forth.</p>
91
2009-07-24T23:32:09Z
[ "python", "virtualenv", "fabric", "automated-deploy" ]
Activate a virtualenv via fabric as deploy user
1,180,411
<p>I want to run my fabric script locally, which will in turn, log into my server, switch user to deploy, activate the projects .virtualenv, which will change dir to the project and issue a git pull.</p> <pre><code>def git_pull(): sudo('su deploy') # here i need to switch to the virtualenv run('git pull') </code></pre> <p>I typically use the workon command from virtualenvwrapper which sources the activate file and the postactivate file will put me in the project folder. In this case, it seems that because fabric runs from within shell, control is give over to fabric, so I can't use bash's source built-in to '$source ~/.virtualenv/myvenv/bin/activate'</p> <p>Anybody have an example and explanation of how they have done this?</p>
115
2009-07-24T22:03:57Z
3,403,558
<p>I'm just using a simple wrapper function virtualenv() that can be called instead of run(). It doesn't use the cd context manager, so relative paths can be used.</p> <pre><code>def virtualenv(command): """ Run a command in the virtualenv. This prefixes the command with the source command. Usage: virtualenv('pip install django') """ source = 'source %(project_directory)s/bin/activate &amp;&amp; ' % env run(source + command) </code></pre>
17
2010-08-04T07:48:49Z
[ "python", "virtualenv", "fabric", "automated-deploy" ]
Activate a virtualenv via fabric as deploy user
1,180,411
<p>I want to run my fabric script locally, which will in turn, log into my server, switch user to deploy, activate the projects .virtualenv, which will change dir to the project and issue a git pull.</p> <pre><code>def git_pull(): sudo('su deploy') # here i need to switch to the virtualenv run('git pull') </code></pre> <p>I typically use the workon command from virtualenvwrapper which sources the activate file and the postactivate file will put me in the project folder. In this case, it seems that because fabric runs from within shell, control is give over to fabric, so I can't use bash's source built-in to '$source ~/.virtualenv/myvenv/bin/activate'</p> <p>Anybody have an example and explanation of how they have done this?</p>
115
2009-07-24T22:03:57Z
5,359,988
<p>As an update to bitprophet's forecast: With Fabric 1.0 you can make use of prefix() and your own context managers.</p> <pre><code>from __future__ import with_statement from fabric.api import * from contextlib import contextmanager as _contextmanager env.hosts = ['servername'] env.user = 'deploy' env.keyfile = ['$HOME/.ssh/deploy_rsa'] env.directory = '/path/to/virtualenvs/project' env.activate = 'source /path/to/virtualenvs/project/bin/activate' @_contextmanager def virtualenv(): with cd(env.directory): with prefix(env.activate): yield def deploy(): with virtualenv(): run('pip freeze') </code></pre>
122
2011-03-19T04:06:46Z
[ "python", "virtualenv", "fabric", "automated-deploy" ]
Activate a virtualenv via fabric as deploy user
1,180,411
<p>I want to run my fabric script locally, which will in turn, log into my server, switch user to deploy, activate the projects .virtualenv, which will change dir to the project and issue a git pull.</p> <pre><code>def git_pull(): sudo('su deploy') # here i need to switch to the virtualenv run('git pull') </code></pre> <p>I typically use the workon command from virtualenvwrapper which sources the activate file and the postactivate file will put me in the project folder. In this case, it seems that because fabric runs from within shell, control is give over to fabric, so I can't use bash's source built-in to '$source ~/.virtualenv/myvenv/bin/activate'</p> <p>Anybody have an example and explanation of how they have done this?</p>
115
2009-07-24T22:03:57Z
18,397,479
<p><code>virtualenvwrapper</code> can make this a little simpler</p> <ol> <li><p>Using @nh2's approach (this approach also works when using <code>local</code>, but only for virtualenvwrapper installations where <code>workon</code> is in <code>$PATH</code>, in other words -- Windows)</p> <pre><code>from contextlib import contextmanager from fabric.api import prefix @contextmanager def virtualenv(): with prefix("workon env1"): yield def deploy(): with virtualenv(): run("pip freeze &gt; requirements.txt") </code></pre></li> <li><p>Or deploy your fab file and run this locally. This setup lets you activate the virtualenv for local or remote commands. This approach is powerful because it works around <code>local</code>'s inability to run .bashrc using <code>bash -l</code>:</p> <pre><code>@contextmanager def local_prefix(shell, prefix): def local_call(command): return local("%(sh)s \"%(pre)s &amp;&amp; %(cmd)s\"" % {"sh": shell, "pre": prefix, "cmd": command}) yield local_prefix def write_requirements(shell="/bin/bash -lic", env="env1"): with local_prefix(shell, "workon %s" % env) as local: local("pip freeze &gt; requirements.txt") write_requirements() # locally run("fab write_requirements") </code></pre></li> </ol>
7
2013-08-23T07:45:03Z
[ "python", "virtualenv", "fabric", "automated-deploy" ]
Activate a virtualenv via fabric as deploy user
1,180,411
<p>I want to run my fabric script locally, which will in turn, log into my server, switch user to deploy, activate the projects .virtualenv, which will change dir to the project and issue a git pull.</p> <pre><code>def git_pull(): sudo('su deploy') # here i need to switch to the virtualenv run('git pull') </code></pre> <p>I typically use the workon command from virtualenvwrapper which sources the activate file and the postactivate file will put me in the project folder. In this case, it seems that because fabric runs from within shell, control is give over to fabric, so I can't use bash's source built-in to '$source ~/.virtualenv/myvenv/bin/activate'</p> <p>Anybody have an example and explanation of how they have done this?</p>
115
2009-07-24T22:03:57Z
18,718,250
<p>This is my approach on using <code>virtualenv</code> with local deployments.</p> <p>Using fabric's <a href="http://docs.fabfile.org/en/1.7/api/core/context_managers.html?highlight=path#fabric.context_managers.path">path()</a> context manager you can run <code>pip</code> or <code>python</code> with binaries from virtualenv.</p> <pre><code>from fabric.api import lcd, local, path project_dir = '/www/my_project/sms/' env_bin_dir = project_dir + '../env/bin/' def deploy(): with lcd(project_dir): local('git pull origin') local('git checkout -f') with path(env_bin_dir, behavior='prepend'): local('pip freeze') local('pip install -r requirements/staging.txt') local('./manage.py migrate') # Django related # Note: previous line is the same as: local('python manage.py migrate') # Using next line, you can make sure that python # from virtualenv directory is used: local('which python') </code></pre>
6
2013-09-10T11:51:45Z
[ "python", "virtualenv", "fabric", "automated-deploy" ]
Activate a virtualenv via fabric as deploy user
1,180,411
<p>I want to run my fabric script locally, which will in turn, log into my server, switch user to deploy, activate the projects .virtualenv, which will change dir to the project and issue a git pull.</p> <pre><code>def git_pull(): sudo('su deploy') # here i need to switch to the virtualenv run('git pull') </code></pre> <p>I typically use the workon command from virtualenvwrapper which sources the activate file and the postactivate file will put me in the project folder. In this case, it seems that because fabric runs from within shell, control is give over to fabric, so I can't use bash's source built-in to '$source ~/.virtualenv/myvenv/bin/activate'</p> <p>Anybody have an example and explanation of how they have done this?</p>
115
2009-07-24T22:03:57Z
24,461,747
<p>Here is code for a decorator that will result in the use of Virtual Environment for any run/sudo calls:</p> <pre><code># This is the bash code to update the $PATH as activate does UPDATE_PYTHON_PATH = r'PATH="{}:$PATH"'.format(VIRTUAL_ENV_BIN_DIR) def with_venv(func, *args, **kwargs): "Use Virtual Environment for the command" def wrapped(*args, **kwargs): with prefix(UPDATE_PYTHON_PATH): return func(*args, **kwargs) wrapped.__name__ = func.__name__ wrapped.__doc__ = func.__doc__ return wrapped </code></pre> <p>and then to use the decorator, note the order of the decorators is important:</p> <pre><code>@task @with_venv def which_python(): "Gets which python is being used" run("which python") </code></pre>
0
2014-06-27T22:38:03Z
[ "python", "virtualenv", "fabric", "automated-deploy" ]
Activate a virtualenv via fabric as deploy user
1,180,411
<p>I want to run my fabric script locally, which will in turn, log into my server, switch user to deploy, activate the projects .virtualenv, which will change dir to the project and issue a git pull.</p> <pre><code>def git_pull(): sudo('su deploy') # here i need to switch to the virtualenv run('git pull') </code></pre> <p>I typically use the workon command from virtualenvwrapper which sources the activate file and the postactivate file will put me in the project folder. In this case, it seems that because fabric runs from within shell, control is give over to fabric, so I can't use bash's source built-in to '$source ~/.virtualenv/myvenv/bin/activate'</p> <p>Anybody have an example and explanation of how they have done this?</p>
115
2009-07-24T22:03:57Z
25,707,904
<p>Thanks to all answers posted and I would like to add one more alternative for this. There is an module, <a href="https://pypi.python.org/pypi/fabric-virtualenv/" rel="nofollow">fabric-virtualenv</a>, which can provide the function as the same code:</p> <pre><code>&gt;&gt;&gt; from fabvenv import virtualenv &gt;&gt;&gt; with virtualenv('/home/me/venv/'): ... run('python foo') </code></pre> <p>fabric-virtualenv makes use of <code>fabric.context_managers.prefix</code>, which might be a good way :)</p>
3
2014-09-07T07:02:36Z
[ "python", "virtualenv", "fabric", "automated-deploy" ]
How to set LANG variable in Windows?
1,180,590
<p>I'm making an application that supports multi language. And I am using <code>gettext</code> and <code>locale</code> to solve this issue. </p> <p>How to set LANG variable in Windows? In Linux and Unix-like systems it's just as simple as</p> <p><code>$ LANG=en_US python appname.py</code></p> <p>And it will automatically set the locale to that particular language. But in Windows, the</p> <p><code>C:\&gt;SET LANG=en_US python appname.py</code> </p> <p>or </p> <p><code>C:\&gt;SET LANG=en_US</code> </p> <p><code>C:\&gt;python appname.py</code></p> <p>doesn't work.</p>
0
2009-07-24T23:01:14Z
1,180,593
<p>Windows locale support doesn't rely on LANG variable (or, indeed, any other environmental variable). It is whatever the user set it to in Control Panel.</p>
3
2009-07-24T23:02:38Z
[ "python", "windows", "locale" ]
How to set LANG variable in Windows?
1,180,590
<p>I'm making an application that supports multi language. And I am using <code>gettext</code> and <code>locale</code> to solve this issue. </p> <p>How to set LANG variable in Windows? In Linux and Unix-like systems it's just as simple as</p> <p><code>$ LANG=en_US python appname.py</code></p> <p>And it will automatically set the locale to that particular language. But in Windows, the</p> <p><code>C:\&gt;SET LANG=en_US python appname.py</code> </p> <p>or </p> <p><code>C:\&gt;SET LANG=en_US</code> </p> <p><code>C:\&gt;python appname.py</code></p> <p>doesn't work.</p>
0
2009-07-24T23:01:14Z
6,734,439
<p>you can use a batch file like in here: <a href="http://www.geany.org/Documentation/FAQ#QQuestions11" rel="nofollow">http://www.geany.org/Documentation/FAQ#QQuestions11</a> </p> <pre><code>set LANG=en_US something.exe </code></pre> <p>or set it through the control panel / system / advanced system settings / advanced / environmental variables</p>
2
2011-07-18T14:25:52Z
[ "python", "windows", "locale" ]
Python Popen difficulties: File not found
1,180,592
<p>I'm trying to use python to run a program.</p> <pre><code>from subprocess import Popen sa_proc = Popen(['C:\\sa\\sa.exe','--?']) </code></pre> <p>Running this small snippit gives the error:</p> <blockquote> <p>WindowsError: [Error 2] The system cannot find the file specified</p> </blockquote> <p>The program exists and I have copy and pasted directly from explorer the absolute path to the exe. I have tried other things and have found that if I put the EXE in the source folder with the python script and use './sa.exe' then it works. The only thing I can think of is that I'm running the python script (and python) from a separate partition (F:).</p> <p>Any ideas? Thanks</p>
1
2009-07-24T23:02:08Z
1,180,654
<p>You may not have permission to execute C:\sa\sa.exe. Have you tried running the program manually?</p>
0
2009-07-24T23:28:47Z
[ "python", "subprocess", "popen" ]
Python Popen difficulties: File not found
1,180,592
<p>I'm trying to use python to run a program.</p> <pre><code>from subprocess import Popen sa_proc = Popen(['C:\\sa\\sa.exe','--?']) </code></pre> <p>Running this small snippit gives the error:</p> <blockquote> <p>WindowsError: [Error 2] The system cannot find the file specified</p> </blockquote> <p>The program exists and I have copy and pasted directly from explorer the absolute path to the exe. I have tried other things and have found that if I put the EXE in the source folder with the python script and use './sa.exe' then it works. The only thing I can think of is that I'm running the python script (and python) from a separate partition (F:).</p> <p>Any ideas? Thanks</p>
1
2009-07-24T23:02:08Z
1,181,026
<p>As <a href="http://docs.python.org/library/subprocess.html?highlight=subprocess#subprocess.Popen">the docs</a> say, "On Windows: the Popen class uses CreateProcess() to execute the child program, which operates on strings. If args is a sequence, it will be converted to a string using the list2cmdline() method.". Maybe that method is messing things up, so why not try the simpler approach of:</p> <pre><code>sa_proc = Popen('C:\\sa\\sa.exe --?') </code></pre> <p>If this still fails, then: what's <code>os.environ['COMSPEC']</code> just before you try this? What happens if you add <code>, shell=True</code> to <code>Popen</code>'s arguments?</p> <p><strong>Edit</strong>: turns out apparently to be a case of simple mis-spellling, as 'sa' was actually the program spelled SpamAssassin -- double s twice -- and what the OP was writing was spamassasin -- one double s but a single one the second time.</p>
5
2009-07-25T02:36:58Z
[ "python", "subprocess", "popen" ]
Using subprocess.Popen for Process with Large Output
1,180,606
<p>I have some Python code that executes an external app which works fine when the app has a small amount of output, but hangs when there is a lot. My code looks like:</p> <pre><code>p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) errcode = p.wait() retval = p.stdout.read() errmess = p.stderr.read() if errcode: log.error('cmd failed &lt;%s&gt;: %s' % (errcode,errmess)) </code></pre> <p>There are comments in the docs that seem to indicate the potential issue. Under wait, there is:</p> <blockquote> <p>Warning: This will deadlock if the child process generates enough output to a <code>stdout</code> or <code>stderr</code> pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use <code>communicate()</code> to avoid that.</p> </blockquote> <p>though under communicate, I see:</p> <p>Note The data read is buffered in memory, so do not use this method if the data size is large or unlimited.</p> <p>So it is unclear to me that I should use either of these if I have a large amount of data. They don't indicate what method I should use in that case.</p> <p>I do need the return value from the exec and do parse and use both the <code>stdout</code> and <code>stderr</code>.</p> <p>So what is an equivalent method in Python to exec an external app that is going to have large output?</p>
20
2009-07-24T23:08:07Z
1,180,632
<p><em>A lot of output</em> is subjective so it's a little difficult to make a recommendation. If the amount of output is <em>really</em> large then you likely don't want to grab it all with a single read() call anyway. You may want to try writing the output to a file and then pull the data in incrementally like such:</p> <pre><code>f=file('data.out','w') p = subprocess.Popen(cmd, shell=True, stdout=f, stderr=subprocess.PIPE) errcode = p.wait() f.close() if errcode: errmess = p.stderr.read() log.error('cmd failed &lt;%s&gt;: %s' % (errcode,errmess)) for line in file('data.out'): #do something </code></pre>
6
2009-07-24T23:18:34Z
[ "python", "subprocess" ]
Using subprocess.Popen for Process with Large Output
1,180,606
<p>I have some Python code that executes an external app which works fine when the app has a small amount of output, but hangs when there is a lot. My code looks like:</p> <pre><code>p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) errcode = p.wait() retval = p.stdout.read() errmess = p.stderr.read() if errcode: log.error('cmd failed &lt;%s&gt;: %s' % (errcode,errmess)) </code></pre> <p>There are comments in the docs that seem to indicate the potential issue. Under wait, there is:</p> <blockquote> <p>Warning: This will deadlock if the child process generates enough output to a <code>stdout</code> or <code>stderr</code> pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use <code>communicate()</code> to avoid that.</p> </blockquote> <p>though under communicate, I see:</p> <p>Note The data read is buffered in memory, so do not use this method if the data size is large or unlimited.</p> <p>So it is unclear to me that I should use either of these if I have a large amount of data. They don't indicate what method I should use in that case.</p> <p>I do need the return value from the exec and do parse and use both the <code>stdout</code> and <code>stderr</code>.</p> <p>So what is an equivalent method in Python to exec an external app that is going to have large output?</p>
20
2009-07-24T23:08:07Z
1,180,641
<p>You're doing blocking reads to two files; the first needs to complete before the second starts. If the application writes a lot to stderr, and nothing to stdout, then your process will sit waiting for data on stdout that isn't coming, while the program you're running sits there waiting for the stuff it wrote to stderr to be read (which it never will be--since you're waiting for stdout).</p> <p>There are a few ways you can fix this.</p> <p>The simplest is to not intercept stderr; leave stderr=None. Errors will be output to stderr directly. You can't intercept them and display them as part of your own message. For commandline tools, this is often OK. For other apps, it can be a problem.</p> <p>Another simple approach is to redirect stderr to stdout, so you only have one incoming file: set stderr=STDOUT. This means you can't distinguish regular output from error output. This may or may not be acceptable, depending on how the application writes output.</p> <p>The complete and complicated way of handling this is select (<a href="http://docs.python.org/library/select.html">http://docs.python.org/library/select.html</a>). This lets you read in a non-blocking way: you get data whenever data appears on either stdout or stderr. I'd only recommend this if it's really necessary. This probably doesn't work in Windows.</p>
13
2009-07-24T23:23:35Z
[ "python", "subprocess" ]
Using subprocess.Popen for Process with Large Output
1,180,606
<p>I have some Python code that executes an external app which works fine when the app has a small amount of output, but hangs when there is a lot. My code looks like:</p> <pre><code>p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) errcode = p.wait() retval = p.stdout.read() errmess = p.stderr.read() if errcode: log.error('cmd failed &lt;%s&gt;: %s' % (errcode,errmess)) </code></pre> <p>There are comments in the docs that seem to indicate the potential issue. Under wait, there is:</p> <blockquote> <p>Warning: This will deadlock if the child process generates enough output to a <code>stdout</code> or <code>stderr</code> pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use <code>communicate()</code> to avoid that.</p> </blockquote> <p>though under communicate, I see:</p> <p>Note The data read is buffered in memory, so do not use this method if the data size is large or unlimited.</p> <p>So it is unclear to me that I should use either of these if I have a large amount of data. They don't indicate what method I should use in that case.</p> <p>I do need the return value from the exec and do parse and use both the <code>stdout</code> and <code>stderr</code>.</p> <p>So what is an equivalent method in Python to exec an external app that is going to have large output?</p>
20
2009-07-24T23:08:07Z
1,180,642
<p>You could try communicate and see if that solves your problem. If not, I'd redirect the output to a temporary file.</p>
2
2009-07-24T23:24:10Z
[ "python", "subprocess" ]
Using subprocess.Popen for Process with Large Output
1,180,606
<p>I have some Python code that executes an external app which works fine when the app has a small amount of output, but hangs when there is a lot. My code looks like:</p> <pre><code>p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) errcode = p.wait() retval = p.stdout.read() errmess = p.stderr.read() if errcode: log.error('cmd failed &lt;%s&gt;: %s' % (errcode,errmess)) </code></pre> <p>There are comments in the docs that seem to indicate the potential issue. Under wait, there is:</p> <blockquote> <p>Warning: This will deadlock if the child process generates enough output to a <code>stdout</code> or <code>stderr</code> pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use <code>communicate()</code> to avoid that.</p> </blockquote> <p>though under communicate, I see:</p> <p>Note The data read is buffered in memory, so do not use this method if the data size is large or unlimited.</p> <p>So it is unclear to me that I should use either of these if I have a large amount of data. They don't indicate what method I should use in that case.</p> <p>I do need the return value from the exec and do parse and use both the <code>stdout</code> and <code>stderr</code>.</p> <p>So what is an equivalent method in Python to exec an external app that is going to have large output?</p>
20
2009-07-24T23:08:07Z
1,182,810
<p>Glenn Maynard is right in his comment about deadlocks. However, the best way of solving this problem is two create two threads, one for stdout and one for stderr, which read those respective streams until exhausted and do whatever you need with the output.</p> <p>The suggestion of using temporary files may or may not work for you depending on the size of output etc. and whether you need to process the subprocess' output as it is generated.</p> <p>As Heikki Toivonen has suggested, you should look at the <code>communicate</code> method. However, this buffers the stdout/stderr of the subprocess in memory and you get those returned from the <code>communicate</code> call - this is not ideal for some scenarios. But the source of the communicate method is worth looking at.</p> <p>Another example is in a package I maintain, <a href="http://code.google.com/p/python-gnupg/">python-gnupg</a>, where the <code>gpg</code> executable is spawned via <code>subprocess</code> to do the heavy lifting, and the Python wrapper spawns threads to read gpg's stdout and stderr and consume them as data is produced by gpg. You may be able to get some ideas by looking at the source there, as well. Data produced by gpg to both stdout and stderr can be quite large, in the general case.</p>
6
2009-07-25T19:14:53Z
[ "python", "subprocess" ]
Using subprocess.Popen for Process with Large Output
1,180,606
<p>I have some Python code that executes an external app which works fine when the app has a small amount of output, but hangs when there is a lot. My code looks like:</p> <pre><code>p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) errcode = p.wait() retval = p.stdout.read() errmess = p.stderr.read() if errcode: log.error('cmd failed &lt;%s&gt;: %s' % (errcode,errmess)) </code></pre> <p>There are comments in the docs that seem to indicate the potential issue. Under wait, there is:</p> <blockquote> <p>Warning: This will deadlock if the child process generates enough output to a <code>stdout</code> or <code>stderr</code> pipe such that it blocks waiting for the OS pipe buffer to accept more data. Use <code>communicate()</code> to avoid that.</p> </blockquote> <p>though under communicate, I see:</p> <p>Note The data read is buffered in memory, so do not use this method if the data size is large or unlimited.</p> <p>So it is unclear to me that I should use either of these if I have a large amount of data. They don't indicate what method I should use in that case.</p> <p>I do need the return value from the exec and do parse and use both the <code>stdout</code> and <code>stderr</code>.</p> <p>So what is an equivalent method in Python to exec an external app that is going to have large output?</p>
20
2009-07-24T23:08:07Z
24,943,368
<p>I had the same problem. If you have to handle a large output, another good option could be to use a file for stdout and stderr, and pass those files per parameter.</p> <p>Check the tempfile module in python: <a href="https://docs.python.org/2/library/tempfile.html" rel="nofollow">https://docs.python.org/2/library/tempfile.html</a>.</p> <p>Something like this might work</p> <pre><code>out = tempfile.NamedTemporaryFile(delete=False) </code></pre> <p>Then you would do:</p> <pre><code>Popen(... stdout=out,...) </code></pre> <p>Then you can read the file, and erase it later.</p>
0
2014-07-24T20:28:30Z
[ "python", "subprocess" ]
Python error: int argument required
1,180,673
<p>What am I doing wrong here?</p> <pre><code> i = 0 cursor.execute("insert into core_room (order) values (%i)", (int(i)) </code></pre> <p>Error:</p> <pre><code> int argument required </code></pre> <p>The database field is an int(11), but I think the %i is generating the error.</p> <p><strong>Update:</strong></p> <p>Here's a more thorough example:</p> <pre><code>time = datetime.datetime.now() floor = 0 i = 0 </code></pre> <p>try: booster_cursor.execute('insert into core_room (extern_id, name, order, unit_id, created, updated) values (%s, %s, %s, %s, %s, %s)', (row[0], row[0], i, floor, time, time,)) except Exception, e: print e</p> <p>Error:</p> <pre><code> (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order, unit_id, created, updated) values ('99', '99', '235', '12', '2009-07-24 1' at line 1") </code></pre>
0
2009-07-24T23:35:04Z
1,180,681
<p>Two things. First, use <code>%s</code> and not <code>%i</code>. Second, parameters must be in a tuple - so you need <code>(i,)</code> (with comma after <code>i</code>).</p> <p>Also, <code>ORDER</code> is a keyword, and should be escaped if you're using it as field name.</p>
4
2009-07-24T23:39:41Z
[ "python", "mysql", "mysql-error-1064" ]
Python error: int argument required
1,180,673
<p>What am I doing wrong here?</p> <pre><code> i = 0 cursor.execute("insert into core_room (order) values (%i)", (int(i)) </code></pre> <p>Error:</p> <pre><code> int argument required </code></pre> <p>The database field is an int(11), but I think the %i is generating the error.</p> <p><strong>Update:</strong></p> <p>Here's a more thorough example:</p> <pre><code>time = datetime.datetime.now() floor = 0 i = 0 </code></pre> <p>try: booster_cursor.execute('insert into core_room (extern_id, name, order, unit_id, created, updated) values (%s, %s, %s, %s, %s, %s)', (row[0], row[0], i, floor, time, time,)) except Exception, e: print e</p> <p>Error:</p> <pre><code> (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order, unit_id, created, updated) values ('99', '99', '235', '12', '2009-07-24 1' at line 1") </code></pre>
0
2009-07-24T23:35:04Z
1,180,687
<p>I believe the second argument to execute() is expected to be an iterable. IF this is the case you need to change:</p> <pre><code>(int(i)) </code></pre> <p>to:</p> <pre><code>(int(i),) </code></pre> <p>to make it into a tuple.</p>
1
2009-07-24T23:40:22Z
[ "python", "mysql", "mysql-error-1064" ]
Python error: int argument required
1,180,673
<p>What am I doing wrong here?</p> <pre><code> i = 0 cursor.execute("insert into core_room (order) values (%i)", (int(i)) </code></pre> <p>Error:</p> <pre><code> int argument required </code></pre> <p>The database field is an int(11), but I think the %i is generating the error.</p> <p><strong>Update:</strong></p> <p>Here's a more thorough example:</p> <pre><code>time = datetime.datetime.now() floor = 0 i = 0 </code></pre> <p>try: booster_cursor.execute('insert into core_room (extern_id, name, order, unit_id, created, updated) values (%s, %s, %s, %s, %s, %s)', (row[0], row[0], i, floor, time, time,)) except Exception, e: print e</p> <p>Error:</p> <pre><code> (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order, unit_id, created, updated) values ('99', '99', '235', '12', '2009-07-24 1' at line 1") </code></pre>
0
2009-07-24T23:35:04Z
1,180,690
<p>You should be using <code>?</code> instead of <code>%i</code> probably. And you're missing a parenthesis.</p> <pre><code>cursor.execute("insert into core_room (order) values (?)", (int(i),)) </code></pre>
1
2009-07-24T23:41:12Z
[ "python", "mysql", "mysql-error-1064" ]
one liner for conditionally replacing dictionary values
1,180,846
<p>Is there a better way to express this using list comprehension? Or any other way of expressing this in one line?</p> <p>I want to replace each value in the original dictionary with a corresponding value in the col dictionary, or leave it unchanged if its not in the col dictionary.</p> <pre><code>col = {'1':3.5, '6':4.7} original = {'1':3, '2':1, '3':5, '4':2, '5':3, '6':4} for entry in col.iteritems(): original[entry[0]] = entry[1] </code></pre>
0
2009-07-25T01:00:20Z
1,180,886
<p>I believe <a href="http://docs.python.org/library/stdtypes.html#dict.update" rel="nofollow"><code>update</code></a> is what you want.</p> <blockquote> <p>update([other])</p> <p>Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None.</p> </blockquote> <p><strong>Code:</strong></p> <pre><code>original.update(col[user]) </code></pre> <p><strong>A simple test:</strong></p> <pre><code>user = "user" matrix = { "user" : { "a" : "b", "c" : "d", "e" : "f", }, } col = { "user" : { "a" : "b_2", "c" : "d_2", }, } original.update(col[user]) print(original) </code></pre> <p><strong>Output</strong></p> <pre><code>{'a': 'b_2', 'c': 'd_2', 'e': 'f'} </code></pre>
2
2009-07-25T01:17:34Z
[ "python", "refactoring", "dictionary", "list-comprehension" ]
Composite pattern for GTD app
1,180,876
<p>This is a continuation of <a href="http://stackoverflow.com/questions/1175110/python-classes-for-simple-gtd-app" rel="nofollow" title="one of my previous questions">one of my previous questions</a></p> <p>Here are my classes.</p> <pre><code>#Project class class Project: def __init__(self, name, children=[]): self.name = name self.children = children #add object def add(self, object): self.children.append(object) #get list of all actions def actions(self): a = [] for c in self.children: if isinstance(c, Action): a.append(c.name) return a #get specific action def action(self, name): for c in self.children: if isinstance(c, Action): if name == c.name: return c #get list of all projects def projects(self): p = [] for c in self.children: if isinstance(c, Project): p.append(c.name) return p #get specific project def project(self, name): for c in self.children: if isinstance(c, Project): if name == c.name: return c #Action class class Action: def __init__(self, name): self.name = name self.done = False def mark_done(self): self.done = True </code></pre> <p>Here's the trouble I'm having. If I build a big project with several small projects, I want to see what the projects are or the actions for the current project, however I'm getting all of them in the tree. Here's the test code I'm using (note that I purposely chose several different ways to add projects and actions to test to make sure different ways work).</p> <pre><code>life = Project("life") playguitar = Action("Play guitar") life.add(Project("Get Married")) wife = Project("Find wife") wife.add(Action("Date")) wife.add(Action("Propose")) wife.add(Action("Plan wedding")) life.project("Get Married").add(wife) life.add(Project("Have kids")) life.project("Have kids").add(Action("Bang wife")) life.project("Have kids").add(Action("Get wife pregnant")) life.project("Have kids").add(Project("Suffer through pregnancy")) life.project("Have kids").project("Suffer through pregnancy").add(Action("Drink")) life.project("Have kids").project("Suffer through pregnancy").add(playguitar) life.add(Project("Retire")) life.project("Retire").add(playguitar) </code></pre> <p>life should have a few projects in it, with a few projects inside of those. The structure amounts to something like this (where indents are projects and -'s are actions)</p> <pre><code>Life Get Married Find wife - Date - Propose - Plan wedding Have kids - Bang wife - Get wife pregnant Suffer through pregnancy - Drink - Play guitar Retire - Play guitar </code></pre> <p>What I'm finding is that life.actions() is returning every action in the tree when it should return none. life.projects() is returning every project, even sub projects, when I only want 'Get Married', 'Have kids', and 'Retire'. What is it that I'm doing wrong?</p>
3
2009-07-25T01:10:46Z
1,180,901
<p>The problem is with your initialization of Projects:</p> <pre><code> __init__(self, name, children=[]): </code></pre> <p>You only get one list, which is shared by all Projects you create without passing a value for children. See <a href="http://effbot.org/zone/default-values.htm">here</a> for an explanation. You want to instead make the default None, and initialize an empty list whenever the value is None. </p> <pre><code> __init__(self, name, children=None): if children is None: children = [] </code></pre>
5
2009-07-25T01:29:29Z
[ "python", "design", "recursion", "composite", "gtd" ]
Spoofing the origination IP address of an HTTP request
1,180,878
<p>This only needs to work on a single subnet and is not for malicious use. </p> <p>I have a load testing tool written in Python that basically blasts HTTP requests at a URL. I need to run performance tests against an IP-based load balancer, so the requests must come from a range of IP's. Most commercial performance tools provide this functionality, but I want to build it into my own.</p> <p>The tool uses Python's urllib2 for transport. Is it possible to send HTTP requests with spoofed IP addresses for the packets making up the request?</p>
19
2009-07-25T01:11:24Z
1,180,884
<p>You want to set the source address used for the connection. Googling "urllib2 source address" gives <a href="http://bugs.python.org/file9988/urllib2_util.py">http://bugs.python.org/file9988/urllib2_util.py</a>. I havn't tried it.</p> <p>The system you're running on needs to be configured with the IPs you're testing from.</p>
5
2009-07-25T01:15:44Z
[ "python", "http", "networking", "sockets", "urllib2" ]
Spoofing the origination IP address of an HTTP request
1,180,878
<p>This only needs to work on a single subnet and is not for malicious use. </p> <p>I have a load testing tool written in Python that basically blasts HTTP requests at a URL. I need to run performance tests against an IP-based load balancer, so the requests must come from a range of IP's. Most commercial performance tools provide this functionality, but I want to build it into my own.</p> <p>The tool uses Python's urllib2 for transport. Is it possible to send HTTP requests with spoofed IP addresses for the packets making up the request?</p>
19
2009-07-25T01:11:24Z
1,180,897
<p>Quick note, as I just learned this yesterday:</p> <p>I think you've implied you know this already, but any responses to an HTTP request go to the IP address that shows up in the header. So if you are wanting to see those responses, you need to have control of the router and have it set up so that the spoofed IPs are all routed back to the IP you are using to view the responses.</p>
4
2009-07-25T01:27:55Z
[ "python", "http", "networking", "sockets", "urllib2" ]
Spoofing the origination IP address of an HTTP request
1,180,878
<p>This only needs to work on a single subnet and is not for malicious use. </p> <p>I have a load testing tool written in Python that basically blasts HTTP requests at a URL. I need to run performance tests against an IP-based load balancer, so the requests must come from a range of IP's. Most commercial performance tools provide this functionality, but I want to build it into my own.</p> <p>The tool uses Python's urllib2 for transport. Is it possible to send HTTP requests with spoofed IP addresses for the packets making up the request?</p>
19
2009-07-25T01:11:24Z
1,180,938
<p>This is a misunderstanding of HTTP. The HTTP protocol is based on top of <a href="http://en.wikipedia.org/wiki/Transmission%5FControl%5FProtocol">TCP</a>. The TCP protocol relies on a 3 way handshake to initialize requests.</p> <p><img src="http://upload.wikimedia.org/wikipedia/commons/archive/c/c7/20051221162333!300px-Tcp-handshake.png" alt="alt text" /></p> <p>Needless to say, if you spoof your originating IP address, you will never get past the synchronization stage and no HTTP information will be sent (the server can't send it to a legal host).</p> <p>If you need to test an IP load balancer, this is not the way to do it.</p>
40
2009-07-25T01:46:29Z
[ "python", "http", "networking", "sockets", "urllib2" ]
Spoofing the origination IP address of an HTTP request
1,180,878
<p>This only needs to work on a single subnet and is not for malicious use. </p> <p>I have a load testing tool written in Python that basically blasts HTTP requests at a URL. I need to run performance tests against an IP-based load balancer, so the requests must come from a range of IP's. Most commercial performance tools provide this functionality, but I want to build it into my own.</p> <p>The tool uses Python's urllib2 for transport. Is it possible to send HTTP requests with spoofed IP addresses for the packets making up the request?</p>
19
2009-07-25T01:11:24Z
1,181,059
<p>You could just use IP aliasing on a Linux box and set up as many IP addresses as you want. The catch is that you can't predict what IP will get stamped in the the IP header unless you set it to another network and set an explicit route for that network. i.e. -</p> <pre><code>current client address on eth0 = 192.168.1.10/24 server-side: ifconfig eth0:1 172.16.1.1 netmask 255.255.255.0 client-side: ifconfig eth0:1 172.16.1.2 netmask 255.255.255.0 route add -net 172.16.1.0/24 gw 172.16.1.1 metric 0 </code></pre> <p>Repeat for as many subnets as you want. Restart apache to set listeners on all the new alias interfaces and you're off and running.</p>
1
2009-07-25T02:50:19Z
[ "python", "http", "networking", "sockets", "urllib2" ]
Spoofing the origination IP address of an HTTP request
1,180,878
<p>This only needs to work on a single subnet and is not for malicious use. </p> <p>I have a load testing tool written in Python that basically blasts HTTP requests at a URL. I need to run performance tests against an IP-based load balancer, so the requests must come from a range of IP's. Most commercial performance tools provide this functionality, but I want to build it into my own.</p> <p>The tool uses Python's urllib2 for transport. Is it possible to send HTTP requests with spoofed IP addresses for the packets making up the request?</p>
19
2009-07-25T01:11:24Z
1,186,102
<p>I suggest seeing if you can configure your load balancer to make it's decision based on the X-Forwarded-For header, rather than the source IP of the packet containing the HTTP request. I know that most of the significant commercial load balancers have this capability.</p> <p>If you can't do that, then I suggest that you probably need to configure a linux box with a whole heap of secondary IP's - don't bother configuring static routes on the LB, just make your linux box the default gateway of the LB device.</p>
1
2009-07-27T01:46:10Z
[ "python", "http", "networking", "sockets", "urllib2" ]
How can you check if a key is currently pressed using Tkinter in Python?
1,181,027
<p>Is there any way to detect which keys are currently pressed using Tkinter? I don't want to have to use extra libraries if possible. I can already detect when keys are pressed, but I want to be able to check at any time what keys are pressed down at the moment.</p>
1
2009-07-25T02:38:56Z
1,181,037
<p>I think you need to keep track of events about keys getting pressed <em>and released</em> (maintaining your own set of "currently pressed" keys) -- I believe Tk doesn't keep track of that for you (and Tkinter really adds little on top of Tk, it's mostly a direct interface to it).</p>
3
2009-07-25T02:43:00Z
[ "python", "tkinter", "keylistener" ]
How can I serve unbuffered CGI content from Apache 2?
1,181,135
<p>I would like to be able to allow a user to view the output of a long-running GCI script as it is generated rather than after the script is complete. However even when I explicitly flush STDOUT the server seems to wait for the script to complete before sending the response to the client. This is on a Linux server running Apache 2.2.9.</p> <p>Example python CGI:</p> <pre><code>#!/usr/bin/python import time import sys print "Content-type: text/plain" print for i in range(1, 10): print i sys.stdout.flush() time.sleep(1) print "Done." </code></pre> <p>Similar example in perl:</p> <pre><code>#!/usr/bin/perl print "Content-type: text/plain\n\n"; for ($i = 1; $i &lt;= 10 ; $i++) { print "$i\n"; sleep(1); } print "Done."; </code></pre> <p>This link says as of Apache 1.3 CGI output should be unbuffered (but this might apply only to Apache 1.x): <a href="http://httpd.apache.org/docs/1.3/misc/FAQ-F.html#nph-scripts">http://httpd.apache.org/docs/1.3/misc/FAQ-F.html#nph-scripts</a></p> <p>Any ideas?</p>
6
2009-07-25T03:42:05Z
1,181,176
<p>According to <a href="http://search.cpan.org/~lds/CGI.pm-3.43/CGI/Push.pm" rel="nofollow">CGI::Push</a>,</p> <blockquote> <p>Apache web server from version 1.3b2 on does not need server push scripts installed as NPH scripts: the -nph parameter to do_push() may be set to a false value to disable the extra headers needed by an NPH script.</p> </blockquote> <p>You just have to find do_push equivalent in python.</p> <p><strong>Edit</strong>: Take a look at <a href="http://www.cherrypy.org/wiki/ReturnVsYield" rel="nofollow">CherryPy: Streaming the response body</a>.</p> <blockquote> <p>When you set the config entry "response.stream" to True (and use "yield") CherryPy manages the conversation between the HTTP server and your code like this:</p> </blockquote> <p><img src="http://www.cherrypy.org/attachment/wiki/ReturnVsYield/cpyield.gif?format=raw" alt="alt text" /></p>
1
2009-07-25T04:11:12Z
[ "python", "perl", "apache2", "cgi" ]
How can I serve unbuffered CGI content from Apache 2?
1,181,135
<p>I would like to be able to allow a user to view the output of a long-running GCI script as it is generated rather than after the script is complete. However even when I explicitly flush STDOUT the server seems to wait for the script to complete before sending the response to the client. This is on a Linux server running Apache 2.2.9.</p> <p>Example python CGI:</p> <pre><code>#!/usr/bin/python import time import sys print "Content-type: text/plain" print for i in range(1, 10): print i sys.stdout.flush() time.sleep(1) print "Done." </code></pre> <p>Similar example in perl:</p> <pre><code>#!/usr/bin/perl print "Content-type: text/plain\n\n"; for ($i = 1; $i &lt;= 10 ; $i++) { print "$i\n"; sleep(1); } print "Done."; </code></pre> <p>This link says as of Apache 1.3 CGI output should be unbuffered (but this might apply only to Apache 1.x): <a href="http://httpd.apache.org/docs/1.3/misc/FAQ-F.html#nph-scripts">http://httpd.apache.org/docs/1.3/misc/FAQ-F.html#nph-scripts</a></p> <p>Any ideas?</p>
6
2009-07-25T03:42:05Z
1,181,248
<p>Flushing STDOUT can help. For example, the following Perl program should work as intended:</p> <pre><code>#!/usr/bin/perl use strict; use warnings; local $| = 1; print "Content-type: text/plain\n\n"; for ( my $i = 1 ; $i &lt;= 10 ; $i++ ) { print "$i\n"; sleep(1); } print "Done."; </code></pre>
1
2009-07-25T04:56:24Z
[ "python", "perl", "apache2", "cgi" ]
How can I serve unbuffered CGI content from Apache 2?
1,181,135
<p>I would like to be able to allow a user to view the output of a long-running GCI script as it is generated rather than after the script is complete. However even when I explicitly flush STDOUT the server seems to wait for the script to complete before sending the response to the client. This is on a Linux server running Apache 2.2.9.</p> <p>Example python CGI:</p> <pre><code>#!/usr/bin/python import time import sys print "Content-type: text/plain" print for i in range(1, 10): print i sys.stdout.flush() time.sleep(1) print "Done." </code></pre> <p>Similar example in perl:</p> <pre><code>#!/usr/bin/perl print "Content-type: text/plain\n\n"; for ($i = 1; $i &lt;= 10 ; $i++) { print "$i\n"; sleep(1); } print "Done."; </code></pre> <p>This link says as of Apache 1.3 CGI output should be unbuffered (but this might apply only to Apache 1.x): <a href="http://httpd.apache.org/docs/1.3/misc/FAQ-F.html#nph-scripts">http://httpd.apache.org/docs/1.3/misc/FAQ-F.html#nph-scripts</a></p> <p>Any ideas?</p>
6
2009-07-25T03:42:05Z
1,181,959
<p>Randal Schwartz's article <a href="http://www.stonehenge.com/merlyn/LinuxMag/col39.html" rel="nofollow">Watching long processes through CGI</a> explains a different (and IMHO, better) way of watching a long running process.</p>
4
2009-07-25T11:56:47Z
[ "python", "perl", "apache2", "cgi" ]
How can I serve unbuffered CGI content from Apache 2?
1,181,135
<p>I would like to be able to allow a user to view the output of a long-running GCI script as it is generated rather than after the script is complete. However even when I explicitly flush STDOUT the server seems to wait for the script to complete before sending the response to the client. This is on a Linux server running Apache 2.2.9.</p> <p>Example python CGI:</p> <pre><code>#!/usr/bin/python import time import sys print "Content-type: text/plain" print for i in range(1, 10): print i sys.stdout.flush() time.sleep(1) print "Done." </code></pre> <p>Similar example in perl:</p> <pre><code>#!/usr/bin/perl print "Content-type: text/plain\n\n"; for ($i = 1; $i &lt;= 10 ; $i++) { print "$i\n"; sleep(1); } print "Done."; </code></pre> <p>This link says as of Apache 1.3 CGI output should be unbuffered (but this might apply only to Apache 1.x): <a href="http://httpd.apache.org/docs/1.3/misc/FAQ-F.html#nph-scripts">http://httpd.apache.org/docs/1.3/misc/FAQ-F.html#nph-scripts</a></p> <p>Any ideas?</p>
6
2009-07-25T03:42:05Z
4,176,941
<p>You must put your push script into a special directory wich contain a special .htaccess with this environnment specs:</p> <pre><code>Options +ExecCGI AddHandler cgi-script .cgi .sh .pl .py SetEnvIfNoCase Content-Type \ "^multipart/form-data;" "MODSEC_NOPOSTBUFFERING=Do not buffer file uploads" SetEnv no-gzip dont-vary </code></pre>
2
2010-11-14T09:37:25Z
[ "python", "perl", "apache2", "cgi" ]
Why isn't Django returning a datetime field from the database?
1,181,145
<p>For my first Django app, I'm trying to write a simple quote collection site (think bash.org), with really simple functionality, just to get my feet wet. I'm using sqlite as my database, since it's the easiest to setup.</p> <p>Here's my only model right now:</p> <pre><code>class Quote(models.Model): text = models.TextField(); upvotes = models.IntegerField(default=0) downvotes = models.IntegerField(default=0) active = models.BooleanField(default=False) date_published = models.DateTimeField(auto_now_add=True) </code></pre> <p>And a really simple detail template, just to dump the information:</p> <pre><code>Quote: {{ quote.text }}&lt;br&gt; Upvotes: {{ quote.upvotes }}&lt;br&gt; Downvotes: {{ quote.downvotes }}&lt;br&gt; Published: {{ qoute.date_published|date:"F j, Y, g:i a" }} </code></pre> <p>When I go to the detail page, everything for the given object is outputted properly, except for the datetime (blank). However, I've checked the database and verified that there is a datetime stored in that object's column, and it shows up fine admin area. Also, when I run the shell from manage.py, here's what I get:</p> <pre><code>&gt;&gt;&gt; q = Quote.objects.all()[0] &gt;&gt;&gt; q.date_published datetime.datetime(2009, 7, 24, 23, 1, 7, 858688) </code></pre> <p>Also, I'm using the generic view <code>django.views.generic.list_detail.object_detail</code> to handle the request, but I also tried to use the view below and got the same result.</p> <pre><code>def detail(Request, id): q = get_object_or_404(Quote, pk=id) return render_to_response('quotable/quote_detail.html', {'quote': q}) </code></pre> <p>Am I'm doing something wrong in my attempt to display the date, or is something else going on here?</p> <p>Thanks.</p>
2
2009-07-25T03:50:28Z
1,181,150
<p>I'm not sure what you're doing with that <code>date:</code> filter -- what happens if you replace it with something simple, such as <code>date:"D d M Y</code>?</p>
0
2009-07-25T03:54:56Z
[ "python", "django", "datetime", "sqlite" ]
Why isn't Django returning a datetime field from the database?
1,181,145
<p>For my first Django app, I'm trying to write a simple quote collection site (think bash.org), with really simple functionality, just to get my feet wet. I'm using sqlite as my database, since it's the easiest to setup.</p> <p>Here's my only model right now:</p> <pre><code>class Quote(models.Model): text = models.TextField(); upvotes = models.IntegerField(default=0) downvotes = models.IntegerField(default=0) active = models.BooleanField(default=False) date_published = models.DateTimeField(auto_now_add=True) </code></pre> <p>And a really simple detail template, just to dump the information:</p> <pre><code>Quote: {{ quote.text }}&lt;br&gt; Upvotes: {{ quote.upvotes }}&lt;br&gt; Downvotes: {{ quote.downvotes }}&lt;br&gt; Published: {{ qoute.date_published|date:"F j, Y, g:i a" }} </code></pre> <p>When I go to the detail page, everything for the given object is outputted properly, except for the datetime (blank). However, I've checked the database and verified that there is a datetime stored in that object's column, and it shows up fine admin area. Also, when I run the shell from manage.py, here's what I get:</p> <pre><code>&gt;&gt;&gt; q = Quote.objects.all()[0] &gt;&gt;&gt; q.date_published datetime.datetime(2009, 7, 24, 23, 1, 7, 858688) </code></pre> <p>Also, I'm using the generic view <code>django.views.generic.list_detail.object_detail</code> to handle the request, but I also tried to use the view below and got the same result.</p> <pre><code>def detail(Request, id): q = get_object_or_404(Quote, pk=id) return render_to_response('quotable/quote_detail.html', {'quote': q}) </code></pre> <p>Am I'm doing something wrong in my attempt to display the date, or is something else going on here?</p> <p>Thanks.</p>
2
2009-07-25T03:50:28Z
1,181,203
<p>As Adam Bernier mentioned, you're misspelling <code>quote</code></p>
2
2009-07-25T04:28:00Z
[ "python", "django", "datetime", "sqlite" ]
Why isn't Django returning a datetime field from the database?
1,181,145
<p>For my first Django app, I'm trying to write a simple quote collection site (think bash.org), with really simple functionality, just to get my feet wet. I'm using sqlite as my database, since it's the easiest to setup.</p> <p>Here's my only model right now:</p> <pre><code>class Quote(models.Model): text = models.TextField(); upvotes = models.IntegerField(default=0) downvotes = models.IntegerField(default=0) active = models.BooleanField(default=False) date_published = models.DateTimeField(auto_now_add=True) </code></pre> <p>And a really simple detail template, just to dump the information:</p> <pre><code>Quote: {{ quote.text }}&lt;br&gt; Upvotes: {{ quote.upvotes }}&lt;br&gt; Downvotes: {{ quote.downvotes }}&lt;br&gt; Published: {{ qoute.date_published|date:"F j, Y, g:i a" }} </code></pre> <p>When I go to the detail page, everything for the given object is outputted properly, except for the datetime (blank). However, I've checked the database and verified that there is a datetime stored in that object's column, and it shows up fine admin area. Also, when I run the shell from manage.py, here's what I get:</p> <pre><code>&gt;&gt;&gt; q = Quote.objects.all()[0] &gt;&gt;&gt; q.date_published datetime.datetime(2009, 7, 24, 23, 1, 7, 858688) </code></pre> <p>Also, I'm using the generic view <code>django.views.generic.list_detail.object_detail</code> to handle the request, but I also tried to use the view below and got the same result.</p> <pre><code>def detail(Request, id): q = get_object_or_404(Quote, pk=id) return render_to_response('quotable/quote_detail.html', {'quote': q}) </code></pre> <p>Am I'm doing something wrong in my attempt to display the date, or is something else going on here?</p> <p>Thanks.</p>
2
2009-07-25T03:50:28Z
1,183,105
<p>I believe that django.views.generic.list_detail.object_detail <a href="http://docs.djangoproject.com/en/dev/intro/tutorial04/" rel="nofollow">uses a variable named object_id, not id</a>.</p> <pre><code> urlpatterns = patterns('', (r'^$', 'django.views.generic.list_detail.object_list', info_dict), (r'^(?P&lt;object_id&gt;\d+)/$', 'django.views.generic.list_detail.object_detail', info_dict), url(r'^(?P&lt;object_id&gt;\d+)/results/$', 'django.views.generic.list_detail.object_detail', dict(info_dict, template_name='polls/results.html'), 'poll_results'), (r'^(?P&lt;poll_id&gt;\d+)/vote/$', 'mysite.polls.views.vote'), ) </code></pre> <p>When you change to using the detail template, your url pattern will be wrong.</p>
0
2009-07-25T21:23:45Z
[ "python", "django", "datetime", "sqlite" ]
emulating LiveHTTPheader in server side script or javascript?
1,181,233
<p>I ran into this problem when scraping sites with heavy usage of javascript to obfuscate it's data.</p> <p>For example,</p> <p>"a href="javascript:void(0)" onClick="grabData(23)"> VIEW DETAILS </p> <p>This href attribute, reveals no information about the actual URL. You'd have to manually look and examine the grabData() javascript function to get a clue.</p> <p>OR</p> <p>The old school way is manually opening up Live HTTP header add on for firefox, and monitoring the POST perimeters, which reveals the actual URL being POSTed.</p> <p>So i'm wondering, is there a way to capture the POST parameters in a server side script or Javscript, as Live HTTP header does, for the outgoing and incoming POST parameters? This would make even the most javscript obfuscated web pages easily scrapable.</p> <p>thanks.</p>
0
2009-07-25T04:49:09Z
1,181,238
<p>I'm not sure I understand the question but...</p> <p>In PHP, incoming POST parameters are stored in the <code>$_POST</code> array, you can display them with <code>print_r($_POST);</code>.</p>
1
2009-07-25T04:51:43Z
[ "php", "jquery", "python" ]
dynamic plotting in wxpython
1,181,391
<p>I have been developing a GUI for reading continuous data from a serial port. After reading the data, some calculations are made and the results will be plotted and refreshed (aka dynamic plotting). I use the wx backend provided in the matplotlib for this purposes. To do this, I basically use an array to store my results, in which I keep appending it to, after each calculation, and replot the whole graph. To make it "dynamic", I just set the x-axis lower and upper limits for each iteration. Something like found in: </p> <p><a href="http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/" rel="nofollow">http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/</a></p> <p>The problem, however, is that since the data is continuous, and if I keep plotting it, eventually the system memory will run out and system will crash. Is there any other way I can plot my result continuously?</p>
2
2009-07-25T06:29:50Z
1,181,433
<blockquote> <p>To do this, I basically use an array to store my results, in which I keep appending it to</p> </blockquote> <p>Try limiting the size of this array, either by deleting old data or by deleting every n-th entry (the screen resolution will prevent all entries to be displayed anyway). I assume you write all the data to disk so you won't lose anything.</p> <p>Also, analise your code for memory leaks. Stuff you use and don't need anymore but that doesn't get garbage-collected because you still have a reference to it.</p>
3
2009-07-25T07:01:02Z
[ "python", "wxpython", "matplotlib" ]
dynamic plotting in wxpython
1,181,391
<p>I have been developing a GUI for reading continuous data from a serial port. After reading the data, some calculations are made and the results will be plotted and refreshed (aka dynamic plotting). I use the wx backend provided in the matplotlib for this purposes. To do this, I basically use an array to store my results, in which I keep appending it to, after each calculation, and replot the whole graph. To make it "dynamic", I just set the x-axis lower and upper limits for each iteration. Something like found in: </p> <p><a href="http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/" rel="nofollow">http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/</a></p> <p>The problem, however, is that since the data is continuous, and if I keep plotting it, eventually the system memory will run out and system will crash. Is there any other way I can plot my result continuously?</p>
2
2009-07-25T06:29:50Z
1,181,968
<p>I have created such a component with pythons Tkinter. The source is <a href="http://code.google.com/p/asuro-syd/source/browse/lib/pysyd/SydPlot.py" rel="nofollow">here</a>. </p> <p>Basically, you have to keep the plotted data <em>somewhere</em>. You cannot keep an infinite amount of data points in memory, so you either have to save it to disk or you have to overwrite old data points.</p>
1
2009-07-25T12:00:36Z
[ "python", "wxpython", "matplotlib" ]
dynamic plotting in wxpython
1,181,391
<p>I have been developing a GUI for reading continuous data from a serial port. After reading the data, some calculations are made and the results will be plotted and refreshed (aka dynamic plotting). I use the wx backend provided in the matplotlib for this purposes. To do this, I basically use an array to store my results, in which I keep appending it to, after each calculation, and replot the whole graph. To make it "dynamic", I just set the x-axis lower and upper limits for each iteration. Something like found in: </p> <p><a href="http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/" rel="nofollow">http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/</a></p> <p>The problem, however, is that since the data is continuous, and if I keep plotting it, eventually the system memory will run out and system will crash. Is there any other way I can plot my result continuously?</p>
2
2009-07-25T06:29:50Z
1,182,006
<p>Data and representation of data are two different things. You might want to store your data to disk if it's important data to be analyzed later, but only keep a fixed period of time or the last N points for display purposes. You could even let the user pick the time frame to be displayed. </p>
1
2009-07-25T12:23:40Z
[ "python", "wxpython", "matplotlib" ]
dynamic plotting in wxpython
1,181,391
<p>I have been developing a GUI for reading continuous data from a serial port. After reading the data, some calculations are made and the results will be plotted and refreshed (aka dynamic plotting). I use the wx backend provided in the matplotlib for this purposes. To do this, I basically use an array to store my results, in which I keep appending it to, after each calculation, and replot the whole graph. To make it "dynamic", I just set the x-axis lower and upper limits for each iteration. Something like found in: </p> <p><a href="http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/" rel="nofollow">http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/</a></p> <p>The problem, however, is that since the data is continuous, and if I keep plotting it, eventually the system memory will run out and system will crash. Is there any other way I can plot my result continuously?</p>
2
2009-07-25T06:29:50Z
7,823,652
<p>I actually ran into this problem (more of a mental block, actually...).</p> <p>First of all I copy-pasted some wx Plot code from <a href="http://wiki.wxpython.org/Using%20wxPython%20Demo%20Code" rel="nofollow">wx Demo Code</a>. </p> <p>What I do is keep a live log of a value, and compare it to two markers (min and max, shown as red and green dotted lines) (but I will make these 2 markers optional - hence the optional parameters).</p> <p>In order to implement the live log, I first wanted to use the deque class, but since the data is in tuple mode (x,y coordinates) I gave up and just tried to rewrite the entire parameter list of tuples: see _update_coordinates.</p> <p>It works just fine for keeping track of the last 100-10,000 plots. Would have also included a printscreen, but I'm too much of a noob at stackoverflow to be allowed :))</p> <p>My live parameter is updated every 0.25 seconds over a 115kbps UART.</p> <p>The trick is at the end, in the custom refresh method!</p> <p>Here is most of the code:</p> <pre><code>class DefaultPlotFrame(wx.Frame): def __init__(self, ymin=0, ymax=MAXIMUM_PLOTS, minThreshold=None, maxThreshold=None, plotColour='blue', title="Default Plot Frame", position=(10,10), backgroundColour="yellow", frameSize=(400,300)): self.minThreshold = minThreshold self.maxThreshold = maxThreshold self.frame1 = wx.Frame(None, title="wx.lib.plot", id=-1, size=(410, 340), pos=position) self.panel1 = wx.Panel(self.frame1) self.panel1.SetBackgroundColour(backgroundColour) self.ymin = ymin self.ymax = ymax self.title = title self.plotColour = plotColour self.lines = [None, None, None] # mild difference between wxPython26 and wxPython28 if wx.VERSION[1] &lt; 7: self.plotter = plot.PlotCanvas(self.panel1, size=frameSize) else: self.plotter = plot.PlotCanvas(self.panel1) self.plotter.SetInitialSize(size=frameSize) # enable the zoom feature (drag a box around area of interest) self.plotter.SetEnableZoom(False) # list of (x,y) data point tuples self.coordinates = [] for x_item in range(MAXIMUM_PLOTS): self.coordinates.append((x_item, (ymin+ymax)/2)) self.queue = deque(self.coordinates) if self.maxThreshold!=None: self._update_max_threshold() #endif if self.lockThreshold!=None: self._update_min_threshold() #endif self.line = plot.PolyLine(self.coordinates, colour=plotColour, width=1) self.lines[0] = (self.line) self.gc = plot.PlotGraphics(self.lines, title, 'Time', 'Value') self.plotter.Draw(self.gc, xAxis=(0, MAXIMUM_PLOTS), yAxis=(ymin, ymax)) self.frame1.Show(True) def _update_max_threshold(self): if self.maxThreshold!=None: self.maxCoordinates = [] for x_item in range(MAXIMUM_PLOTS): self.maxCoordinates.append((x_item, self.maxThreshold)) #endfor self.maxLine = plot.PolyLine(self.maxCoordinates, colour="green", width=1) self.maxMarker = plot.PolyMarker(self.maxCoordinates, colour="green", marker='dot') self.lines[1] = self.maxMarker #endif def _update_live_param(self, liveParam, minParam, maxParam): if minParam!=None: self.minThreshold = int(minParam) self._update_min_threshold() #endif if maxParam!=None: self.maxThreshold = int(maxParam) self._update_max_threshold() #endif if liveParam!=None: self._update_coordinates(int(liveParam)) #endif def _update_coordinates(self, newValue): newList = [] for x,y in self.coordinates[1:]: newList.append((x-1, y)) #endfor newList.append((x, newValue)) print "New list", newList self.line = (plot.PolyLine(newList, colour=self.plotColour, width=1)) self.lines[0] = self.line self.coordinates = newList def _MyLIVE_MAGIC_refresh__(self, liveParam=None, minParam=None, maxParam=None): self._update_live_param(liveParam, minParam, maxParam) self.gc = plot.PlotGraphics(self.lines, self.title, 'Time', 'Value') self.plotter.Draw(self.gc, xAxis=(0, MAXIMUM_PLOTS), yAxis=(self.ymin, self.ymax)) self.plotter.Refresh() self.frame1.Refresh() </code></pre>
0
2011-10-19T15:19:34Z
[ "python", "wxpython", "matplotlib" ]
Practical point of view: Why would I want to use Python with C++?
1,181,462
<p>I've been seeing some examples of Python being used with c++, and I'm trying to understand why would someone want to do it. What are the benefits of calling C++ code from an external language such as Python?</p> <p>I'd appreciate a simple example - Boost::Python will do</p>
4
2009-07-25T07:14:52Z
1,181,468
<p>Here's two possibilities:</p> <ol> <li>Perhaps the C++ code is already written &amp; available for use. </li> <li>It's likely the C++ code is faster/smaller than equivalent Python</li> </ol>
3
2009-07-25T07:19:34Z
[ "c++", "python" ]
Practical point of view: Why would I want to use Python with C++?
1,181,462
<p>I've been seeing some examples of Python being used with c++, and I'm trying to understand why would someone want to do it. What are the benefits of calling C++ code from an external language such as Python?</p> <p>I'd appreciate a simple example - Boost::Python will do</p>
4
2009-07-25T07:14:52Z
1,181,475
<p>It depends on your point of view:</p> <p><strong>Calling C++ code from a python application</strong></p> <p>You generally want to do this when performance is an issue. Highly dynamic languages like python are typically somewhat slower then native code such as C++. "Features" of C++ such as manual memory management allows for the development of very fast libraries, which can then be called from python in order to gain performance.</p> <p>Another reason is due to the fact that most libraries on both windows and *nix are written in C or C++, and it's a huge advantage to have this existing code base available.</p> <p><strong>Calling python code from a C++ application</strong></p> <p>Complex applications sometimes require the ability to define additional abilities. Adding behaviors in a compiled application is messy, requires the original source code and is time consuming. Therefore it's often strategic to embed a scripting language such as python in order to make the application more flexible and customizable.</p> <p>As for an example: I think you need to clarify a bit what you're interested in if you want the sample to be of any help. The boost manual provides a simple <a href="http://www.boost.org/doc/libs/1%5F39%5F0/libs/python/doc/tutorial/doc/html/index.html" rel="nofollow">hello world sample</a>, if that's what you're looking for.</p>
21
2009-07-25T07:24:16Z
[ "c++", "python" ]
Practical point of view: Why would I want to use Python with C++?
1,181,462
<p>I've been seeing some examples of Python being used with c++, and I'm trying to understand why would someone want to do it. What are the benefits of calling C++ code from an external language such as Python?</p> <p>I'd appreciate a simple example - Boost::Python will do</p>
4
2009-07-25T07:14:52Z
1,181,476
<p>Generally, you'd call C++ from python in order to use an existing library or other functionality. Often someone else has written a set of functions that make your life easier, and calling compiled C code is easier than re-writing the library in python.</p> <p>The other reason is for performance purposes. Often, specific functions of an otherwise completely scripted program are written in a pre-compiled language like C because they take a long time to run and can be more efficiently done in a lower-level language.</p> <p>A third reason is for interfacing with devices. Python doesn't natively include a lot of code for dealing with sound cards, serial ports, and so on. If your device needs a device driver, python will talk to it via pre-compiled code you include in your app.</p>
5
2009-07-25T07:25:08Z
[ "c++", "python" ]
Practical point of view: Why would I want to use Python with C++?
1,181,462
<p>I've been seeing some examples of Python being used with c++, and I'm trying to understand why would someone want to do it. What are the benefits of calling C++ code from an external language such as Python?</p> <p>I'd appreciate a simple example - Boost::Python will do</p>
4
2009-07-25T07:14:52Z
1,181,481
<p>Because C++ provides a direct way of calling OS services, and (if used in a careful way) can produce code that is more efficient in memory and time, whereas Python is a high-level language, and is less painful to use in those situations where utter efficiency isn't a concern and where you already have libraries giving you access to the services you need.</p> <p><strong>If you're a C++ user</strong>, you may wonder why this is necessary, but the expressiveness and safety of a high-level language has such a massive relative effect on your productivity, it has to be experienced to be understood or believed.</p> <p>I can't speak for Python specifically, but I've heard people talk in terms of "tripling" their productivity by doing most of their development in it and using C++ only where shown to be necessary by profiling, or to create extra libraries.</p> <p><strong>If you're a Python user</strong>, you may not have encountered a situation where you need anything beyond the libraries already available, and you may not have a problem with the performance you get from pure Python (this is quite likely). In which case - lucky you! You can forget about all this.</p>
3
2009-07-25T07:28:47Z
[ "c++", "python" ]
Practical point of view: Why would I want to use Python with C++?
1,181,462
<p>I've been seeing some examples of Python being used with c++, and I'm trying to understand why would someone want to do it. What are the benefits of calling C++ code from an external language such as Python?</p> <p>I'd appreciate a simple example - Boost::Python will do</p>
4
2009-07-25T07:14:52Z
1,181,567
<ol> <li>Performance :</li> </ol> <p>From my limited experience, Python is about 10 times slower than using C. Using Psyco will dramatically improve it, but still about 5 times slower than C. BUT, calling c module from python is only a little faster than Psyco.</p> <ol> <li>When you have some libraries in C.<br /> For example, I am working heavily on SIP. It's a very complicated protocol stacks and there is no complete Python implementation. So my only choice is calling SIP libraries written in C.</li> </ol> <p>There are also this kind of cases, like video/audio decoding.</p>
0
2009-07-25T08:14:46Z
[ "c++", "python" ]
Practical point of view: Why would I want to use Python with C++?
1,181,462
<p>I've been seeing some examples of Python being used with c++, and I'm trying to understand why would someone want to do it. What are the benefits of calling C++ code from an external language such as Python?</p> <p>I'd appreciate a simple example - Boost::Python will do</p>
4
2009-07-25T07:14:52Z
1,182,051
<p>One nice thing about using a scripting language is that you can reload new code into the application without quitting the app, then making changes, recompile, and then relaunching the app. When people talk about quicker development times, some of that refers to this capability. A downside of using a scripting languages is that their debuggers are usually not as fully featured as what you would have in C++. I haven't done any Python programming so I don't know what the features are of its debugger, if it has one at all.</p> <p>This answer doesn't exactly answer what you asked but I thought it was relevant. The answer is more the pro/cons of using a scripting language. Please don't flame me. :)</p>
0
2009-07-25T12:54:35Z
[ "c++", "python" ]
Practical point of view: Why would I want to use Python with C++?
1,181,462
<p>I've been seeing some examples of Python being used with c++, and I'm trying to understand why would someone want to do it. What are the benefits of calling C++ code from an external language such as Python?</p> <p>I'd appreciate a simple example - Boost::Python will do</p>
4
2009-07-25T07:14:52Z
1,182,301
<p>Here's a real-life example: I've written a DLL in C to interface with some custom hardware for work. Then for the very first stage of testing, I was writing short programs in C to verify that the different commands were working properly. The process of write, compile, run took probably 3-5 times as long as when I finally wrote a Python interface to the DLL using <code>ctypes</code>.</p> <p>Now, I can write testing scripts much more rapidly with much less regards to proper variable initialization and memory management that I would have to worry about in C. In fact, I've even been able to use unit testing libraries in Python to create much more robust tests than before. Would that have been possible in C? Absolutely, but it would have taken me much longer, and it would have been many more lines of code. </p> <p>Fewer lines of code in Python means (in general) that there are fewer things with my main logic that can go wrong.</p> <p>Moreover, since the hardware communication is almost completely IO bound, there's no <em>need</em> to write any supporting code in C. I may as well program in whatever is fastest to develop.</p> <p>So there you go, real-life example.</p>
2
2009-07-25T15:23:09Z
[ "c++", "python" ]
Controlling mouse with Python
1,181,464
<p>How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?</p>
101
2009-07-25T07:15:30Z
1,181,517
<p><a href="http://danielbaggio.blogspot.com/2009/03/python-mouse-move-in-5-lines-of-code.html" rel="nofollow">http://danielbaggio.blogspot.com/2009/03/python-mouse-move-in-5-lines-of-code.html</a></p> <pre><code>from Xlib import X, display d = display.Display() s = d.screen() root = s.root root.warp_pointer(300,300) d.sync() </code></pre>
7
2009-07-25T07:43:37Z
[ "python", "mouse" ]
Controlling mouse with Python
1,181,464
<p>How does one control the mouse cursor in Python, i.e. move it to certain position and click, under Windows?</p>
101
2009-07-25T07:15:30Z
1,181,538
<p>Tested on WinXP, Python 2.6 after installing <a href="http://sourceforge.net/projects/pywin32/files/">pywin32</a> (pywin32-214.win32-py2.6.exe in my case):</p> <pre><code>import win32api, win32con def click(x,y): win32api.SetCursorPos((x,y)) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x,y,0,0) win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x,y,0,0) click(10,10) </code></pre>
193
2009-07-25T07:57:19Z
[ "python", "mouse" ]