title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
how to get content of a small ascii file in python? | 1,432,126 | <p>Let's say we want to implement an equivalent of the PHP's <a href="http://fr2.php.net/manual/en/function.file-get-contents.php"><code>file_get_content</code></a>.</p>
<p>What is the best practice? (elegant and reliable)</p>
<p>Here are some proposition, are they correct?</p>
<p>using <code>with</code> statement:</p>
<pre><code>def file_get_contents(filename):
with file(filename) as f:
s = f.read()
return s
</code></pre>
<p>is using standard <code>open()</code> safe?</p>
<pre><code>def file_get_contents(filename):
return open(filename).read()
</code></pre>
<p>What happens to file descriptor in either solution?</p>
| 20 | 2009-09-16T10:13:28Z | 1,432,235 | <p>Using the with statement is actually the nicest way to be <em>sure</em> that the file is really closed.</p>
<p>Depending on the garbage collector behavior for this task might work, but in this case, there is a nice way to be sure in all cases, so...</p>
| 3 | 2009-09-16T10:47:45Z | [
"python",
"file"
] |
how to get content of a small ascii file in python? | 1,432,126 | <p>Let's say we want to implement an equivalent of the PHP's <a href="http://fr2.php.net/manual/en/function.file-get-contents.php"><code>file_get_content</code></a>.</p>
<p>What is the best practice? (elegant and reliable)</p>
<p>Here are some proposition, are they correct?</p>
<p>using <code>with</code> statement:</p>
<pre><code>def file_get_contents(filename):
with file(filename) as f:
s = f.read()
return s
</code></pre>
<p>is using standard <code>open()</code> safe?</p>
<pre><code>def file_get_contents(filename):
return open(filename).read()
</code></pre>
<p>What happens to file descriptor in either solution?</p>
| 20 | 2009-09-16T10:13:28Z | 1,432,238 | <p>In the current implementation of CPython, both will generally immediately close the file. However, Python the language makes no such guarantee for the second one - the file will eventually be closed, but the finaliser may not be called until the next gc cycle. Implementations like Jython and IronPython will work like this, so it's good practice to explicitely close your files. </p>
<p>I'd say using the first solution is the best practice, though <code>open</code> is generally preferred to <code>file</code>. Note that you can shorten it a little though if you prefer the brevity of the second example:</p>
<pre><code>def file_get_contents(filename):
with open(filename) as f:
return f.read()
</code></pre>
<p>The <code>__exit__</code> part of the context manager will execute when you leave the body for <em>any</em> reason, including exceptions and returning from the function - there's no need to use an intermediate variable.</p>
| 29 | 2009-09-16T10:48:20Z | [
"python",
"file"
] |
how to get content of a small ascii file in python? | 1,432,126 | <p>Let's say we want to implement an equivalent of the PHP's <a href="http://fr2.php.net/manual/en/function.file-get-contents.php"><code>file_get_content</code></a>.</p>
<p>What is the best practice? (elegant and reliable)</p>
<p>Here are some proposition, are they correct?</p>
<p>using <code>with</code> statement:</p>
<pre><code>def file_get_contents(filename):
with file(filename) as f:
s = f.read()
return s
</code></pre>
<p>is using standard <code>open()</code> safe?</p>
<pre><code>def file_get_contents(filename):
return open(filename).read()
</code></pre>
<p>What happens to file descriptor in either solution?</p>
| 20 | 2009-09-16T10:13:28Z | 10,930,035 | <p>You can also use Python's v3 feature:</p>
<pre><code>>>> ''.join(open('htdocs/config.php', 'r').readlines())
"This is the first line of the file.\nSecond line of the file"
</code></pre>
<p>Read more here <a href="http://docs.python.org/py3k/tutorial/inputoutput.html" rel="nofollow">http://docs.python.org/py3k/tutorial/inputoutput.html</a></p>
| -1 | 2012-06-07T10:30:05Z | [
"python",
"file"
] |
Returning a list | 1,432,358 | <p>I have the following code:</p>
<pre><code>def foo(*args)
print len(args)
print args
</code></pre>
<p>now I'd like to know how to return that same args list. I guess it should be simple?</p>
<p>Thanks</p>
| 0 | 2009-09-16T11:16:39Z | 1,432,361 | <p>It is indeed simple:</p>
<pre><code>return args
</code></pre>
<p><a href="http://docs.python.org/tutorial/index.html" rel="nofollow">Here</a> is the Python tutorial:
There are also many resources on beginners python on the net. Some are listed <a href="http://stackoverflow.com/questions/774325/programming-tutorials-for-people-with-zero-experience">in this question</a>.</p>
| 6 | 2009-09-16T11:17:35Z | [
"python"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 1,432,505 | <p><code>os.system('clear')</code> works on linux. If you are running windows try <code>os.system('CLS')</code> instead.</p>
<p>You need to import os first like this: </p>
<pre><code>import os
</code></pre>
| 41 | 2009-09-16T11:54:59Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 1,433,135 | <p>The way to execute commands in Python 2.4+ is to use the <a href="http://docs.python.org/library/subprocess.html">subprocess</a> module. You can use it in the same way that you use <code>os.system</code>.</p>
<pre><code>import subprocess
subprocess.call("clear") # linux/mac
subprocess.call("cls", shell=True) # windows
</code></pre>
<p>If you're executing this in the python console, you'll need to do something to hide the return value (for either <code>os.system</code> or <code>subprocess.call</code>), like assigning it to a variable:</p>
<pre><code>cls = subprocess.call("cls", shell=True)
</code></pre>
| 7 | 2009-09-16T13:56:11Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 1,433,818 | <p>The "cls" and "clear" are commands which will clear a terminal (ie a DOS prompt, or terminal window). From your screenshot, you are using the shell within IDLE, which won't be affected by such things. Unfortunately, I don't think there is a way to clear the screen in IDLE. The best you could do is to scroll the screen down lots of lines, eg:</p>
<pre><code>print "\n" * 100
</code></pre>
<p>Though you could put this in a function:</p>
<pre><code>def cls(): print "\n" * 100
</code></pre>
<p>And then call it when needed as <code>cls()</code></p>
| 64 | 2009-09-16T15:44:21Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 1,433,849 | <p>Your screenshot shows you're using IDLE. <code>cls</code>/<code>clear</code> won't work for you.</p>
| 1 | 2009-09-16T15:50:56Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 1,435,237 | <p>There does not appear to be a way to clear the IDLE 'shell' buffer.</p>
| 6 | 2009-09-16T20:19:45Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 1,576,881 | <p>As mark.ribau said, it seems that there is no way to clear the Text widget in idle. One should edit the <code>EditorWindow.py</code> module and add a method and a menu item in the EditorWindow class that does something like:</p>
<pre><code>self.text.tag_remove("sel", "1.0", "end")
self.text.delete("1.0", "end")
</code></pre>
<p>and perhaps some more tag management of which I'm unaware of.</p>
| 0 | 2009-10-16T08:40:54Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 4,550,807 | <p>File -> New Window</p>
<p><strong>In the new window**</strong></p>
<p>Run -> Python Shell</p>
<p>The problem with this method is that it will clear all the things you defined, such as variables.</p>
<p>Alternatively, you should just use command prompt. </p>
<p>open up command prompt</p>
<p>type "cd c:\python27"</p>
<p>type "python example.py" , you have to edit this using IDLE when it's not in interactive mode. If you're in python shell, file -> new window.</p>
<p>Note that the example.py needs to be in the same directory as C:\python27, or whatever directory you have python installed.</p>
<p>Then from here, you just press the UP arrow key on your keyboard. You just edit example.py, use CTRL + S, then go back to command prompt, press the UP arrow key, hit enter.</p>
<p>If the command prompt gets too crowded, just type "clr"</p>
<p>The "clr" command only works with command prompt, it will not work with IDLE.</p>
| 2 | 2010-12-29T01:11:27Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 5,888,489 | <p>If you want to clear the shell buffer go to shell > restart shell in IDLE. Your question is a little vague. Do you want to clear the shell buffer or are you trying to call the OS command?</p>
| 1 | 2011-05-04T18:57:19Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 8,352,839 | <p>An extension for clearing the shell can be found in <a href="http://bugs.python.org/issue6143">Issue6143</a> as a "feature request". This extension is included with <a href="http://idlex.sourceforge.net">IdleX</a>.</p>
| 14 | 2011-12-02T07:04:16Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 8,846,657 | <pre><code>>>> import os
>>>def cls():
... os.system("clear")
...
>>>cls()
</code></pre>
<p>That does is perfectly. No '0' printed either.</p>
| 6 | 2012-01-13T06:13:07Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 12,491,227 | <p>I do this on my mac like so:</p>
<p>First..
I have a file named fxn.py in a folder I have added to PYTHONPATH so each time I load python, I can just do</p>
<pre><code>>>> from fxn import *
</code></pre>
<p>...all my functions declared are now available. one of the functions declared therein is:</p>
<pre><code>import os
def superclear():
os.system("/usr/bin/osascript -e 'tell application \"System Events\" to tell process \"Terminal\" to keystroke \"k\" using command down'")
</code></pre>
<p>So when I do:</p>
<pre><code>>>> superclear()
</code></pre>
<p><strong>ZAP!</strong> it's all gone. (that is... All. Gone. No scrolling up to see what has been done before, hence the name "<strong>superclear</strong>")</p>
| 0 | 2012-09-19T08:44:55Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 14,471,376 | <p>There is no need to write your own function to do this! Python has a built in clear function. </p>
<p>Type the following in the command prompt:</p>
<pre><code>shell.clear()
</code></pre>
| -2 | 2013-01-23T02:12:44Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 16,622,317 | <p>The best way to do it on windows is using the command prompt 'cmd' and access python directory the command prompt could be found on the start menu >run>cmd</p>
<pre><code>C:\>cd Python27
C:\Python27>python.exe
Python 2.7.3 (default, Apr 10 2012, 23:24:47) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>import os
>>>os.system('cls') #This will clear the screen and return the value 0
</code></pre>
| 0 | 2013-05-18T08:46:42Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 16,634,647 | <p>If you are using the terminal ( i am using ubuntu ) , then just use the combination of <kbd>CTRL</kbd>+<kbd>l</kbd> from keyboard to clear the python script, even it clears the terminal script...</p>
| -1 | 2013-05-19T12:28:15Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 18,176,163 | <p>You can make an <a href="http://www.autohotkey.com/" rel="nofollow">AutoHotKey</a> script.</p>
<p>To set ctrl-r to a hotkey to clear the shell:</p>
<pre><code>^r::SendInput print '\n' * 50 {Enter}
</code></pre>
<p>Just install AutoHotKey, put the above in a file called idle_clear.ahk, run the file, and your hotkey is active.</p>
| 2 | 2013-08-11T20:07:07Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 24,121,785 | <p>This works for me in Windows:</p>
<p><code>print chr(12)</code></p>
| 0 | 2014-06-09T13:54:38Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 24,466,596 | <p>Most of the answers appear here do clearing the DOS prompt screen clearing commands. Which is not the Question asked here. An other answer here posted was the printing blank lines to show a clearing effect of the screen. </p>
<p>The simplest answer of this question is </p>
<blockquote>
<p>It is not possible to clear python IDLE shell without some external module integration. If you really want to get a blank pure fresh shell just close the previous shell and run it again </p>
</blockquote>
| 7 | 2014-06-28T11:59:57Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 25,972,072 | <pre><code>from subprocess import call as c
def cls():
c("cls",shell=True)
print([x for x in range(10000)])
cls()
</code></pre>
<p>Whenever you wish to clear console call the function cls, but note that this function will clear the screen in Windows only if you are running Python Script using cmd prompt, it will not clear the buffer if you running by IDLE.</p>
| 1 | 2014-09-22T10:38:01Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 26,911,370 | <p>use this</p>
<pre><code>for num in range(1,100):
print("\n")
</code></pre>
| 0 | 2014-11-13T14:37:56Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 29,189,588 | <p><kbd>ctrl</kbd> + <kbd>L</kbd> clears the screen on Ubuntu Linux.</p>
| 12 | 2015-03-22T00:19:55Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 37,799,264 | <p>I like to use:</p>
<pre><code>import os
clear = lambda : os.system('cls') # or clear for Linux
clear()
</code></pre>
| 0 | 2016-06-13T21:15:39Z | [
"python",
"python-idle"
] |
Any way to clear python's IDLE window? | 1,432,480 | <p>I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.</p>
<p>How do I clear python's IDLE window?</p>
| 80 | 2009-09-16T11:49:36Z | 38,944,644 | <p>None of these solutions worked for me on Windows 7 and within IDLE. Wound up using PowerShell, running Python within it and exiting to call "cls" in PowerShell to clear the window. </p>
<p>CONS: Assumes Python is already in the PATH variable. Also, this does clear your Python variables (though so does restarting the shell).</p>
<p>PROS: Retains any window customization you've made (color, font-size).</p>
| 0 | 2016-08-14T17:18:02Z | [
"python",
"python-idle"
] |
Help with Admin forms validation error | 1,432,530 | <p>I am quite new to Django, I'm having few problems with validation
forms in Admin module, more specifically with raising exceptions in the
ModelForm. I can validate and manipulate data in clean methods but
cannot seem to raise any errors. Whenever I include any raise
statement I get this error "'NoneType' object has no attribute
'ValidationError'". When I remove the raise part everything works
fine. </p>
<p>Then if I reimport django.forms (inside clean method) with a different alias (e.g. from django import forms as blahbalh) then I'm able to raise messages using blahblah.ValidateException.</p>
<p>Any tips or suggestions on doing such a thing properly ?</p>
<p>Here's an example of what I'm doing in Admin.py:</p>
<h3>admin.py</h3>
<p>from django import forms
from proj.models import *
from django.contrib import admin</p>
<p>class FontAdminForm(forms.ModelForm):</p>
<pre><code>class Meta:
model = Font
def clean_name(self):
return self.cleaned_data["name"].upper()
def clean_description(self):
desc = self.cleaned_data['description']
if desc and if len(desc) < 10:
raise forms.ValidationError('Description is too short.')
return desc
</code></pre>
<p>class FontAdmin(admin.ModelAdmin):</p>
<pre><code>form = FontAdminForm
list_display = ['name', 'description']
</code></pre>
<p>admin.site.register(Font, FontAdmin)</p>
<p>--
Thanks,
A</p>
| 0 | 2009-09-16T11:59:07Z | 1,432,695 | <p>You problem might be in the * import.</p>
<pre><code>from proj.models import *
</code></pre>
<p>if proj.models contains any variable named forms (including some module import like "from django import forms), it could trounce your initial import of:</p>
<pre><code>from django import forms
</code></pre>
<p>I would explicitly import from proj.models, e.g.</p>
<pre><code>from proj.models import Font
</code></pre>
<p>If that doesn't work, see if there are any other variables name "forms" that could be messing with your scope.</p>
<p>You can use introspection to see what "forms" is. Inside your clean_description method:</p>
<pre><code>print forms.__package__
</code></pre>
<p>My guess is it is not going to be "django" (or will return an error, indicating that it is definitely not django.forms).</p>
| 3 | 2009-09-16T12:37:57Z | [
"python",
"django",
"django-models",
"django-admin"
] |
Explaining persistent data structures in simple terms | 1,432,760 | <p>I'm working on a <a href="http://persistence.kenai.com/">library for Python</a> that implements some persistent data structures (mainly as a learning exercise). However, I'm beginning to learn that explaining persistent data structures to people unfamiliar with them can be difficult. Can someone help me think of an easy (or at least the least complicated) way to describe persistent data structures to them?</p>
<p>I've had a couple of people tell me that the documentation that I have is somewhat confusing.</p>
<p>(And before anyone asks, no I don't mean persistent data structures as in persisted to the file system. Google persistent data structures if you're unclear on this.)</p>
| 12 | 2009-09-16T12:50:11Z | 1,432,910 | <p>Try this:</p>
<p>Persistent data structures are data structures which, unlike arrays or lists, always preserve their original structure and contents.</p>
<p>They are effectively immutable - instead of changing such a structure, any computation will yield a new <em>copy</em> leaving the original structure unchanged. Whereas conventional data structures follow an imperative (change-based) philosophy, persistent ones are commonly used in functional programming where, in extreme cases, no change is allowed at all. The advantage of this paradigm is that persistent data are much safer, often easier to handle and even preventing bugs connected to unintended change and multithreading issues. Many problems can be formulated functionally in a much more concise way.</p>
<p>Example for a non-persistent data structure: The list (vector-list)</p>
<pre><code>list = [1, 2, 3]
# List is [1, 2, 3]
list += [4]
# Added an element at the end
list[0] = 42
# We changed the first element to 42
# List is [42, 2, 3, 4]
</code></pre>
<p>Persistence example: Linked lists (Haskell)</p>
<pre><code>list = [1, 2, 3]
# List is [1, 2, 3]
list2 = 0 : list
# List2 combines [0] and [1, 2, 3] to [0, 1, 2, 3]
# List is still [1, 2, 3]
list3 = updateAt 0 42 list
# List3 contains the elements of list2 with the first one set to 42
# List and List2 still hold their original values
</code></pre>
| 6 | 2009-09-16T13:19:13Z | [
"python",
"data-structures",
"documentation",
"functional-programming",
"persistence"
] |
Explaining persistent data structures in simple terms | 1,432,760 | <p>I'm working on a <a href="http://persistence.kenai.com/">library for Python</a> that implements some persistent data structures (mainly as a learning exercise). However, I'm beginning to learn that explaining persistent data structures to people unfamiliar with them can be difficult. Can someone help me think of an easy (or at least the least complicated) way to describe persistent data structures to them?</p>
<p>I've had a couple of people tell me that the documentation that I have is somewhat confusing.</p>
<p>(And before anyone asks, no I don't mean persistent data structures as in persisted to the file system. Google persistent data structures if you're unclear on this.)</p>
| 12 | 2009-09-16T12:50:11Z | 1,433,052 | <p>Explaining "persistent" data structures is much, much easier if you use the word the Python community uses: "immutable".</p>
<p>Everyone understands immutable numbers. <code>2+2</code> can't update 2, it has to create a new value.</p>
<p>Everyone understand mutable lists. <code>[2, 3].append(4)</code> actually updates the <code>[2,3]</code> list. The list is mutable, the individual numbers are not. See above.</p>
<p>The cool step is explaining immutable tuples. <code>(2,3).append(4)</code> can't exist because a tuple is an immutable ("persistent") data structure. In this case, neither the tuple nor the numbers are mutable.</p>
<p>Immutable strings, similarly, makes perfect sense. <code>"hello" + "there"</code> cannot update the string "hello", but can create a new string. </p>
<blockquote>
<p>Some people balk at this. Refer back to tuples and integers. It's simpler to have
strings behave like numbers than to behave like lists.</p>
</blockquote>
<p>Immutable <code>fractions</code> and <code>decimal</code> numbers are good examples of immutable ("persistent") data structures.</p>
| 6 | 2009-09-16T13:43:24Z | [
"python",
"data-structures",
"documentation",
"functional-programming",
"persistence"
] |
Explaining persistent data structures in simple terms | 1,432,760 | <p>I'm working on a <a href="http://persistence.kenai.com/">library for Python</a> that implements some persistent data structures (mainly as a learning exercise). However, I'm beginning to learn that explaining persistent data structures to people unfamiliar with them can be difficult. Can someone help me think of an easy (or at least the least complicated) way to describe persistent data structures to them?</p>
<p>I've had a couple of people tell me that the documentation that I have is somewhat confusing.</p>
<p>(And before anyone asks, no I don't mean persistent data structures as in persisted to the file system. Google persistent data structures if you're unclear on this.)</p>
| 12 | 2009-09-16T12:50:11Z | 1,433,202 | <p>Other useful concept words to describe persistent data structures are "<em>Snapshot</em>" or "<em>Version</em>", which you may precede by "virtual" because an efficient implementation of a persistent structure would not merely make multiple copies. Persistent Data Structure libraries strive to store and process the structures in efficient fashion.</p>
<p>Partial persistence allows modifications to the current structure but allows previous versions of that structure to be queried.
Full persistence allow any version of the structure to be modified and queried.
In both cases, any modification does not impact the integrity of previous versions which can still be shown/queried as they were prior to the changes.</p>
<p>I think that for the presentation page of your project, you can use much of the wording from Dario and S.Lott, trying to address the following:</p>
<ul>
<li>Brief description of what Persistent Data Structures are</li>
<li>possibly a link or two to basic introduction articles of the concept</li>
<li>Quick exit point about this project not being about data persistence (to disk and such)</li>
<li>Where this is used</li>
<li>What it can do for you</li>
<li>Brief code snippets and their output</li>
</ul>
<p>Also, do remove [from the home page] details about the data type / isinstance and all that. This is valuable info, but only of use for in a user manual or some other in-depth resource.</p>
| 1 | 2009-09-16T14:08:24Z | [
"python",
"data-structures",
"documentation",
"functional-programming",
"persistence"
] |
Explaining persistent data structures in simple terms | 1,432,760 | <p>I'm working on a <a href="http://persistence.kenai.com/">library for Python</a> that implements some persistent data structures (mainly as a learning exercise). However, I'm beginning to learn that explaining persistent data structures to people unfamiliar with them can be difficult. Can someone help me think of an easy (or at least the least complicated) way to describe persistent data structures to them?</p>
<p>I've had a couple of people tell me that the documentation that I have is somewhat confusing.</p>
<p>(And before anyone asks, no I don't mean persistent data structures as in persisted to the file system. Google persistent data structures if you're unclear on this.)</p>
| 12 | 2009-09-16T12:50:11Z | 1,448,892 | <p>The sort of phrasing I would suggest is that the value of the given structure is persistent across function calls, and that any function calls that result in a change to the structure result in a new structure being created based on copy-on-change semantics.</p>
<p>For example, given a cons type structure L defined as cons(1,cons(2, cons(3, None))), prepending the value 0 to this list results in a new list L' defined as cons(0, L), which expands to cons(0, cons(1,cons(2, cons(3, None)))). However in order to append the value 4 to this list, this requires a change to a value, which results in a copy being created which contains the change: cons(0, cons(1,cons(2, cons(3, cons(4, None)))))</p>
<p>Obviously you can have more efficient implementations that this, but this is one logical representation of what can occur. </p>
<p>Personally prefer the term immutable list, which you can say differs from an ordinary python (ordered) tuple in that it defines appending, prepending, and concatenation, since that's probably clearer to the average developer :-)</p>
| 2 | 2009-09-19T16:30:49Z | [
"python",
"data-structures",
"documentation",
"functional-programming",
"persistence"
] |
Explaining persistent data structures in simple terms | 1,432,760 | <p>I'm working on a <a href="http://persistence.kenai.com/">library for Python</a> that implements some persistent data structures (mainly as a learning exercise). However, I'm beginning to learn that explaining persistent data structures to people unfamiliar with them can be difficult. Can someone help me think of an easy (or at least the least complicated) way to describe persistent data structures to them?</p>
<p>I've had a couple of people tell me that the documentation that I have is somewhat confusing.</p>
<p>(And before anyone asks, no I don't mean persistent data structures as in persisted to the file system. Google persistent data structures if you're unclear on this.)</p>
| 12 | 2009-09-16T12:50:11Z | 1,512,210 | <p>I think the key point to make is that persistent data structures are an optimization for handling immutable values. </p>
<p>But they are an important optimization, even with fast cpu and big memory.</p>
<p>For example, Java strings are immutable but they do NOT have a persistent data structure behind the scenes. That means you have to use things like StringBuilder. If they had a persistent data structure then you could just concatenate and not worry about it.</p>
<p>Immutability is becoming important because it helps deal with concurrency. But to make immutability efficient requires persistent data structures.</p>
<p>Clojure has some good explanations of persistent data structures.</p>
| 1 | 2009-10-02T23:01:02Z | [
"python",
"data-structures",
"documentation",
"functional-programming",
"persistence"
] |
Explaining persistent data structures in simple terms | 1,432,760 | <p>I'm working on a <a href="http://persistence.kenai.com/">library for Python</a> that implements some persistent data structures (mainly as a learning exercise). However, I'm beginning to learn that explaining persistent data structures to people unfamiliar with them can be difficult. Can someone help me think of an easy (or at least the least complicated) way to describe persistent data structures to them?</p>
<p>I've had a couple of people tell me that the documentation that I have is somewhat confusing.</p>
<p>(And before anyone asks, no I don't mean persistent data structures as in persisted to the file system. Google persistent data structures if you're unclear on this.)</p>
| 12 | 2009-09-16T12:50:11Z | 2,883,662 | <p>When you alter a mutable data structure (e.g. insert into a hash table) it changes in-place and the previous version is lost. When you alter a persistent data structure (e.g. insert into a <code>Map</code>) you get a new data structure and the previous version remains valid.</p>
| 0 | 2010-05-21T16:08:04Z | [
"python",
"data-structures",
"documentation",
"functional-programming",
"persistence"
] |
python: Change the scripts working directory to the script's own directory | 1,432,924 | <p>I run a python shell from crontab every minute:</p>
<pre><code>* * * * * /home/udi/foo/bar.py
</code></pre>
<p><code>/home/udi/foo</code> has some necessary subdirectories, like <code>/home/udi/foo/log</code> and <code>/home/udi/foo/config</code>, which <code>/home/udi/foo/bar.py</code> refers to.</p>
<p>The problem is that <code>crontab</code> runs the script from a different working directory, so trying to open <code>./log/bar.log</code> fails.</p>
<p>Is there a nice way to tell the script to change the working directory to the script's own directory? I would fancy a solution that would work for any script location, rather than explicitly telling the script where it is.</p>
<p><strong>EDIT:</strong></p>
<pre><code>os.chdir(os.path.dirname(sys.argv[0]))
</code></pre>
<p>Was the most compact elegant solution. Thanks for your answers and explanations!</p>
| 85 | 2009-09-16T13:21:51Z | 1,432,949 | <p>This will change your current working directory to so that opening relative paths will work:</p>
<pre><code>import os
os.chdir("/home/udi/foo")
</code></pre>
<p>However, you asked how to change into whatever directory your Python script is located, even if you don't know what directory that will be when you're writing your script. To do this, you can use the <code>os.path</code> functions:</p>
<pre><code>import os
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
</code></pre>
<p>This takes the filename of your script, converts it to an absolute path, then extracts the directory of that path, then changes into that directory.</p>
| 100 | 2009-09-16T13:26:24Z | [
"python",
"working-directory"
] |
python: Change the scripts working directory to the script's own directory | 1,432,924 | <p>I run a python shell from crontab every minute:</p>
<pre><code>* * * * * /home/udi/foo/bar.py
</code></pre>
<p><code>/home/udi/foo</code> has some necessary subdirectories, like <code>/home/udi/foo/log</code> and <code>/home/udi/foo/config</code>, which <code>/home/udi/foo/bar.py</code> refers to.</p>
<p>The problem is that <code>crontab</code> runs the script from a different working directory, so trying to open <code>./log/bar.log</code> fails.</p>
<p>Is there a nice way to tell the script to change the working directory to the script's own directory? I would fancy a solution that would work for any script location, rather than explicitly telling the script where it is.</p>
<p><strong>EDIT:</strong></p>
<pre><code>os.chdir(os.path.dirname(sys.argv[0]))
</code></pre>
<p>Was the most compact elegant solution. Thanks for your answers and explanations!</p>
| 85 | 2009-09-16T13:21:51Z | 1,433,009 | <p>Don't do this.</p>
<p>Your scripts and your data should not be mashed into one big directory. Put your code in some known location (<code>site-packages</code> or <code>/var/opt/udi</code> or something) separate from your data. Use good version control on your code to be sure that you have current and previous versions separated from each other so you can fall back to previous versions and test future versions.</p>
<p>Bottom line: Do not mingle code and data.</p>
<p>Data is precious. Code comes and goes.</p>
<p>Provide the working directory as a command-line argument value. You can provide a default as an environment variable. Don't deduce it (or guess at it)</p>
<p>Make it a required argument value and do this.</p>
<pre><code>import sys
import os
working= os.environ.get("WORKING_DIRECTORY","/some/default")
if len(sys.argv) > 1: working = sys.argv[1]
os.chdir( working )
</code></pre>
<p>Do not "assume" a directory based on the location of your software. It will not work out well in the long run.</p>
| 14 | 2009-09-16T13:34:21Z | [
"python",
"working-directory"
] |
python: Change the scripts working directory to the script's own directory | 1,432,924 | <p>I run a python shell from crontab every minute:</p>
<pre><code>* * * * * /home/udi/foo/bar.py
</code></pre>
<p><code>/home/udi/foo</code> has some necessary subdirectories, like <code>/home/udi/foo/log</code> and <code>/home/udi/foo/config</code>, which <code>/home/udi/foo/bar.py</code> refers to.</p>
<p>The problem is that <code>crontab</code> runs the script from a different working directory, so trying to open <code>./log/bar.log</code> fails.</p>
<p>Is there a nice way to tell the script to change the working directory to the script's own directory? I would fancy a solution that would work for any script location, rather than explicitly telling the script where it is.</p>
<p><strong>EDIT:</strong></p>
<pre><code>os.chdir(os.path.dirname(sys.argv[0]))
</code></pre>
<p>Was the most compact elegant solution. Thanks for your answers and explanations!</p>
| 85 | 2009-09-16T13:21:51Z | 9,130,405 | <p>You can get a shorter version by using <code>sys.path[0]</code>.</p>
<pre><code>os.chdir(sys.path[0])
</code></pre>
<p>From <a href="http://docs.python.org/library/sys.html#sys.path">http://docs.python.org/library/sys.html#sys.path</a></p>
<blockquote>
<p>As initialized upon program startup, the first item of this list,
<code>path[0]</code>, is the directory containing the script that was used to
invoke the Python interpreter</p>
</blockquote>
| 16 | 2012-02-03T14:41:28Z | [
"python",
"working-directory"
] |
python: Change the scripts working directory to the script's own directory | 1,432,924 | <p>I run a python shell from crontab every minute:</p>
<pre><code>* * * * * /home/udi/foo/bar.py
</code></pre>
<p><code>/home/udi/foo</code> has some necessary subdirectories, like <code>/home/udi/foo/log</code> and <code>/home/udi/foo/config</code>, which <code>/home/udi/foo/bar.py</code> refers to.</p>
<p>The problem is that <code>crontab</code> runs the script from a different working directory, so trying to open <code>./log/bar.log</code> fails.</p>
<p>Is there a nice way to tell the script to change the working directory to the script's own directory? I would fancy a solution that would work for any script location, rather than explicitly telling the script where it is.</p>
<p><strong>EDIT:</strong></p>
<pre><code>os.chdir(os.path.dirname(sys.argv[0]))
</code></pre>
<p>Was the most compact elegant solution. Thanks for your answers and explanations!</p>
| 85 | 2009-09-16T13:21:51Z | 14,628,314 | <p>Change your crontab command to</p>
<pre><code>* * * * * (cd /home/udi/foo/ || exit 1; ./bar.py)
</code></pre>
<p>The <code>(...)</code> starts a sub-shell that your crond executes as a single command. The <code>|| exit 1</code> causes your cronjob to fail in case that the directory is unavailable.</p>
<p>Though the other solutions may be more elegant in the long run for your specific scripts, my example could still be useful in cases where you can't modify the program or command that you want to execute.</p>
| 9 | 2013-01-31T14:37:45Z | [
"python",
"working-directory"
] |
Generate and parse Python code from C# application | 1,432,998 | <p>I need to generate Python code to be more specific <a href="http://ironpython.codeplex.com/">IronPyton</a>. I also need to be able to parse the code and load it into <a href="http://en.wikipedia.org/wiki/Abstract%5Fsyntax%5Ftree">AST</a>. I just started looking at some tools. I played with <a href="http://msdn.microsoft.com/en-us/oslo/default.aspx">"Oslo"</a> and made decision that it's not the right tool for me. I just looked very briefly at <a href="http://www.ssw.uni-linz.ac.at/Research/Projects/Coco/">Coco/R</a> and it looks promising.</p>
<p>Does any one used Coco/R?<br />
If you did what's your experience with the tool?
Can you recommend some other tool?</p>
| 5 | 2009-09-16T13:33:10Z | 1,433,184 | <p>I think you should look at the <a href="http://msdn.microsoft.com/en-us/magazine/cc163344.aspx" rel="nofollow">Dynamic Language Runtime</a>. This will be a standard part of some later version of .Net and C# (.Net 4 from memory).</p>
<p>I've used it to compile and execute Python code generated at runtime, but I haven't played with all the AST stuff yet.</p>
| 0 | 2009-09-16T14:04:35Z | [
"c#",
"python",
"code-generation",
"ironpython",
"cocor"
] |
Generate and parse Python code from C# application | 1,432,998 | <p>I need to generate Python code to be more specific <a href="http://ironpython.codeplex.com/">IronPyton</a>. I also need to be able to parse the code and load it into <a href="http://en.wikipedia.org/wiki/Abstract%5Fsyntax%5Ftree">AST</a>. I just started looking at some tools. I played with <a href="http://msdn.microsoft.com/en-us/oslo/default.aspx">"Oslo"</a> and made decision that it's not the right tool for me. I just looked very briefly at <a href="http://www.ssw.uni-linz.ac.at/Research/Projects/Coco/">Coco/R</a> and it looks promising.</p>
<p>Does any one used Coco/R?<br />
If you did what's your experience with the tool?
Can you recommend some other tool?</p>
| 5 | 2009-09-16T13:33:10Z | 1,433,330 | <p>The <a href="http://ironpython.codeplex.com/">IronPython</a> implementation itself includes <a href="http://ironpython.codeplex.com/SourceControl/changeset/view/59195#992853">a parser</a> and <a href="http://ironpython.codeplex.com/SourceControl/changeset/view/59195#992331">an AST representation</a> of Python programs which can be walked with a <a href="http://ironpython.codeplex.com/SourceControl/changeset/view/59195#992880"><code>PythonWalker</code></a>.</p>
| 7 | 2009-09-16T14:29:00Z | [
"c#",
"python",
"code-generation",
"ironpython",
"cocor"
] |
Generate and parse Python code from C# application | 1,432,998 | <p>I need to generate Python code to be more specific <a href="http://ironpython.codeplex.com/">IronPyton</a>. I also need to be able to parse the code and load it into <a href="http://en.wikipedia.org/wiki/Abstract%5Fsyntax%5Ftree">AST</a>. I just started looking at some tools. I played with <a href="http://msdn.microsoft.com/en-us/oslo/default.aspx">"Oslo"</a> and made decision that it's not the right tool for me. I just looked very briefly at <a href="http://www.ssw.uni-linz.ac.at/Research/Projects/Coco/">Coco/R</a> and it looks promising.</p>
<p>Does any one used Coco/R?<br />
If you did what's your experience with the tool?
Can you recommend some other tool?</p>
| 5 | 2009-09-16T13:33:10Z | 1,433,475 | <p>Not really my area of expertise but you might want to try <a href="http://www.antlr.org/" rel="nofollow">ANTLR</a>. It has support for generating <a href="http://www.antlr.org/wiki/display/ANTLR3/Antlr3PythonTarget" rel="nofollow">Python</a>.</p>
| 1 | 2009-09-16T14:48:13Z | [
"c#",
"python",
"code-generation",
"ironpython",
"cocor"
] |
How do I run a sub-process, display its output in a GUI and allow it to be terminated? | 1,433,367 | <p>I have been trying to write an application that runs subprocesses and (among other things) displays their output in a GUI and allows the user to click a button to cancel them. I start the processes like this:</p>
<pre><code>queue = Queue.Queue(500)
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
iothread = threading.Thread(
target=simple_io_thread,
args=(process.stdout, queue))
iothread.daemon=True
iothread.start()
</code></pre>
<p>where simple_io_thread is defined as follows:</p>
<pre><code>def simple_io_thread(pipe, queue):
while True:
line = pipe.readline()
queue.put(line, block=True)
if line=="":
break
</code></pre>
<p>This works well enough. In my UI I periodically do non-blocking "get"s from the queue. However, my problems come when I want to terminate the subprocess. (The subprocess is an arbitrary process, not something I wrote myself.) I can use the terminate method to terminate the process, but I do not know how to guarantee that my I/O thread will terminate. It will normally be doing blocking I/O on the pipe. This may or may not end some time after I terminate the process. (If the subprocess has spawned <em>another</em> subprocess, I can kill the first subprocess, but the second one will still keep the pipe open. I'm not even sure how to get such grand-children to terminate cleanly.) After that the I/O thread will try to enqueue the output, but I don't want to commit to reading from the queue indefinitely.</p>
<p>Ideally I would like some way to request termination of the subprocess, block for a short (<0.5s) amount of time and after that be guaranteed that the I/O thread has exited (or will exit in a timely fashion without interfering with anything else) and that I can stop reading from the queue.</p>
<p>It's not critical to me that a solution uses an I/O thread. If there's another way to do this that works on Windows and Linux with Python 2.6 and a Tkinter GUI that would be fine.</p>
<p><hr></p>
<p>EDIT - Will's answer and other things I've seen on the web about doing this in other languages suggest that the operating system expects you just to close the file handle on the main thread and then the I/O thread should come out of its blocking read. However, as I described in the comment, that doesn't seem to work for me. If I do this on the main thread:</p>
<pre><code>process.stdout.close()
</code></pre>
<p>I get:</p>
<pre><code>IOError: close() called during concurrent operation on the same file object.
</code></pre>
<p>...on the main thread. If I do this on the main thread:</p>
<pre><code>os.close(process.stdout.fileno())
</code></pre>
<p>I get:</p>
<pre><code>close failed in file object destructor: IOError: [Errno 9] Bad file descriptor
</code></pre>
<p>...later on in the main thread when it tries to close the file handle itself.</p>
| 2 | 2009-09-16T14:35:14Z | 1,433,495 | <p>In the code that terminates the process, you could also explicitly <code>os.close()</code> the pipe that your thread is reading from?</p>
| 1 | 2009-09-16T14:50:13Z | [
"python"
] |
How do I run a sub-process, display its output in a GUI and allow it to be terminated? | 1,433,367 | <p>I have been trying to write an application that runs subprocesses and (among other things) displays their output in a GUI and allows the user to click a button to cancel them. I start the processes like this:</p>
<pre><code>queue = Queue.Queue(500)
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
iothread = threading.Thread(
target=simple_io_thread,
args=(process.stdout, queue))
iothread.daemon=True
iothread.start()
</code></pre>
<p>where simple_io_thread is defined as follows:</p>
<pre><code>def simple_io_thread(pipe, queue):
while True:
line = pipe.readline()
queue.put(line, block=True)
if line=="":
break
</code></pre>
<p>This works well enough. In my UI I periodically do non-blocking "get"s from the queue. However, my problems come when I want to terminate the subprocess. (The subprocess is an arbitrary process, not something I wrote myself.) I can use the terminate method to terminate the process, but I do not know how to guarantee that my I/O thread will terminate. It will normally be doing blocking I/O on the pipe. This may or may not end some time after I terminate the process. (If the subprocess has spawned <em>another</em> subprocess, I can kill the first subprocess, but the second one will still keep the pipe open. I'm not even sure how to get such grand-children to terminate cleanly.) After that the I/O thread will try to enqueue the output, but I don't want to commit to reading from the queue indefinitely.</p>
<p>Ideally I would like some way to request termination of the subprocess, block for a short (<0.5s) amount of time and after that be guaranteed that the I/O thread has exited (or will exit in a timely fashion without interfering with anything else) and that I can stop reading from the queue.</p>
<p>It's not critical to me that a solution uses an I/O thread. If there's another way to do this that works on Windows and Linux with Python 2.6 and a Tkinter GUI that would be fine.</p>
<p><hr></p>
<p>EDIT - Will's answer and other things I've seen on the web about doing this in other languages suggest that the operating system expects you just to close the file handle on the main thread and then the I/O thread should come out of its blocking read. However, as I described in the comment, that doesn't seem to work for me. If I do this on the main thread:</p>
<pre><code>process.stdout.close()
</code></pre>
<p>I get:</p>
<pre><code>IOError: close() called during concurrent operation on the same file object.
</code></pre>
<p>...on the main thread. If I do this on the main thread:</p>
<pre><code>os.close(process.stdout.fileno())
</code></pre>
<p>I get:</p>
<pre><code>close failed in file object destructor: IOError: [Errno 9] Bad file descriptor
</code></pre>
<p>...later on in the main thread when it tries to close the file handle itself.</p>
| 2 | 2009-09-16T14:35:14Z | 5,942,234 | <p>I know this is an old post, but in case it still helps anyone, I think your problem could be solved by passing the subprocess.Popen instance to io_thread, rather than it's output stream.
If you do that, then you can replace your <code>while True:</code> line with <code>while process.poll() == None:</code>. </p>
<p><a href="http://docs.python.org/library/subprocess.html#subprocess.Popen.poll" rel="nofollow">process.poll()</a> checks for the subprocess return code; if the process hasn't finished, then there isn't one (i.e. <code>process.poll() == None</code>). You can then do away with <code>if line == "": break</code>.</p>
<p>The reason I'm here is because I wrote a very similar script to this today, and I got those:-<br />
<code>IOError: close() called during concurrent operation on the same file object.</code> errors. <br /><br />
Again, in case it helps, I <strong>think</strong> my problems stem from (my) io_thread doing some overly efficient garbage collection, and closes a file handle I give it (I'm probably wrong, but it works now..) Mine's different tho in that it's not daemonic, and it iterates through subprocess.stdout, rather than using a while loop.. i.e.:-<br /></p>
<pre><code>def io_thread(subprocess,logfile,lock):
for line in subprocess.stdout:
lock.acquire()
print line,
lock.release()
logfile.write( line )
</code></pre>
<p>I should also probably mention that I pass the bufsize argument to subprocess.Popen, so that it's line buffered.</p>
| 2 | 2011-05-09T20:39:28Z | [
"python"
] |
How do I run a sub-process, display its output in a GUI and allow it to be terminated? | 1,433,367 | <p>I have been trying to write an application that runs subprocesses and (among other things) displays their output in a GUI and allows the user to click a button to cancel them. I start the processes like this:</p>
<pre><code>queue = Queue.Queue(500)
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
iothread = threading.Thread(
target=simple_io_thread,
args=(process.stdout, queue))
iothread.daemon=True
iothread.start()
</code></pre>
<p>where simple_io_thread is defined as follows:</p>
<pre><code>def simple_io_thread(pipe, queue):
while True:
line = pipe.readline()
queue.put(line, block=True)
if line=="":
break
</code></pre>
<p>This works well enough. In my UI I periodically do non-blocking "get"s from the queue. However, my problems come when I want to terminate the subprocess. (The subprocess is an arbitrary process, not something I wrote myself.) I can use the terminate method to terminate the process, but I do not know how to guarantee that my I/O thread will terminate. It will normally be doing blocking I/O on the pipe. This may or may not end some time after I terminate the process. (If the subprocess has spawned <em>another</em> subprocess, I can kill the first subprocess, but the second one will still keep the pipe open. I'm not even sure how to get such grand-children to terminate cleanly.) After that the I/O thread will try to enqueue the output, but I don't want to commit to reading from the queue indefinitely.</p>
<p>Ideally I would like some way to request termination of the subprocess, block for a short (<0.5s) amount of time and after that be guaranteed that the I/O thread has exited (or will exit in a timely fashion without interfering with anything else) and that I can stop reading from the queue.</p>
<p>It's not critical to me that a solution uses an I/O thread. If there's another way to do this that works on Windows and Linux with Python 2.6 and a Tkinter GUI that would be fine.</p>
<p><hr></p>
<p>EDIT - Will's answer and other things I've seen on the web about doing this in other languages suggest that the operating system expects you just to close the file handle on the main thread and then the I/O thread should come out of its blocking read. However, as I described in the comment, that doesn't seem to work for me. If I do this on the main thread:</p>
<pre><code>process.stdout.close()
</code></pre>
<p>I get:</p>
<pre><code>IOError: close() called during concurrent operation on the same file object.
</code></pre>
<p>...on the main thread. If I do this on the main thread:</p>
<pre><code>os.close(process.stdout.fileno())
</code></pre>
<p>I get:</p>
<pre><code>close failed in file object destructor: IOError: [Errno 9] Bad file descriptor
</code></pre>
<p>...later on in the main thread when it tries to close the file handle itself.</p>
| 2 | 2009-09-16T14:35:14Z | 20,977,023 | <p>This is probably old enough, but still usefull to someone coming from search engine...</p>
<p>The reason that it shows that message is that after the subprocess has been completed it closes the file descriptors, therefore, the daemon thread (which is running concurrently) will try to use those closed descriptors raising the error.</p>
<p>By joining the thread before the subprocess wait() or communicate() methods should be more than enough to suppress the error.</p>
<pre><code>my_thread.join()
print my_thread.is_alive()
my_popen.communicate()
</code></pre>
| 2 | 2014-01-07T16:39:25Z | [
"python"
] |
Can we use a python variable to hold an entire file? | 1,433,577 | <p>Provided that we know that all the file will be loaded in memory and we can afford it,
what are the drawbacks (if any) or limitations (if any) of loading an entire file (possibly a binary file) in a python variable. If this is technically possible, should this be avoided, and why ?</p>
<p>Regarding file size concerns, to what maximum size this solution should be limited ?. And why ?</p>
<p>The actual loading code could be the one proposed in <a href="http://stackoverflow.com/questions/1432126/how-to-get-content-of-a-small-ascii-file-in-python">this stackoverflow entry</a>.</p>
<p>Sample code is:</p>
<pre><code>def file_get_contents(filename):
with open(filename) as f:
return f.read()
content = file_get_contents('/bin/kill')
... code manipulating 'content' ...
</code></pre>
<p>[EDIT]
Code manipulation that comes to mind (but is maybe not applicable) is standard list/strings operators (square brackets, '+' signs) or some string operators ('len', 'in' operator, 'count', 'endswith'/'startswith', 'split', 'translation' ...).</p>
| 6 | 2009-09-16T15:03:20Z | 1,433,601 | <ul>
<li>Yes, you can</li>
<li>The only drawback is memory usage, and possible also speed if the file is big.</li>
<li>File size should be limited to how much space you have in memory.</li>
</ul>
<p>In general, there are better ways to do it, but for one-off scripts where you know memory is not an issue, sure.</p>
| 11 | 2009-09-16T15:08:40Z | [
"python",
"file",
"variables"
] |
Can we use a python variable to hold an entire file? | 1,433,577 | <p>Provided that we know that all the file will be loaded in memory and we can afford it,
what are the drawbacks (if any) or limitations (if any) of loading an entire file (possibly a binary file) in a python variable. If this is technically possible, should this be avoided, and why ?</p>
<p>Regarding file size concerns, to what maximum size this solution should be limited ?. And why ?</p>
<p>The actual loading code could be the one proposed in <a href="http://stackoverflow.com/questions/1432126/how-to-get-content-of-a-small-ascii-file-in-python">this stackoverflow entry</a>.</p>
<p>Sample code is:</p>
<pre><code>def file_get_contents(filename):
with open(filename) as f:
return f.read()
content = file_get_contents('/bin/kill')
... code manipulating 'content' ...
</code></pre>
<p>[EDIT]
Code manipulation that comes to mind (but is maybe not applicable) is standard list/strings operators (square brackets, '+' signs) or some string operators ('len', 'in' operator, 'count', 'endswith'/'startswith', 'split', 'translation' ...).</p>
| 6 | 2009-09-16T15:03:20Z | 1,433,619 | <p>The sole issue you can run into is memory consumption: Strings in Python are immutable. So when you need to change a byte, you need to copy the old string:</p>
<pre><code>new = old[0:pos] + newByte + old[pos+1:]
</code></pre>
<p>This needs up to three times the memory of <code>old</code>.</p>
<p>Instead of a string, you can use an <a href="http://docs.python.org/library/array.html" rel="nofollow">array</a>. These offer much better performance if you need to modify the contents and you can create them easily from a string.</p>
| 3 | 2009-09-16T15:10:40Z | [
"python",
"file",
"variables"
] |
Can we use a python variable to hold an entire file? | 1,433,577 | <p>Provided that we know that all the file will be loaded in memory and we can afford it,
what are the drawbacks (if any) or limitations (if any) of loading an entire file (possibly a binary file) in a python variable. If this is technically possible, should this be avoided, and why ?</p>
<p>Regarding file size concerns, to what maximum size this solution should be limited ?. And why ?</p>
<p>The actual loading code could be the one proposed in <a href="http://stackoverflow.com/questions/1432126/how-to-get-content-of-a-small-ascii-file-in-python">this stackoverflow entry</a>.</p>
<p>Sample code is:</p>
<pre><code>def file_get_contents(filename):
with open(filename) as f:
return f.read()
content = file_get_contents('/bin/kill')
... code manipulating 'content' ...
</code></pre>
<p>[EDIT]
Code manipulation that comes to mind (but is maybe not applicable) is standard list/strings operators (square brackets, '+' signs) or some string operators ('len', 'in' operator, 'count', 'endswith'/'startswith', 'split', 'translation' ...).</p>
| 6 | 2009-09-16T15:03:20Z | 1,433,621 | <pre><code>with open(filename) as f:
</code></pre>
<p>This only works on Python 2.x on Unix. It won't do what you expect on Python 3.x or on Windows, as these both draw a strong distinction between text and binary files. It's better to specify that the file is binary, like this:</p>
<pre><code>with open(filename, 'rb') as f:
</code></pre>
<p>This will turn off the OS's CR/LF conversion on Windows, and will force Python 3.x to return a byte array rather than Unicode characters.</p>
<p>As for the rest of your question, I agree with Lennart Regebro's (unedited) answer.</p>
| 4 | 2009-09-16T15:10:58Z | [
"python",
"file",
"variables"
] |
Can we use a python variable to hold an entire file? | 1,433,577 | <p>Provided that we know that all the file will be loaded in memory and we can afford it,
what are the drawbacks (if any) or limitations (if any) of loading an entire file (possibly a binary file) in a python variable. If this is technically possible, should this be avoided, and why ?</p>
<p>Regarding file size concerns, to what maximum size this solution should be limited ?. And why ?</p>
<p>The actual loading code could be the one proposed in <a href="http://stackoverflow.com/questions/1432126/how-to-get-content-of-a-small-ascii-file-in-python">this stackoverflow entry</a>.</p>
<p>Sample code is:</p>
<pre><code>def file_get_contents(filename):
with open(filename) as f:
return f.read()
content = file_get_contents('/bin/kill')
... code manipulating 'content' ...
</code></pre>
<p>[EDIT]
Code manipulation that comes to mind (but is maybe not applicable) is standard list/strings operators (square brackets, '+' signs) or some string operators ('len', 'in' operator, 'count', 'endswith'/'startswith', 'split', 'translation' ...).</p>
| 6 | 2009-09-16T15:03:20Z | 1,433,650 | <p>Yes you can -provided the file is small enough-.</p>
<p>It is even very pythonic to further convert the return from read() to any container/iterable type as with say, string.split(), along with associated functional programming features to continue treating the file "at once".</p>
| 0 | 2009-09-16T15:17:30Z | [
"python",
"file",
"variables"
] |
Can we use a python variable to hold an entire file? | 1,433,577 | <p>Provided that we know that all the file will be loaded in memory and we can afford it,
what are the drawbacks (if any) or limitations (if any) of loading an entire file (possibly a binary file) in a python variable. If this is technically possible, should this be avoided, and why ?</p>
<p>Regarding file size concerns, to what maximum size this solution should be limited ?. And why ?</p>
<p>The actual loading code could be the one proposed in <a href="http://stackoverflow.com/questions/1432126/how-to-get-content-of-a-small-ascii-file-in-python">this stackoverflow entry</a>.</p>
<p>Sample code is:</p>
<pre><code>def file_get_contents(filename):
with open(filename) as f:
return f.read()
content = file_get_contents('/bin/kill')
... code manipulating 'content' ...
</code></pre>
<p>[EDIT]
Code manipulation that comes to mind (but is maybe not applicable) is standard list/strings operators (square brackets, '+' signs) or some string operators ('len', 'in' operator, 'count', 'endswith'/'startswith', 'split', 'translation' ...).</p>
| 6 | 2009-09-16T15:03:20Z | 1,436,408 | <p>While you've gotten good responses, it seems nobody has answered this part of your question (as often happens when you ask many questions in a question;-)...:</p>
<blockquote>
<p>Regarding file size concerns, to what
maximum size this solution should be
limited ?. And why ?</p>
</blockquote>
<p>The most important thing is, how much physical RAM can this specific Python process actually <strong>use</strong> (what's known as a "working set"), without unduly penalizing other aspects of the overall system's performance. If you exceed physical RAM for your "working set", you'll be paginating and swapping in and out to disk, and your performance can rapidly degrade (up to a state known as "thrashing" were basically all available cycles are going to the tasks of getting pages in and out, and negligible amounts of actual work can actually get done).</p>
<p>Out of that total, a reasonably modest amount (say a few MB at most, in general) are probably going to be taken up by executable code (Python's own executable files, DLLs or .so's) and bytecode and general support datastructures that are actively needed in memory; on a typical modern machine that's not doing other important or urgent tasks, you can almost ignore this overhead compared to the gigabytes of RAM that you have available overall (though the situation might be different on embedded systems, etc).</p>
<p>All the rest is available for your data -- which includes this file you're reading into memory, as well as any other significant data structures. "Modifications" of the file's data can typically take (transiently) twice as much memory as the file's contents' size (if you're holding it in a string) -- more, of course, if you're keeping a copy of the old data as well as making new modified copies/versions.</p>
<p>So for "read-only" use on a typical modern 32-bit machine with, say, 2GB of RAM overall, reading into memory (say) 1.5 GB should be no problem; but it will have to be substantially less than 1 GB if you're doing "modifications" (and even less if you have other significant data structures in memory!). Of course, on a dedicated server with a 64-bit build of Python, a 64-bit OS, and 16 GB of RAM, the practical limits before very different -- roughly in proportion to the vastly different amount of available RAM in fact.</p>
<p>For example, the King James' Bible text as downloadable <a href="http://www.gutenberg.org/dirs/etext90/kjv10.zip">here</a> (unzipped) is about 4.4 MB; so, in a machine with 2 GB of RAM, you could keep about 400 slightly modified copies of it in memory (if nothing else is requesting memory), but, in a machine with 16 (available and addressable) GB of RAM, you could keep well over 3000 such copies.</p>
| 6 | 2009-09-17T02:14:58Z | [
"python",
"file",
"variables"
] |
Can we use a python variable to hold an entire file? | 1,433,577 | <p>Provided that we know that all the file will be loaded in memory and we can afford it,
what are the drawbacks (if any) or limitations (if any) of loading an entire file (possibly a binary file) in a python variable. If this is technically possible, should this be avoided, and why ?</p>
<p>Regarding file size concerns, to what maximum size this solution should be limited ?. And why ?</p>
<p>The actual loading code could be the one proposed in <a href="http://stackoverflow.com/questions/1432126/how-to-get-content-of-a-small-ascii-file-in-python">this stackoverflow entry</a>.</p>
<p>Sample code is:</p>
<pre><code>def file_get_contents(filename):
with open(filename) as f:
return f.read()
content = file_get_contents('/bin/kill')
... code manipulating 'content' ...
</code></pre>
<p>[EDIT]
Code manipulation that comes to mind (but is maybe not applicable) is standard list/strings operators (square brackets, '+' signs) or some string operators ('len', 'in' operator, 'count', 'endswith'/'startswith', 'split', 'translation' ...).</p>
| 6 | 2009-09-16T15:03:20Z | 10,930,086 | <p>You can also use Python's v3 feature:</p>
<pre><code>>>> ''.join(open('htdocs/config.php', 'r').readlines())
"This is the first line of the file.\nSecond line of the file"
</code></pre>
<p>Read more here <a href="http://docs.python.org/py3k/tutorial/inputoutput.html" rel="nofollow">http://docs.python.org/py3k/tutorial/inputoutput.html</a></p>
| 1 | 2012-06-07T10:33:53Z | [
"python",
"file",
"variables"
] |
Getting text values from XML in Python | 1,433,907 | <pre><code>from xml.dom.minidom import parseString
dom = parseString(data)
data = dom.getElementsByTagName('data')
</code></pre>
<p>the 'data' variable returns as an element object but I cant for the life of me see in the documentation to grab the text value of the element.</p>
<p>For example:</p>
<pre><code><something><data>I WANT THIS</data></something>
</code></pre>
<p>Anyone have any ideas?</p>
| 4 | 2009-09-16T16:02:07Z | 1,433,946 | <p>This should do the trick:</p>
<pre><code>dom = parseString('<something><data>I WANT THIS</data></something>')
data = dom.getElementsByTagName('data')[0].childNodes[0].data
</code></pre>
<p>i.e. you need to wade deeper into the DOM structure to get at the text child node and then access its value. </p>
| 3 | 2009-09-16T16:09:13Z | [
"python",
"xml",
"parsing"
] |
Getting text values from XML in Python | 1,433,907 | <pre><code>from xml.dom.minidom import parseString
dom = parseString(data)
data = dom.getElementsByTagName('data')
</code></pre>
<p>the 'data' variable returns as an element object but I cant for the life of me see in the documentation to grab the text value of the element.</p>
<p>For example:</p>
<pre><code><something><data>I WANT THIS</data></something>
</code></pre>
<p>Anyone have any ideas?</p>
| 4 | 2009-09-16T16:02:07Z | 1,433,958 | <p>So the way to look at it is that "I WANT THIS" is actually another node. It's a text child of "data".</p>
<pre><code>from xml.dom.minidom import parseString
dom = parseString(data)
nodes = dom.getElementsByTagName('data')
</code></pre>
<p>At this point, "nodes" is a NodeList and in your example, it has one item in it which is the "data" element. Correspondingly the "data" element also only has one child which is a text node "I WANT THIS".</p>
<p>So you could just do something like this:</p>
<pre><code>print nodes[0].firstChild.nodeValue
</code></pre>
<p>Note that in the case where you have more than one tag called "data" in your input, you should use some sort of iteration technique on "nodes" rather than index it directly.</p>
| 4 | 2009-09-16T16:10:41Z | [
"python",
"xml",
"parsing"
] |
Compiling Python | 1,434,144 | <p>How can I compile and run a python file (*.py extension)?</p>
| 41 | 2009-09-16T16:42:51Z | 1,434,155 | <p><code>python yourfile.py</code></p>
<p>You have to have python installed first. It will automatically compile your file into a .pyc binary, and then run it for you. It will automatically recompile any time your file changes.</p>
<p><a href="http://www.python.org/download/">http://www.python.org/download/</a></p>
| 25 | 2009-09-16T16:44:03Z | [
"python",
"compiler-construction"
] |
Compiling Python | 1,434,144 | <p>How can I compile and run a python file (*.py extension)?</p>
| 41 | 2009-09-16T16:42:51Z | 1,434,170 | <p>Python compiles its files to bytecode before executing them. That means you have to have a Python interpreter installed on the target machine.</p>
<p>If you don't want to install Python on the target machine use <a href="http://www.py2exe.org/">py2exe</a>, <a href="http://svn.pythonmac.org/py2app/py2app/trunk/doc/index.html">py2app</a> or something similar.</p>
| 15 | 2009-09-16T16:48:05Z | [
"python",
"compiler-construction"
] |
Compiling Python | 1,434,144 | <p>How can I compile and run a python file (*.py extension)?</p>
| 41 | 2009-09-16T16:42:51Z | 1,434,199 | <p>To add to <a href="http://stackoverflow.com/questions/1434144/pyhton-programming/1434155#1434155">Paul McMillan's answer</a>, if you are on Windows and you have Python installed, then any files ending with the extension ".py" should be associated with the <code>python</code> executable, allowing you to run it like so:</p>
<pre><code>> myfile.py
</code></pre>
<p>In *nix, you can begin the file with <code>#!/usr/bin/python</code> and run it like so:</p>
<pre><code>$ ./myfile.py
</code></pre>
<p>In *nix systems, if the first two characters of a file are <code>#!</code> then it will execute the file with the specified executable, which I set here to be <code>/usr/bin/python</code>.</p>
| 5 | 2009-09-16T16:54:17Z | [
"python",
"compiler-construction"
] |
Compiling Python | 1,434,144 | <p>How can I compile and run a python file (*.py extension)?</p>
| 41 | 2009-09-16T16:42:51Z | 1,434,239 | <p>On most Unix-like systems, you can use the shebang to tell the operating system which interpreter should be called. You simply put</p>
<pre><code>#!/path/to/python
</code></pre>
<p>in the first line of your file, where of course you have to replace "/path/to/" with the path you have on your system. In most cases this would be "/usr/bin/python" or "/usr/local/bin/python". On unix systems you could also look for the path with </p>
<pre><code>"#!usr/bin/env python"
</code></pre>
<p>or invoke the command</p>
<pre><code>which python
</code></pre>
<p>to find the path.
You can then run your program with the command</p>
<pre><code>./yourprogram.py
</code></pre>
<p>If it tells you that you do not have permission to do so, you have to use the command</p>
<pre><code>chmod a+x yourprogram.py
</code></pre>
| 1 | 2009-09-16T17:01:44Z | [
"python",
"compiler-construction"
] |
Compiling Python | 1,434,144 | <p>How can I compile and run a python file (*.py extension)?</p>
| 41 | 2009-09-16T16:42:51Z | 1,434,277 | <p>If you want to transform a python source file into a double-clickable <code>.exe</code> on windows, you can use <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a>, which can help you build an easy to distribute package.</p>
| 3 | 2009-09-16T17:09:32Z | [
"python",
"compiler-construction"
] |
Compiling Python | 1,434,144 | <p>How can I compile and run a python file (*.py extension)?</p>
| 41 | 2009-09-16T16:42:51Z | 1,434,486 | <p>Python is an interpreted language, so you don't need to compile it; just to run it. As it happens, the standard version of python will compile this to "bytecode", just like Java etc. does, and will save that (in .pyc files) and run it next time around, saving time, if you haven't updated the file since. If you've updated the file, it will be recompiled automatically.</p>
<p>You can also run python with a -O flag, which will generate .pyo files instead of .pyc. I'm not sure it makes much difference. If speed is important, use psyco.</p>
<p>And yes, on Unix (including Linux, BSD, and Mac OS X, or in a unix shell on windows) you can use a shebang line at the top of the file to make the file automatically run using python. On windows, the equivalent is to associate .py files with python.exe, and then make sure your PATHEXT environment variable includes ".PY" extensions.</p>
<p>However, for windows, you more likely want to write a gui program in python (possibly using PyQT4 and ERIC4) which has a .pyw file as its main script, and has .pyw associated with pythonw (which comes with python on windows). This will let you run python scripts on windows just like other GUI programs. For publishing and distribution, you probably want to compile to an executable file using something like py2exe, as others mentioned.</p>
| 8 | 2009-09-16T17:44:59Z | [
"python",
"compiler-construction"
] |
Compiling Python | 1,434,144 | <p>How can I compile and run a python file (*.py extension)?</p>
| 41 | 2009-09-16T16:42:51Z | 1,529,049 | <p>If you just want to compile sources, without running them, you can do this</p>
<pre><code>compileall.py <directory>
</code></pre>
<p>this command will compile python code in that directory recursively</p>
<p><strong>compileall</strong> script is usually located in directory like</p>
<pre><code>/usr/local/lib/python2.6
</code></pre>
<p>i.e. <code><prefix>/lib/python2.6</code> (or similar, depending on prefixes set a python configuration)</p>
<p>As Lulu suggests, you should make sure that resulting .pyc and .pyo files are executable by the users you care about.</p>
<p><a href="http://docs.python.org/library/compileall.html">compileall</a> can also be used as a module</p>
<pre><code>import compileall
compileall.compile_dir(path)
</code></pre>
| 9 | 2009-10-07T01:27:11Z | [
"python",
"compiler-construction"
] |
Compiling Python | 1,434,144 | <p>How can I compile and run a python file (*.py extension)?</p>
| 41 | 2009-09-16T16:42:51Z | 19,947,830 | <p><strong>Answer for Windows</strong></p>
<ol>
<li>first you must install python</li>
<li>then set path variable</li>
<li>after that write your python program and save</li>
<li>think there is a python program that name "<strong>hello.py</strong>"</li>
<li>open cmd.exe</li>
<li>then goto the path that you saved your "<strong>hello.py</strong>" file,</li>
<li>and then type <strong>python hello.py</strong> and press <strong>enter</strong> key.</li>
</ol>
<p>now the python code is automatically compile and show the result. </p>
| 0 | 2013-11-13T07:26:36Z | [
"python",
"compiler-construction"
] |
python help needed | 1,434,276 | <pre><code>import os
import sys, urllib2, urllib
import re
import time
from threading import Thread
class testit(Thread):
def __init__ (self):
Thread.__init__(self)
def run(self):
url = 'http://games.espnstar.asia/the-greatest-odi/post_brackets.php'
data = urllib.urlencode([('id',"btn_13_9_13"), ('matchNo',"13")])
req = urllib2.Request(url)
fd = urllib2.urlopen(req, data)
<TAB>fd.close()
<TAB>"""while 1:
data = fd.read(1024)
if not len(data):
break
sys.stdout.write(data)"""
url2 = 'http://games.espnstar.asia/the-greatest-odi/post_perc.php'
data2 = urllib.urlencode([('id',"btn_13_9_13"), ('matchNo',"13")])
req2 = urllib2.Request(url2)
fd2 = urllib2.urlopen(req2, data2)
<TAB>#prints current votes
while 1:
data2 = fd2.read(1024)
if not len(data2):
break
sys.stdout.write(data2)
<TAB>fd2.close()
print time.ctime()
print " ending thread\n"
i=-1
while i<0:
current = testit()
time.sleep(0.001) #decrease this like 0.0001 for more loops
current.start()
</code></pre>
<p>Hey can anybody help me finding out the error in the code
Its saying inconsistent use of tabs an spaces in indentation</p>
| -1 | 2009-09-16T17:09:12Z | 1,434,292 | <p>Unfortunately, it looks like the code formatter here on Stack Overflow turns everything into spaces. But the error is quite self-explanatory. Python, unlike the curly-brace languages (like C, C++, and Java) uses indentation to mark blocks of code. The error means that a block is improperly indented.</p>
| 4 | 2009-09-16T17:12:13Z | [
"python",
"indentation"
] |
python help needed | 1,434,276 | <pre><code>import os
import sys, urllib2, urllib
import re
import time
from threading import Thread
class testit(Thread):
def __init__ (self):
Thread.__init__(self)
def run(self):
url = 'http://games.espnstar.asia/the-greatest-odi/post_brackets.php'
data = urllib.urlencode([('id',"btn_13_9_13"), ('matchNo',"13")])
req = urllib2.Request(url)
fd = urllib2.urlopen(req, data)
<TAB>fd.close()
<TAB>"""while 1:
data = fd.read(1024)
if not len(data):
break
sys.stdout.write(data)"""
url2 = 'http://games.espnstar.asia/the-greatest-odi/post_perc.php'
data2 = urllib.urlencode([('id',"btn_13_9_13"), ('matchNo',"13")])
req2 = urllib2.Request(url2)
fd2 = urllib2.urlopen(req2, data2)
<TAB>#prints current votes
while 1:
data2 = fd2.read(1024)
if not len(data2):
break
sys.stdout.write(data2)
<TAB>fd2.close()
print time.ctime()
print " ending thread\n"
i=-1
while i<0:
current = testit()
time.sleep(0.001) #decrease this like 0.0001 for more loops
current.start()
</code></pre>
<p>Hey can anybody help me finding out the error in the code
Its saying inconsistent use of tabs an spaces in indentation</p>
| -1 | 2009-09-16T17:09:12Z | 1,434,329 | <p>I edited your post to replace all the tabs with <code><TAB></code>. You need to delete the indentation on those lines and line it back up with spaces. Some editors can do that for you, but I don't know which editor you are using.</p>
<p>If you get serious about Python, you should reconfigure your editor to always insert 4 spaces when the tab key is pressed. You can also try changing the amount of indentation provided by the tab character or in some editors print a visible symbol for the tab character so you can see where the problem is.</p>
| 5 | 2009-09-16T17:17:43Z | [
"python",
"indentation"
] |
PyQt4 - Image Watermark | 1,434,582 | <p>I'm trying to open a PNG image and write some text to it (a watermark) via QImage and QPainter. The code works 100% on Linux but when I run it on Windows XP (haven't tested with any other versions of Windows) the text is never written to the image. I have the code in a try/except block, but no errors are returned.</p>
<pre><code>image = QtGui.QImage('demo.png')
painter = QtGui.QPainter()
painter.begin(image)
painter.setOpacity(0.8)
painter.setPen(QtCore.Qt.blue)
painter.setFont(QtGui.QFont('arial', 12))
painter.drawText(image.rect(), QtCore.Qt.AlignCenter, 'Watermark')
painter.end()
image.save('demo.png')
</code></pre>
<p>Using Python 2.6.2, PyQt 4.5.4</p>
<p>Any ideas?</p>
| 2 | 2009-09-16T18:04:35Z | 1,434,605 | <p>First thing that comes to my mind is maybe it isn't finding the specified font on Windows.</p>
| 0 | 2009-09-16T18:10:09Z | [
"python",
"pyqt4",
"qimage",
"qpainter"
] |
PyQt4 - Image Watermark | 1,434,582 | <p>I'm trying to open a PNG image and write some text to it (a watermark) via QImage and QPainter. The code works 100% on Linux but when I run it on Windows XP (haven't tested with any other versions of Windows) the text is never written to the image. I have the code in a try/except block, but no errors are returned.</p>
<pre><code>image = QtGui.QImage('demo.png')
painter = QtGui.QPainter()
painter.begin(image)
painter.setOpacity(0.8)
painter.setPen(QtCore.Qt.blue)
painter.setFont(QtGui.QFont('arial', 12))
painter.drawText(image.rect(), QtCore.Qt.AlignCenter, 'Watermark')
painter.end()
image.save('demo.png')
</code></pre>
<p>Using Python 2.6.2, PyQt 4.5.4</p>
<p>Any ideas?</p>
| 2 | 2009-09-16T18:04:35Z | 1,434,615 | <p>My guess would be that whatever png lib you are using on Windows doesn't do tranparency (properly)</p>
| 0 | 2009-09-16T18:12:22Z | [
"python",
"pyqt4",
"qimage",
"qpainter"
] |
Invalid syntax error for "print expr"? | 1,434,751 | <pre><code>import os
import sys, urllib2, urllib
import re
import time
from threading import Thread
class testit(Thread):
def _init_ (self):
Thread.__init__(self)
def run(self):
url = 'http://games.espnstar.asia/the-greatest-odi/post_brackets.php'
data = urllib.urlencode([('id',"btn_13_9_13"), ('matchNo',"13")])
req = urllib2.Request(url)
fd = urllib2.urlopen(req, data)
"""while 1:
data = fd.read(1024)
if not len(data):
break
sys.stdout.write(data)"""
fd.close();
url2 = 'http://games.espnstar.asia/the-greatest-odi/post_perc.php'
data2 = urllib.urlencode([('id',"btn_13_9_13"), ('matchNo',"13")])
req2 = urllib2.Request(url2)
fd2 = urllib2.urlopen(req2, data2)
while 1:
data2 = fd2.read(1024)
if not len(data2):
break
sys.stdout.write(data2)
fd2.close()
print time.ctime()
print " ending thread\n"
i=-1
while i<0:
current = testit()
time.sleep(0.001)
current.start()
</code></pre>
<p>I'm getting an error stating invalid syntax for the line:</p>
<pre><code>print time.ctime()
</code></pre>
<p>Please help me out.</p>
| -1 | 2009-09-16T18:39:45Z | 1,434,860 | <p>From <a href="http://pydoc.org/1.6/time.html#-ctime" rel="nofollow">this page</a>:</p>
<blockquote>
<p>ctime(...)</p>
<p>ctime(seconds) -> string</p>
<p>Convert a time in seconds since the Epoch to a string in local time.</p>
<p>This is equivalent to asctime(localtime(seconds)).</p>
</blockquote>
<p><code>ctime</code> requires an argument and you aren't giving it one. If you're trying to get the current time, try <code>time.time()</code> instead. Or, if you're trying to convert the current time in seconds to a string in local time, you should try this:</p>
<pre><code>time.ctime(time.time())
</code></pre>
| -2 | 2009-09-16T18:59:35Z | [
"python",
"syntax-error"
] |
Invalid syntax error for "print expr"? | 1,434,751 | <pre><code>import os
import sys, urllib2, urllib
import re
import time
from threading import Thread
class testit(Thread):
def _init_ (self):
Thread.__init__(self)
def run(self):
url = 'http://games.espnstar.asia/the-greatest-odi/post_brackets.php'
data = urllib.urlencode([('id',"btn_13_9_13"), ('matchNo',"13")])
req = urllib2.Request(url)
fd = urllib2.urlopen(req, data)
"""while 1:
data = fd.read(1024)
if not len(data):
break
sys.stdout.write(data)"""
fd.close();
url2 = 'http://games.espnstar.asia/the-greatest-odi/post_perc.php'
data2 = urllib.urlencode([('id',"btn_13_9_13"), ('matchNo',"13")])
req2 = urllib2.Request(url2)
fd2 = urllib2.urlopen(req2, data2)
while 1:
data2 = fd2.read(1024)
if not len(data2):
break
sys.stdout.write(data2)
fd2.close()
print time.ctime()
print " ending thread\n"
i=-1
while i<0:
current = testit()
time.sleep(0.001)
current.start()
</code></pre>
<p>I'm getting an error stating invalid syntax for the line:</p>
<pre><code>print time.ctime()
</code></pre>
<p>Please help me out.</p>
| -1 | 2009-09-16T18:39:45Z | 1,434,881 | <p>This is because (in Python 3.0 onwards at least), print is a function.</p>
<p>Use:</p>
<pre><code>print (time.ctime())
</code></pre>
<p>and it should be fine.</p>
| 4 | 2009-09-16T19:02:59Z | [
"python",
"syntax-error"
] |
Thread error in Python & PyQt | 1,434,831 | <p>I noticed that when the function <a href="http://doc.trolltech.com/4.0/qabstractitemview.html#setModel" rel="nofollow">setModel</a> is executed in parallel thread (I tried threading.Timer or threading.thread), I get this:</p>
<pre><code>QObject: Cannot create children for a parent that is in a different thread.
(Parent is QHeaderView(0x1c93ed0), parent's thread is QThread(0xb179c0), current thread is QThread(0x23dce38)
QObject::startTimer: timers cannot be started from another thread
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QTreeView(0xc65060), parent's thread is QThread(0xb179c0), current thread is QThread(0x23dce38)
QObject::startTimer: timers cannot be started from another thread
</code></pre>
<p>Is there any way to solve this?</p>
| 2 | 2009-09-16T18:54:35Z | 1,434,850 | <p>Looks like you've stumped on a Qt limitation there. Try using signals or events if you need objects to communicate across threads.</p>
<p>Or ask the Qt folk about this. It doesn't seem specific to PyQt.</p>
| 0 | 2009-09-16T18:58:17Z | [
"python",
"multithreading",
"pyqt"
] |
Thread error in Python & PyQt | 1,434,831 | <p>I noticed that when the function <a href="http://doc.trolltech.com/4.0/qabstractitemview.html#setModel" rel="nofollow">setModel</a> is executed in parallel thread (I tried threading.Timer or threading.thread), I get this:</p>
<pre><code>QObject: Cannot create children for a parent that is in a different thread.
(Parent is QHeaderView(0x1c93ed0), parent's thread is QThread(0xb179c0), current thread is QThread(0x23dce38)
QObject::startTimer: timers cannot be started from another thread
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QTreeView(0xc65060), parent's thread is QThread(0xb179c0), current thread is QThread(0x23dce38)
QObject::startTimer: timers cannot be started from another thread
</code></pre>
<p>Is there any way to solve this?</p>
| 2 | 2009-09-16T18:54:35Z | 1,436,366 | <p>It is indeed a fact of life that multithreaded use of Qt (and other rich frameworks) is a delicate and difficult job, requiring explicit attention and care -- see <a href="http://doc.trolltech.com/4.5/threads.html">Qt's docs</a> for an excellent coverage of the subject (for readers experienced in threading in general, with suggested readings for those who yet aren't).</p>
<p>If you possibly can, I would suggest what I always suggest as the soundest architecture for threading in Python: let each subsystem be owned and used by a single dedicated thread; communicate among threads via instances of <code>Queue.Queue</code>, i.e., by message passing. This approach can be a bit restrictive, but it provides a good foundation on which specifically identified and carefully architected exceptions (based on thread pools, occasional new threads being spawned, locks, condition variables, and other such finicky things;-). In the latter category I would also classify Qt-specific things such as cross-thread signal/slot communication via <a href="http://doc.trolltech.com/4.5/threads.html#signals-and-slots-across-threads">queued connections</a>.</p>
| 5 | 2009-09-17T01:52:29Z | [
"python",
"multithreading",
"pyqt"
] |
Socket in use error when reusing sockets | 1,434,914 | <p>I am writing an XMLRPC client in c++ that is intended to talk to a python XMLRPC server. </p>
<p>Unfortunately, at this time, the python XMLRPC server is only capable of fielding one request on a connection, then it shuts down, I discovered this thanks to mhawke's response to my previous query about a <a href="http://stackoverflow.com/questions/1423251/talking-between-python-tcp-server-and-a-c-client">related subject</a></p>
<p>Because of this, I have to create a new socket connection to my python server every time I want to make an XMLRPC request. This means the creation and deletion of a lot of sockets. Everything works fine, until I approach ~4000 requests. At this point I get socket error <a href="http://www.pscs.co.uk/helpdesk/vpop3help/vpop3/socket%5Ferror%5F10048.htm" rel="nofollow">10048, Socket in use</a>. </p>
<p>I've tried sleeping the thread to let winsock fix its file descriptors, a trick that worked when a python client of mine had an identical issue, to no avail.
I've tried the following</p>
<pre><code>int err = setsockopt(s_,SOL_SOCKET,SO_REUSEADDR,(char*)TRUE,sizeof(BOOL));
</code></pre>
<p>with no success.</p>
<p>I'm using winsock 2.0, so WSADATA::iMaxSockets shouldn't come into play, and either way, I checked and its set to 0 (I assume that means infinity)</p>
<p>4000 requests doesn't seem like an outlandish number of requests to make during the run of an application. Is there some way to use SO_KEEPALIVE on the client side while the server continually closes and reopens?</p>
<p>Am I totally missing something?</p>
| 3 | 2009-09-16T19:10:31Z | 1,434,962 | <p>Do you close the sockets after using it?</p>
| 0 | 2009-09-16T19:21:14Z | [
"c++",
"python",
"sockets",
"xml-rpc"
] |
Socket in use error when reusing sockets | 1,434,914 | <p>I am writing an XMLRPC client in c++ that is intended to talk to a python XMLRPC server. </p>
<p>Unfortunately, at this time, the python XMLRPC server is only capable of fielding one request on a connection, then it shuts down, I discovered this thanks to mhawke's response to my previous query about a <a href="http://stackoverflow.com/questions/1423251/talking-between-python-tcp-server-and-a-c-client">related subject</a></p>
<p>Because of this, I have to create a new socket connection to my python server every time I want to make an XMLRPC request. This means the creation and deletion of a lot of sockets. Everything works fine, until I approach ~4000 requests. At this point I get socket error <a href="http://www.pscs.co.uk/helpdesk/vpop3help/vpop3/socket%5Ferror%5F10048.htm" rel="nofollow">10048, Socket in use</a>. </p>
<p>I've tried sleeping the thread to let winsock fix its file descriptors, a trick that worked when a python client of mine had an identical issue, to no avail.
I've tried the following</p>
<pre><code>int err = setsockopt(s_,SOL_SOCKET,SO_REUSEADDR,(char*)TRUE,sizeof(BOOL));
</code></pre>
<p>with no success.</p>
<p>I'm using winsock 2.0, so WSADATA::iMaxSockets shouldn't come into play, and either way, I checked and its set to 0 (I assume that means infinity)</p>
<p>4000 requests doesn't seem like an outlandish number of requests to make during the run of an application. Is there some way to use SO_KEEPALIVE on the client side while the server continually closes and reopens?</p>
<p>Am I totally missing something?</p>
| 3 | 2009-09-16T19:10:31Z | 1,435,353 | <p>Update:</p>
<p>I tossed this into the code and it seems to be working now.</p>
<pre><code>if(::connect(s_, (sockaddr *) &addr, sizeof(sockaddr)))
{
int err = WSAGetLastError();
if(err == 10048) //if socket in user error, force kill and reopen socket
{
closesocket(s_);
WSACleanup();
WSADATA info;
WSAStartup(MAKEWORD(2,0), &info);
s_ = socket(AF_INET,SOCK_STREAM,0);
setsockopt(s_,SOL_SOCKET,SO_REUSEADDR,(char*)&x,sizeof(BOOL));
}
}
</code></pre>
<p>Basically, if you encounter the 10048 error (socket in use), you can simply close the socket, call cleanup, and restart WSA, the reset the socket and its sockopt</p>
<p>(the last sockopt may not be necessary)</p>
<p>i must have been missing the WSACleanup/WSAStartup calls before, because closesocket() and socket() were definitely being called</p>
<p>this error only occurs once every 4000ish calls.</p>
<p>I am curious as to why this may be, even though this seems to fix it.
If anyone has any input on the subject i would be very curious to hear it</p>
| 1 | 2009-09-16T20:42:54Z | [
"c++",
"python",
"sockets",
"xml-rpc"
] |
Socket in use error when reusing sockets | 1,434,914 | <p>I am writing an XMLRPC client in c++ that is intended to talk to a python XMLRPC server. </p>
<p>Unfortunately, at this time, the python XMLRPC server is only capable of fielding one request on a connection, then it shuts down, I discovered this thanks to mhawke's response to my previous query about a <a href="http://stackoverflow.com/questions/1423251/talking-between-python-tcp-server-and-a-c-client">related subject</a></p>
<p>Because of this, I have to create a new socket connection to my python server every time I want to make an XMLRPC request. This means the creation and deletion of a lot of sockets. Everything works fine, until I approach ~4000 requests. At this point I get socket error <a href="http://www.pscs.co.uk/helpdesk/vpop3help/vpop3/socket%5Ferror%5F10048.htm" rel="nofollow">10048, Socket in use</a>. </p>
<p>I've tried sleeping the thread to let winsock fix its file descriptors, a trick that worked when a python client of mine had an identical issue, to no avail.
I've tried the following</p>
<pre><code>int err = setsockopt(s_,SOL_SOCKET,SO_REUSEADDR,(char*)TRUE,sizeof(BOOL));
</code></pre>
<p>with no success.</p>
<p>I'm using winsock 2.0, so WSADATA::iMaxSockets shouldn't come into play, and either way, I checked and its set to 0 (I assume that means infinity)</p>
<p>4000 requests doesn't seem like an outlandish number of requests to make during the run of an application. Is there some way to use SO_KEEPALIVE on the client side while the server continually closes and reopens?</p>
<p>Am I totally missing something?</p>
| 3 | 2009-09-16T19:10:31Z | 1,436,261 | <p>The problem is being caused by sockets hanging around in the TIME_WAIT state which is entered once you close the client's socket. By default the socket will remain in this state for 4 minutes before it is available for reuse. Your client (possibly helped by other processes) is consuming them all within a 4 minute period. See <a href="http://stackoverflow.com/questions/1339142/wcf-system-net-socketexception-only-one-usage-of-each-socket-address-protocol/1339240#1339240">this answer</a> for a good explanation and a possible non-code solution.</p>
<p>Windows dynamically allocates port numbers in the range 1024-5000 (3977 ports) when you do not explicitly bind the socket address. This Python code demonstrates the problem:</p>
<pre><code>import socket
sockets = []
while True:
s = socket.socket()
s.connect(('some_host', 80))
sockets.append(s.getsockname())
s.close()
print len(sockets)
sockets.sort()
print "Lowest port: ", sockets[0][1], " Highest port: ", sockets[-1][1]
# on Windows you should see something like this...
3960
Lowest port: 1025 Highest port: 5000
</code></pre>
<p>If you try to run this immeditaely again, it should fail very quickly since all dynamic ports are in the TIME_WAIT state.</p>
<p>There are a few ways around this:</p>
<ol>
<li><p>Manage your own port assignments and
use <code>bind()</code> to explicitly bind your
client socket to a specific port
that you increment each time your
create a socket. You'll still have
to handle the case where a port is
already in use, but you will not be
limited to dynamic ports. e.g.</p>
<pre><code>port = 5000
while True:
s = socket.socket()
s.bind(('your_host', port))
s.connect(('some_host', 80))
s.close()
port += 1
</code></pre></li>
<li><p>Fiddle with the SO_LINGER socket
option. I have found that this
sometimes works in Windows (although
not exactly sure why):
<code>s.setsockopt(socket.SOL_SOCKET,
socket.SO_LINGER, 1)</code></p></li>
<li><p>I don't know if this will help in
your particular application,
however, it is possible to send
multiple XMLRPC requests over the
same connection using the
<a href="http://docs.python.org/library/xmlrpclib.html#multicall-objects">multicall</a> method. Basically
this allows you to accumulate
several requests and then send them
all at once. You will not get any
responses until you actually send
the accumulated requests, so you can
essentially think of this as batch
processing - does this fit in with
your application design?</p></li>
</ol>
| 11 | 2009-09-17T01:09:07Z | [
"c++",
"python",
"sockets",
"xml-rpc"
] |
Python: bind child class at run time | 1,434,949 | <p>Can anyone tell me how to bind to specific child class at run time in the following code? I want mCar instance in the following example redirect to class Truck or Compact according to command line options? </p>
<pre><code>class Car(object):
pass
class Truck(Car):
pass
class Compact(Car):
pass
</code></pre>
<p>and a instance of <code>Car</code></p>
<pre><code>mCar = Car()
</code></pre>
| 0 | 2009-09-16T19:17:44Z | 1,434,974 | <p>You mean like this?</p>
<pre><code>car_classes = {
'car' : Car,
'truck' : Truck,
'compact' : Compact
}
if __name__ == '__main__':
option = sys.argv[1]
mCar = car_classes[option]()
print 'I am a', mCar.__class__.__name__
</code></pre>
| 4 | 2009-09-16T19:24:09Z | [
"python",
"class"
] |
Python: bind child class at run time | 1,434,949 | <p>Can anyone tell me how to bind to specific child class at run time in the following code? I want mCar instance in the following example redirect to class Truck or Compact according to command line options? </p>
<pre><code>class Car(object):
pass
class Truck(Car):
pass
class Compact(Car):
pass
</code></pre>
<p>and a instance of <code>Car</code></p>
<pre><code>mCar = Car()
</code></pre>
| 0 | 2009-09-16T19:17:44Z | 1,436,341 | <p>As a side note, while not particularly recommended, it IS possible to assign a different value to <code>self.__class__</code> -- be that in <code>__init__</code> or anywhere else. Do notice that this will change the lookups for class-level names (such as methods), but per se it will not alter the instance's state (nor implcitly invoke any kind of initialization -- you'll have to do it explicitly if you need that to happen)... these subtleties are part of why such tricks are not particularly recommended (along with the general cultural bias of Pythonistas against "black magic";-) and a "factory function" (which in especially simple cases can be reduce to a dict lookup, as in GHZ's answer) is the recommended approach.</p>
| 1 | 2009-09-17T01:40:22Z | [
"python",
"class"
] |
Python memory leaks | 1,435,415 | <p>I have a long-running script which, if let to run long enough, will consume all the memory on my system.</p>
<p>Without going into details about the script, I have two questions:</p>
<ol>
<li>Are there any "Best Practices" to follow, which will help prevent leaks from occurring?</li>
<li>What techniques are there to debug memory leaks in Python?</li>
</ol>
| 72 | 2009-09-16T20:56:04Z | 1,435,426 | <p>Have a look at this article: <a href="http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks" rel="nofollow">Tracing python memory leaks</a></p>
<p>Also, note that the <a href="http://docs.python.org/library/gc.html" rel="nofollow">garbage collection module</a> actually can have debug flags set. Look at the set_debug function. Additionally, look at <a href="http://stackoverflow.com/questions/1641231/python-working-around-memory-leaks/1641280#1641280">this code by Gnibbler</a> for determining the types of objects that have been created after a call.</p>
| 52 | 2009-09-16T20:58:17Z | [
"python",
"debugging",
"memory-management",
"memory-leaks"
] |
Python memory leaks | 1,435,415 | <p>I have a long-running script which, if let to run long enough, will consume all the memory on my system.</p>
<p>Without going into details about the script, I have two questions:</p>
<ol>
<li>Are there any "Best Practices" to follow, which will help prevent leaks from occurring?</li>
<li>What techniques are there to debug memory leaks in Python?</li>
</ol>
| 72 | 2009-09-16T20:56:04Z | 1,435,434 | <p>Not sure about "Best Practices" for memory leaks in python, but python should clear it's own memory by it's garbage collector. So mainly I would start by checking for circular list of some short, since they won't be picked up by the garbage collector.</p>
| 3 | 2009-09-16T20:59:56Z | [
"python",
"debugging",
"memory-management",
"memory-leaks"
] |
Python memory leaks | 1,435,415 | <p>I have a long-running script which, if let to run long enough, will consume all the memory on my system.</p>
<p>Without going into details about the script, I have two questions:</p>
<ol>
<li>Are there any "Best Practices" to follow, which will help prevent leaks from occurring?</li>
<li>What techniques are there to debug memory leaks in Python?</li>
</ol>
| 72 | 2009-09-16T20:56:04Z | 1,435,485 | <p>You should specially have a look on your global or static data (long living data).</p>
<p>When this data grows without restriction, you can also get troubles in Python.</p>
<p>The garbage collector can only collect data, that is not referenced any more. But your static data can hookup data elements that should be freed.</p>
<p>Another problem can be memory cycles, but at least in theory the Garbage collector should find and eliminate cycles -- at least as long as they are not hooked on some long living data.</p>
<p>What kinds of long living data are specially troublesome? Have a good look on any lists and dictionaries -- they can grow without any limit. In dictionaries you might even don't see the trouble coming since when you access dicts, the number of keys in the dictionary might not be of big visibility to you ...</p>
| 6 | 2009-09-16T21:08:54Z | [
"python",
"debugging",
"memory-management",
"memory-leaks"
] |
Python memory leaks | 1,435,415 | <p>I have a long-running script which, if let to run long enough, will consume all the memory on my system.</p>
<p>Without going into details about the script, I have two questions:</p>
<ol>
<li>Are there any "Best Practices" to follow, which will help prevent leaks from occurring?</li>
<li>What techniques are there to debug memory leaks in Python?</li>
</ol>
| 72 | 2009-09-16T20:56:04Z | 9,352,959 | <p>This is by no means exhaustive advice. But number one thing to keep in mind when writing with the thought of avoiding future memory leaks (loops) is to make sure that anything which accepts a reference to a call-back, should store that call-back as a weak reference.</p>
| 2 | 2012-02-19T20:32:21Z | [
"python",
"debugging",
"memory-management",
"memory-leaks"
] |
Python memory leaks | 1,435,415 | <p>I have a long-running script which, if let to run long enough, will consume all the memory on my system.</p>
<p>Without going into details about the script, I have two questions:</p>
<ol>
<li>Are there any "Best Practices" to follow, which will help prevent leaks from occurring?</li>
<li>What techniques are there to debug memory leaks in Python?</li>
</ol>
| 72 | 2009-09-16T20:56:04Z | 23,883,524 | <p>Let me recommend <a href="https://pypi.python.org/pypi/mem_top">mem_top</a> tool,<br>
that helped me to solve a similar issue.</p>
<p>It just instantly shows top suspects for memory leaks in a Python program.</p>
| 9 | 2014-05-27T07:32:36Z | [
"python",
"debugging",
"memory-management",
"memory-leaks"
] |
Python memory leaks | 1,435,415 | <p>I have a long-running script which, if let to run long enough, will consume all the memory on my system.</p>
<p>Without going into details about the script, I have two questions:</p>
<ol>
<li>Are there any "Best Practices" to follow, which will help prevent leaks from occurring?</li>
<li>What techniques are there to debug memory leaks in Python?</li>
</ol>
| 72 | 2009-09-16T20:56:04Z | 29,923,561 | <p>I tried out most options mentioned previously but found this small and intuitive package to be the best: <a href="https://github.com/pympler/pympler" rel="nofollow">pympler</a></p>
<p>It's quite straight forward to trace objects that were not garbage-collected, check this small example:</p>
<p>install package via <code>pip install pympler</code></p>
<pre><code>from pympler.tracker import SummaryTracker
tracker = SummaryTracker()
# ... some code you want to investigate ...
tracker.print_diff()
</code></pre>
<p>The output shows you all the objects that have been added, plus the memory they consumed.</p>
<p>Sample output:</p>
<pre><code> types | # objects | total size
====================================== | =========== | ============
list | 1095 | 160.78 KB
str | 1093 | 66.33 KB
int | 120 | 2.81 KB
dict | 3 | 840 B
frame (codename: create_summary) | 1 | 560 B
frame (codename: print_diff) | 1 | 480 B
</code></pre>
<p>This package provides a number of more features. Check <a href="https://pythonhosted.org/Pympler/" rel="nofollow">pympler's documentation</a>, in particular the section <a href="https://pythonhosted.org/Pympler/muppy.html" rel="nofollow">Identifying memory leaks</a>.</p>
| 33 | 2015-04-28T15:27:15Z | [
"python",
"debugging",
"memory-management",
"memory-leaks"
] |
Retrieving values from 2 different tables with Django's QuerySet | 1,435,438 | <p>For the following models:</p>
<pre><code>class Topping(models.Model):
name = models.CharField(max_length=100)
class Pizza(models.Model):
name = models.CharField(max_length=100)
toppings = models.ManyToManyField(Toppping)
</code></pre>
<p>My data looks like the following:</p>
<p>Pizza and Topping tables joined: </p>
<pre><code>ID NAME TOPPINGS
------------------------------------
1 deluxe topping_1, topping_2
2 deluxe topping_3, topping_4
3 hawaiian topping_1
</code></pre>
<p>I want to get the pizza id along with their corresponding toppings for all pizza named <code>deluxe</code>. My expected result is:</p>
<pre><code>1 topping_1
1 topping_2
2 topping_3
2 topping_4
</code></pre>
<p>The junction table is:</p>
<pre><code>pizza_toppings
--------------
id
pizza_id
topping_id
</code></pre>
<p>Here's the SQL equivalent of what I want to achieve:</p>
<pre><code>SELECT p.id, t.name
FROM pizza_toppings AS pt
INNER JOIN pizza AS p ON p.id = pt.pizza_id
INNER JOIN topping AS t ON t.id = pt.topping_id
WHERE p.name = 'deluxe'
</code></pre>
<p>Any ideas on what the corresponding Django Queryset looks like? I also want to sort the resulting toppings by name if the above is not challenging enough.</p>
| 3 | 2009-09-16T21:00:47Z | 1,435,566 | <p>There is no direct way to get a pizza when you have a topping from the model above. You could do</p>
<pre><code>pizzas = topping.pizza_set.all()
</code></pre>
<p>for all pizzas with a topping or probably (in case the topping exists on only one pizza with the name "deluxe")</p>
<pre><code>pizza = topping.pizza_set.get(name="deluxe")
</code></pre>
<p>once you have a topping. Or, you could store the Pizza and the Topping in a list of tuples or a dictionary (if there are no duplicate toppings):</p>
<pre><code>toppings = {}
pizzas = Pizza.objects.filter(name="deluxe")
for pizza in pizzas:
for topping in pizza.toppings.all():
toppings[topping.name] = pizza.name
sorted_toppings = toppings.keys()
sorted_toppings.sort()
</code></pre>
<p>Then you can fetch the pizza for a topping with the dictionary.</p>
| 0 | 2009-09-16T21:25:57Z | [
"python",
"django",
"django-models"
] |
Retrieving values from 2 different tables with Django's QuerySet | 1,435,438 | <p>For the following models:</p>
<pre><code>class Topping(models.Model):
name = models.CharField(max_length=100)
class Pizza(models.Model):
name = models.CharField(max_length=100)
toppings = models.ManyToManyField(Toppping)
</code></pre>
<p>My data looks like the following:</p>
<p>Pizza and Topping tables joined: </p>
<pre><code>ID NAME TOPPINGS
------------------------------------
1 deluxe topping_1, topping_2
2 deluxe topping_3, topping_4
3 hawaiian topping_1
</code></pre>
<p>I want to get the pizza id along with their corresponding toppings for all pizza named <code>deluxe</code>. My expected result is:</p>
<pre><code>1 topping_1
1 topping_2
2 topping_3
2 topping_4
</code></pre>
<p>The junction table is:</p>
<pre><code>pizza_toppings
--------------
id
pizza_id
topping_id
</code></pre>
<p>Here's the SQL equivalent of what I want to achieve:</p>
<pre><code>SELECT p.id, t.name
FROM pizza_toppings AS pt
INNER JOIN pizza AS p ON p.id = pt.pizza_id
INNER JOIN topping AS t ON t.id = pt.topping_id
WHERE p.name = 'deluxe'
</code></pre>
<p>Any ideas on what the corresponding Django Queryset looks like? I also want to sort the resulting toppings by name if the above is not challenging enough.</p>
| 3 | 2009-09-16T21:00:47Z | 1,438,650 | <p>I don't think there is a clean solution to this, since you want data from two different models. Depending on your data structure you might want to use select_related to avoid hitting the database for all the toppings. Going for your desired result, I would do:</p>
<pre><code>result = []
pizzas = Pizza.objects.select_related().filter(name='deluxe')
for pizza in pizzas:
for toppings in pizza.toppings.all():
result.append((pizza.pk, topping.name))
</code></pre>
<p>This would generate:</p>
<pre><code>[
(1, topping_1),
(1, topping_2),
(2, topping_3),
(2, topping_4),
]
</code></pre>
<p>Now there are different ways to setup the data, using lists, tuples and dictionaries, but I think you get the idea of how you could do it.</p>
| 2 | 2009-09-17T12:45:50Z | [
"python",
"django",
"django-models"
] |
manage.py syncdb doesn't add tables for some models | 1,435,523 | <p>My second not-so-adept question of the day: I have a django project with four installed apps. When I run manage.py syndb, it only creates tables for two of them. To my knowledge, there are no problems in any of my models files, and all the apps are specified in INSTALLED_APPS in my settings file. Manage.py syndb just seems to ignore two of my apps. </p>
<p>One thing that is unique about the two "ignored" apps is that the models files import models from the other two apps and use them as foreign keys (don't know if this is good/bad practice, but helps me stay organized). I don't think that's the problem though, because I commented out the foreign key-having models and the tables still weren't created. I'm stumped.</p>
<p>UPDATE: When I comment out the lines importing models files from other apps, syndb creates my tables. Perhaps I'm not understanding something about how models files in separate apps relate to other other. I though it was ok to use a model from another app as a foreign key by simply importing it. Not true?</p>
| 4 | 2009-09-16T21:17:42Z | 1,435,758 | <p>I think I ran across something similar.</p>
<p>I had an issue where a model wasn't being reset.
In this case it turned out that there was an error in my models that wasn't being spit out.</p>
<p>Although I think syncdb, when run, spit out some kind of error.</p>
<p>In any case try to import your models file from the shell and see if you can.</p>
<pre><code>$ manage.py shell
>>> from myapp import models
>>>
</code></pre>
<p>If theres an error in the file this should point it out.</p>
<p>According to your update, it sounds like you may have a cross-import issue.
Instead of:</p>
<pre><code>from app1.models import X
class ModelA(models.Model):
fk = models.ForeignKey(X)
</code></pre>
<p>Try:</p>
<pre><code>class ModelA(models.Model):
fk = models.ForeignKey("app1.X")
</code></pre>
<p>... although I think you should get an error on syncdb.</p>
| 8 | 2009-09-16T22:06:55Z | [
"python",
"django",
"django-models",
"django-syncdb"
] |
manage.py syncdb doesn't add tables for some models | 1,435,523 | <p>My second not-so-adept question of the day: I have a django project with four installed apps. When I run manage.py syndb, it only creates tables for two of them. To my knowledge, there are no problems in any of my models files, and all the apps are specified in INSTALLED_APPS in my settings file. Manage.py syndb just seems to ignore two of my apps. </p>
<p>One thing that is unique about the two "ignored" apps is that the models files import models from the other two apps and use them as foreign keys (don't know if this is good/bad practice, but helps me stay organized). I don't think that's the problem though, because I commented out the foreign key-having models and the tables still weren't created. I'm stumped.</p>
<p>UPDATE: When I comment out the lines importing models files from other apps, syndb creates my tables. Perhaps I'm not understanding something about how models files in separate apps relate to other other. I though it was ok to use a model from another app as a foreign key by simply importing it. Not true?</p>
| 4 | 2009-09-16T21:17:42Z | 1,436,024 | <p>Unfortunately, manage.py silently fails to load an app where there's an import error in its models.py (<a href="http://code.djangoproject.com/ticket/10706">ticket #10706</a>). Chances are that there's a typo in one of your models.py files... check all of the import statements closely (or use pylint). </p>
<p>Recently syncdb stoped loading a couple of my apps, and sqlall gave me the error "App with label foo could not be found". Not knowing that this sometimes means "App with label foo was found but could not be loaded due to ImportError being raised", it took me half an hour to realise that I was trying to import 'haslib' instead of 'hashlib' in one of my models.py files.</p>
| 6 | 2009-09-16T23:26:28Z | [
"python",
"django",
"django-models",
"django-syncdb"
] |
Matplotlib Legend for Scatter with custom colours | 1,435,535 | <p>I'm a bit of newbie at this and am trying to create a scatter chart with custom bubble sizes and colours. The chart displays fine but how do I get a legend saying what the colours refer to. This is as far as I've got:</p>
<pre><code>inc = []
out = []
bal = []
col = []
fig=Figure()
ax=fig.add_subplot(111)
inc = (30000,20000,70000)
out = (80000,30000,40000)
bal = (12000,10000,6000)
col = (1,2,3)
leg = ('proj1','proj2','proj3')
ax.scatter(inc, out, s=bal, c=col)
ax.axis([0, 100000, 0, 100000])
ax.set_xlabel('income', fontsize=20)
ax.set_ylabel('Expenditure', fontsize=20)
ax.set_title('Project FInancial Positions %s' % dt)
ax.grid(True)
canvas=FigureCanvas(fig)
response=HttpResponse(content_type='image/png')
canvas.print_png(response)
</code></pre>
<p>This thread was helpful, but couldn't get it to solve my problem: <a href="http://stackoverflow.com/questions/872397/matplotlib-legend-not-displayed-properly">http://stackoverflow.com/questions/872397/matplotlib-legend-not-displayed-properly</a></p>
| 10 | 2009-09-16T21:20:11Z | 1,435,635 | <p>Have a look into this:</p>
<p><a href="http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.legend" rel="nofollow">http://matplotlib.sourceforge.net/api/pyplot%5Fapi.html#matplotlib.pyplot.legend</a></p>
<p>Hope that helps. If not just ask for more :)</p>
| -3 | 2009-09-16T21:38:28Z | [
"python",
"charts",
"matplotlib"
] |
Matplotlib Legend for Scatter with custom colours | 1,435,535 | <p>I'm a bit of newbie at this and am trying to create a scatter chart with custom bubble sizes and colours. The chart displays fine but how do I get a legend saying what the colours refer to. This is as far as I've got:</p>
<pre><code>inc = []
out = []
bal = []
col = []
fig=Figure()
ax=fig.add_subplot(111)
inc = (30000,20000,70000)
out = (80000,30000,40000)
bal = (12000,10000,6000)
col = (1,2,3)
leg = ('proj1','proj2','proj3')
ax.scatter(inc, out, s=bal, c=col)
ax.axis([0, 100000, 0, 100000])
ax.set_xlabel('income', fontsize=20)
ax.set_ylabel('Expenditure', fontsize=20)
ax.set_title('Project FInancial Positions %s' % dt)
ax.grid(True)
canvas=FigureCanvas(fig)
response=HttpResponse(content_type='image/png')
canvas.print_png(response)
</code></pre>
<p>This thread was helpful, but couldn't get it to solve my problem: <a href="http://stackoverflow.com/questions/872397/matplotlib-legend-not-displayed-properly">http://stackoverflow.com/questions/872397/matplotlib-legend-not-displayed-properly</a></p>
| 10 | 2009-09-16T21:20:11Z | 1,435,977 | <p>Maybe this <a href="http://en.wikipedia.org/wiki/File%3aWeight_Growth_of_RN_First_Rate_Line-of-Battle_Ships_1630-1875.svg" rel="nofollow">example</a> is helpful.</p>
<p>In general, the items in the legend are related with some kind of <em>plotted object</em>. The <code>scatter</code> function/method treats all circles as a single object, see:</p>
<pre><code>print type(ax.scatter(...))
</code></pre>
<p>Thus the solution is to create multiple objects. Hence, calling <code>scatter</code> multiple times.</p>
<p>Unfortunately, newer version of matplotlib seem not to use a rectangle in the legend. Thus the legend will contain very large circles, since you increased the size of your scatter plot objects.</p>
<p>The legend function as a <code>markerscale</code> keyword argument to control the size of legend markers, but it seems to be broken.</p>
<p><strong>Update:</strong></p>
<p>The <a href="http://matplotlib.sourceforge.net/users/legend_guide.html" rel="nofollow">Legend guide</a> recommends using <a href="http://matplotlib.sourceforge.net/users/legend_guide.html#using-proxy-artist" rel="nofollow">Proxy Artist</a> in similar cases. The <a href="http://matplotlib.sourceforge.net/api/colors_api.html" rel="nofollow">Color API</a> explains valid <code>fc</code> values.</p>
<pre><code>p1 = Rectangle((0, 0), 1, 1, fc="b")
p2 = Rectangle((0, 0), 1, 1, fc="g")
p3 = Rectangle((0, 0), 1, 1, fc="r")
legend((p1, p2, p3), ('proj1','proj2','proj3'))
</code></pre>
<p>To get the colors used previously in a plot, use the above example like:</p>
<pre><code>pl1, = plot(x1, y1, '.', alpha=0.1, label='plot1')
pl2, = plot(x2, y2, '.', alpha=0.1, label='plot2')
p1 = Rectangle((0, 0), 1, 1, fc=pl1.get_color())
p2 = Rectangle((0, 0), 1, 1, fc=pl2.get_color())
legend((p1, p2), (pl1.get_label(), pl2.get_label()), loc='best')
</code></pre>
<p>This example will make a plot like:</p>
<p><img src="http://i.stack.imgur.com/rLtIO.png" alt="Matplotlib with custom legend"></p>
| 9 | 2009-09-16T23:06:52Z | [
"python",
"charts",
"matplotlib"
] |
Getting Started with Tornado | 1,435,896 | <p>After installing the necessary packages through apt (python 2.5, simplejson etc) I get an error when I try to run the demos.</p>
<pre>
<code>
: Request instance has no attribute 'responseHeaders'
/usr/lib/python2.5/site-packages/tornado/web.py, line 404 in flush
402 for k,v in self._generate_headers():
403 if isinstance(v, list):
404 self.request.responseHeaders.setRawHeaders(k, v)
405 else:
Self
request
twisted.web.server.Request instance @ 0x85da24c
Locals
self
k 'Set-Cookie'
v
List instance @ 0x85da46c
</code>
</pre>
<p>Here is proof that the necessary packages are installed</p>
<pre>
<code>
/web/tmp/tornado/demos/helloworld# dpkg -l | grep python2.5
ii python2.5 2.5.2-2ubuntu6 An interactive high-level object-oriented la
ii python2.5-dev 2.5.2-2ubuntu6 Header files and a static library for Python
ii python2.5-minimal 2.5.2-2ubuntu6 A minimal subset of the Python language
# dpkg -l | grep simplejson
ii python-simplejson 1.7.3-1
# dpkg -l | grep pycurl
ii python-pycurl 7.16.4-1
</code>
</pre>
<p>Seems that not too many people have been trying out this Tornado thing from friendfeed. Anyone have any suggestions/hints to help me get up and running with it?</p>
| 3 | 2009-09-16T22:43:30Z | 1,436,012 | <p>I was under the impression tornado didn't depend on twisted. Have you tried the "official" version? line 404 is completely different.</p>
<p><a href="http://github.com/facebook/tornado/blob/master/tornado/web.py" rel="nofollow">http://github.com/facebook/tornado/blob/master/tornado/web.py</a></p>
<pre><code>def flush(self, include_footers=False):
"""Flushes the current output buffer to the nextwork."""
if self.application._wsgi:
raise Exception("WSGI applications do not support flush()") #line 404
if not self._headers_written:
self._headers_written = True
headers = self._generate_headers()
else:
headers = ""
</code></pre>
<p>Other than that, I'd try installing twisted and see what happens</p>
| 2 | 2009-09-16T23:21:32Z | [
"python",
"twisted",
"tornado"
] |
Primer on writing documentation with Sphinx? | 1,436,092 | <p>I followed a tutorial that showed only how to build it, I have it up and running on my web host but I'm a bit confused on how I should be creating and writing documentation.</p>
<p>So far I've made a small little edit to the index.rst file and made a new reference to a page, then it obviously complains that it's an "undefined label: foobarz ".</p>
<p>Is there some sort of primer out there anyone can recommend? Do I always have to regenerate the html? Is there some easier way that I can edit files on the fly in a web page such as a wiki or does that go against the whole concept?</p>
<p>Thanks.</p>
| 5 | 2009-09-16T23:57:52Z | 1,436,131 | <p>From your question I can't tell if the <a href="http://matplotlib.sourceforge.net/sampledoc/index.html" rel="nofollow">sampledoc</a> tutorial is the tutorial that you've already tried. If you haven't tried it I suggest you do.</p>
| 6 | 2009-09-17T00:12:12Z | [
"python",
"documentation",
"python-sphinx"
] |
Problem with building Boost Graph Library Python bindings under Leopard | 1,436,182 | <p>I've inherited some Python code which is importing boost.graph and I'm having an issue setting up the following under Mac OS X Leopard (I believe this is what I need to install to get it working):</p>
<p><a href="http://osl.iu.edu/~dgregor/bgl-python/" rel="nofollow">http://osl.iu.edu/~dgregor/bgl-python/</a></p>
<p>According to the readme I need to build with bjam, but I see the following error:</p>
<pre><code>[matt@imac ~/Downloads/bgl-python-0.9]$ bjam
error: Could not find parent for project at '.'
error: Did not find Jamfile or project-root.jam in any parent directory.
</code></pre>
<p>I'm running a full Macports stack of python25, boost, boost-jam, boost-build.</p>
<p>I don't have any experience with building using bjam. Can anyone offer any help?</p>
| 0 | 2009-09-17T00:38:22Z | 1,443,154 | <p>This error suggests the project is not a standalone, and is meant to be put inside the Boost source tree.</p>
| 0 | 2009-09-18T08:07:41Z | [
"python",
"boost",
"graph",
"osx-leopard",
"binding"
] |
state of HTML after onload javascript | 1,436,211 | <p>many webpages use onload JavaScript to manipulate their DOM. Is there a way I can automate accessing the state of the HTML after these JavaScript operations?</p>
<p>A took like wget is not useful here because it just downloads the original source.
Is there perhaps a way to use a web browser rendering engine?</p>
<p>Ideally I am after a solution that I can interface with from Python.</p>
<p>thanks!</p>
| 1 | 2009-09-17T00:51:50Z | 1,436,306 | <p>The only good way I know to do such things is to automate a browser, for example via <a href="http://seleniumhq.org/projects/remote-control/" rel="nofollow">Selenium RC</a>. If you have no idea of how to deduce that the page has finished running the relevant javascript, then, just a real live user visiting that page, you'll just have to wait a while, grab a snapshot, wait some more, grab another, and check there was no change between them to convince yourself that it's really finished.</p>
| 2 | 2009-09-17T01:29:14Z | [
"javascript",
"python",
"html",
"screen-scraping"
] |
state of HTML after onload javascript | 1,436,211 | <p>many webpages use onload JavaScript to manipulate their DOM. Is there a way I can automate accessing the state of the HTML after these JavaScript operations?</p>
<p>A took like wget is not useful here because it just downloads the original source.
Is there perhaps a way to use a web browser rendering engine?</p>
<p>Ideally I am after a solution that I can interface with from Python.</p>
<p>thanks!</p>
| 1 | 2009-09-17T00:51:50Z | 1,436,325 | <p>Please see related info at stackoverflow:</p>
<ul>
<li><a href="http://stackoverflow.com/questions/tagged/screen-scraping">screen-scraping</a> </li>
<li><a href="http://stackoverflow.com/questions/857515/screen-scraping-from-a-web-page-with-a-lot-of-javascript">Screen Scraping from a web page with a lot of Javascript</a></li>
</ul>
| 1 | 2009-09-17T01:34:30Z | [
"javascript",
"python",
"html",
"screen-scraping"
] |
Fixing broken urls | 1,436,382 | <p>Does anyone know of a library for fixing "broken" urls. When I try to open a url such as </p>
<pre><code>http://www.domain.com/../page.html
http://www.domain.com//page.html
http://www.domain.com/page.html#stuff
</code></pre>
<p>urllib2.urlopen chokes and gives me an HTTPError traceback. Does anyone know of a library that can fix these sorts of things?</p>
| 0 | 2009-09-17T02:02:06Z | 1,436,541 | <p>What about something like...:</p>
<pre><code>import re
import urlparse
urls = '''
http://www.domain.com/../page.html
http://www.domain.com//page.html
http://www.domain.com/page.html#stuff
'''.split()
def main():
for u in urls:
pieces = list(urlparse.urlparse(u))
pieces[2] = re.sub(r'^[./]*', '/', pieces[2])
pieces[-1] = ''
print urlparse.urlunparse(pieces)
main()
</code></pre>
<p>it does emit, as you desire:</p>
<pre><code>http://www.domain.com/page.html
http://www.domain.com/page.html
http://www.domain.com/page.html
</code></pre>
<p>and would appear to roughly match your needs, if I understood them correctly.</p>
| 2 | 2009-09-17T03:10:31Z | [
"python",
"url",
"urllib2"
] |
Fixing broken urls | 1,436,382 | <p>Does anyone know of a library for fixing "broken" urls. When I try to open a url such as </p>
<pre><code>http://www.domain.com/../page.html
http://www.domain.com//page.html
http://www.domain.com/page.html#stuff
</code></pre>
<p>urllib2.urlopen chokes and gives me an HTTPError traceback. Does anyone know of a library that can fix these sorts of things?</p>
| 0 | 2009-09-17T02:02:06Z | 1,440,536 | <p>See also <a href="http://stackoverflow.com/questions/120951/how-can-i-normalize-a-url-in-python">this question</a>.</p>
| 0 | 2009-09-17T18:25:35Z | [
"python",
"url",
"urllib2"
] |
Python - Iterate over all classes | 1,436,384 | <p>How can I iterate over a list of all classes loaded in memory?
I'm thinking of doing it for a backup, looking for all classes inheriting from db.Model (Google App Engine). </p>
<p>Thanks,
Neal Walters </p>
| 2 | 2009-09-17T02:03:31Z | 1,436,401 | <p>Classes are defined in modules. Modules are created by an <code>import</code> statement.</p>
<p>Modules are simply dictionaries. If you want, you can use the <code>dir(x)</code> function on a module named <code>x</code></p>
<p>Or you can use <code>x.__dict__</code> on a module named <code>x</code>.</p>
| 2 | 2009-09-17T02:09:30Z | [
"python",
"google-app-engine",
"loops"
] |
Python - Iterate over all classes | 1,436,384 | <p>How can I iterate over a list of all classes loaded in memory?
I'm thinking of doing it for a backup, looking for all classes inheriting from db.Model (Google App Engine). </p>
<p>Thanks,
Neal Walters </p>
| 2 | 2009-09-17T02:03:31Z | 1,436,451 | <p>In "normal" Python, you can reach all objects via the <code>gc.getobjects()</code> function of the <code>gc</code> standard library module; it's then very easy to loop on them, checking which one are classes (rather than instances or anything else -- I do believe you mean <em>instances</em> of classes, but you can very easily get the classes themselves too if that's really what you want), etc.</p>
<p>Unfortunately, the <code>gc</code> module in App Engine does NOT implement <code>getobjects</code> -- which makes it extremely difficult to reach ALL classes. For example, a class created by calling:</p>
<pre><code>def makeaclass():
class sic(object): pass
return sic
</code></pre>
<p>and hidden into a list somewhere, IS going to be very difficult to reach.</p>
<p>But fortunately, since you say in your question's text that you only care about subclasses of <code>db.Model</code>, that's even easier than <code>gc</code> would allow:</p>
<pre><code>for amodel in db.Model.__subclasses__():
...
</code></pre>
<p>Just make sure you explicitly ignore such classes you don't care about, such as <code>Expando</code>;-).</p>
<p>Note that this DOES give you only and exactly the CLASSES, <strong>not</strong> the instances -- there is no similarly easy shortcut if <em>those</em> are what you're really after!</p>
| 9 | 2009-09-17T02:34:35Z | [
"python",
"google-app-engine",
"loops"
] |
Python - Iterate over all classes | 1,436,384 | <p>How can I iterate over a list of all classes loaded in memory?
I'm thinking of doing it for a backup, looking for all classes inheriting from db.Model (Google App Engine). </p>
<p>Thanks,
Neal Walters </p>
| 2 | 2009-09-17T02:03:31Z | 1,436,472 | <p>Based on S.Lott's response:
This works if I omit the "if issubclass" except then I get classes I don't want.</p>
<pre><code> import dbModels
self.response.out.write("<br/><br/>Class Names:</br/>")
for item in dbModels.__dict__:
if issubclass(item, db.Model):
self.response.out.write("<br/>" + item)
</code></pre>
<p>The above gives error: </p>
<blockquote>
<p>TypeError: issubclass() arg 1 must be
a class</p>
</blockquote>
<p>So it wants a classname as a parm, not an object name apparently.</p>
<p>Based on Alex's answer, this worked great: </p>
<pre><code> self.response.out.write("<br/><br/>Class Names Inheriting from db.Model:</br/>")
for item in db.Model.__subclasses__():
self.response.out.write("<br/>" + item.__name__)
</code></pre>
<p>Thanks to both!</p>
<p>Neal </p>
| 0 | 2009-09-17T02:40:47Z | [
"python",
"google-app-engine",
"loops"
] |
long-index arrays in python | 1,436,411 | <p>I'm attempting to shorten the memory footprint of 10B sequential integers by referencing them as indexes in a boolean array. In other words, I need to create an array of 10,000,000,000 elements, but that's well into the "Long" range. When I try to reference an array index greater than sys.maxint the array blows up:</p>
<pre>
x = [False] * 10000000000
Traceback (most recent call last):
File "", line 1, in
x = [0] * 10000000000
OverflowError: cannot fit 'long' into an index-sized integer
</pre>
<p>Anything I can do? I can't seem to find anyone on the net having this problem... Presumably the answer is "python can't handle arrays bigger than 2B." </p>
| 2 | 2009-09-17T02:18:22Z | 1,436,450 | <p>From googling around some , e.g. <a href="http://www.python.org/doc/2.5/whatsnew/pep-353.html" rel="nofollow">PEP 353</a> (assuming I'm understanding it) and <a href="http://mail.python.org/pipermail/python-list/2006-January/532801.html" rel="nofollow">this exchange</a> it looks like the real issue is probably platform/system dependent. Do you have enough memory to handle 10,000,000,000 entries?</p>
| 0 | 2009-09-17T02:34:33Z | [
"python"
] |
long-index arrays in python | 1,436,411 | <p>I'm attempting to shorten the memory footprint of 10B sequential integers by referencing them as indexes in a boolean array. In other words, I need to create an array of 10,000,000,000 elements, but that's well into the "Long" range. When I try to reference an array index greater than sys.maxint the array blows up:</p>
<pre>
x = [False] * 10000000000
Traceback (most recent call last):
File "", line 1, in
x = [0] * 10000000000
OverflowError: cannot fit 'long' into an index-sized integer
</pre>
<p>Anything I can do? I can't seem to find anyone on the net having this problem... Presumably the answer is "python can't handle arrays bigger than 2B." </p>
| 2 | 2009-09-17T02:18:22Z | 1,436,482 | <blockquote>
<p>10B booleans (1.25MB of memory, assuming Python is sane)</p>
</blockquote>
<p>I think you have your arithmetic wrong -- stored supercompactly, 10B booleans would be 1.25 <strong>GIGA</strong>, _not__ <strong>MEGA</strong>, bytes.</p>
<p>A list takes at least 4 bytes per item, so you'd need 40GB to do it the way you want.</p>
<p>You can store an <strong>array</strong> (see the <code>array</code> module in the standard library) in much less memory than that, so it might possibly fit.</p>
| 2 | 2009-09-17T02:43:32Z | [
"python"
] |
long-index arrays in python | 1,436,411 | <p>I'm attempting to shorten the memory footprint of 10B sequential integers by referencing them as indexes in a boolean array. In other words, I need to create an array of 10,000,000,000 elements, but that's well into the "Long" range. When I try to reference an array index greater than sys.maxint the array blows up:</p>
<pre>
x = [False] * 10000000000
Traceback (most recent call last):
File "", line 1, in
x = [0] * 10000000000
OverflowError: cannot fit 'long' into an index-sized integer
</pre>
<p>Anything I can do? I can't seem to find anyone on the net having this problem... Presumably the answer is "python can't handle arrays bigger than 2B." </p>
| 2 | 2009-09-17T02:18:22Z | 1,436,491 | <p>With a 32-bit address space, any language is going to be struggling to be able to address such an array. Then there's the problem of how much real memory you have on your computer.</p>
<p>If you want 10B array elements, each element representing either true or false, use an array.array('I', ...) ...</p>
<pre><code>container = array.array('I', [0]) * ((10000000000 + 31) // 32)
</code></pre>
<p>Then you can set and clear bits using the usual masking and shifting operations.</p>
<p><strong>Alternative:</strong></p>
<p>If only a small number of elements are true, or only a small number of elements are false, you could use a set for the best memory saving, or a dict for programming convenience.</p>
| 5 | 2009-09-17T02:46:39Z | [
"python"
] |
long-index arrays in python | 1,436,411 | <p>I'm attempting to shorten the memory footprint of 10B sequential integers by referencing them as indexes in a boolean array. In other words, I need to create an array of 10,000,000,000 elements, but that's well into the "Long" range. When I try to reference an array index greater than sys.maxint the array blows up:</p>
<pre>
x = [False] * 10000000000
Traceback (most recent call last):
File "", line 1, in
x = [0] * 10000000000
OverflowError: cannot fit 'long' into an index-sized integer
</pre>
<p>Anything I can do? I can't seem to find anyone on the net having this problem... Presumably the answer is "python can't handle arrays bigger than 2B." </p>
| 2 | 2009-09-17T02:18:22Z | 1,436,547 | <p>A dense bit vector is plausible but it won't be optimal unless you know you won't have more than about <code>10**10</code> elements, all clustered near each other, with a reasonably randomized distribution. If you have a different distribution, then a different structure will be better. </p>
<p>For instance, if you know that in that range, [0,10**10), only a few members are present, use a <code>set()</code>, or if the reverse is true, with nearly every element present except for a fraction, use a negated set, ie <code>element not in mySet</code>. </p>
<p>If the elements tend to cluster around small ranges, you could use a run length encoding, something like <code>[xrange(0,10),xrange(10,15),xrange(15,100)]</code>, which you lookup into by bisecting until you find a matching range, and if the index is even, then the element is in the set. inserts and removals involve shuffling the ranges a bit.</p>
<p>If your distribution really is dense, but you need a little more than what fits in memory (seems to be typical in practice) then you can manage memory by using <code>mmap</code> and wrapping the mapped file with an adaptor that uses a similar mechanism to the suggested <code>array('I')</code> solution already suggested.</p>
<p>To get an idea of just how compressible you can possibly get, try building a plain file with a reasonable corpus of data in packed form and then apply a general compression algorithm (such as gzip) to see how much reduction you see. If there is much reduction, then you can probably use some sort of space optimization in your code as well.</p>
| 3 | 2009-09-17T03:13:53Z | [
"python"
] |
long-index arrays in python | 1,436,411 | <p>I'm attempting to shorten the memory footprint of 10B sequential integers by referencing them as indexes in a boolean array. In other words, I need to create an array of 10,000,000,000 elements, but that's well into the "Long" range. When I try to reference an array index greater than sys.maxint the array blows up:</p>
<pre>
x = [False] * 10000000000
Traceback (most recent call last):
File "", line 1, in
x = [0] * 10000000000
OverflowError: cannot fit 'long' into an index-sized integer
</pre>
<p>Anything I can do? I can't seem to find anyone on the net having this problem... Presumably the answer is "python can't handle arrays bigger than 2B." </p>
| 2 | 2009-09-17T02:18:22Z | 1,436,606 | <p>The <a href="http://pypi.python.org/pypi/bitarray/" rel="nofollow">bitarray</a> package looks like it might be another useful option.</p>
| 4 | 2009-09-17T03:39:22Z | [
"python"
] |
long-index arrays in python | 1,436,411 | <p>I'm attempting to shorten the memory footprint of 10B sequential integers by referencing them as indexes in a boolean array. In other words, I need to create an array of 10,000,000,000 elements, but that's well into the "Long" range. When I try to reference an array index greater than sys.maxint the array blows up:</p>
<pre>
x = [False] * 10000000000
Traceback (most recent call last):
File "", line 1, in
x = [0] * 10000000000
OverflowError: cannot fit 'long' into an index-sized integer
</pre>
<p>Anything I can do? I can't seem to find anyone on the net having this problem... Presumably the answer is "python can't handle arrays bigger than 2B." </p>
| 2 | 2009-09-17T02:18:22Z | 2,555,287 | <p>Another option for very large bit arrays would be to use <a href="http://python-bitstring.googlecode.com" rel="nofollow">bitstring</a>. It uses a <code>bytearray</code> (or <code>array.array</code> on older Python versions) to store the data but its interface is just an array of bits. For your case you could use:</p>
<pre><code>>>> from bitstring import BitString
>>> s = BitString(10000000000) # zero initialised
>>> s.set([9, 999999999, 253]) # set 3 bits to '1'
>>> s[66] = True # set another bit
>>> s.allset([9, 66]) # check if bits are set to '1'
True
</code></pre>
<p>I think it's preferable to doing all the bit masking and shifting yourself!</p>
| 1 | 2010-03-31T18:04:31Z | [
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.