title
stringlengths
12
150
question_id
int64
469
40.1M
question_score
int64
2
5.52k
question_date
stringdate
2008-08-02 15:11:16
2016-10-18 06:16:31
answer_id
int64
536
40.1M
answer_score
int64
7
8.38k
answer_date
stringdate
2008-08-02 18:49:07
2016-10-18 06:19:33
tags
listlengths
1
5
question_body_md
stringlengths
15
30.2k
answer_body_md
stringlengths
11
27.8k
Why does sys.exit() not exit when called inside a thread in Python?
905,189
43
2009-05-25T03:10:44Z
905,224
35
2009-05-25T03:31:38Z
[ "python", "python-2.6" ]
This could be a stupid question, but I'm testing out some of my assumptions about Python and I'm confused as to why the following code snippet would not exit when called in the thread, but would exit when called in the main thread. ``` import sys, time from threading import Thread def testexit(): time.sleep(5) sys....
sys.exit() raises the SystemExit exception, as does thread.exit(). So, when sys.exit() raises that exception inside that thread, it has the same effect as calling thread.exit(), which is why only the thread exits.
Why does sys.exit() not exit when called inside a thread in Python?
905,189
43
2009-05-25T03:10:44Z
906,401
12
2009-05-25T11:32:18Z
[ "python", "python-2.6" ]
This could be a stupid question, but I'm testing out some of my assumptions about Python and I'm confused as to why the following code snippet would not exit when called in the thread, but would exit when called in the main thread. ``` import sys, time from threading import Thread def testexit(): time.sleep(5) sys....
> What if I did want to exit the program > from the thread (not that I actually > want to, but just so I understand)? My preferred method is Erlang-ish message passing. Slightly simlified, I do it like this: ``` import sys, time import threading import Queue # thread-safe class CleanExit: pass ipq = Queue.Queue()...
Why does sys.exit() not exit when called inside a thread in Python?
905,189
43
2009-05-25T03:10:44Z
5,120,178
7
2011-02-25T16:58:10Z
[ "python", "python-2.6" ]
This could be a stupid question, but I'm testing out some of my assumptions about Python and I'm confused as to why the following code snippet would not exit when called in the thread, but would exit when called in the main thread. ``` import sys, time from threading import Thread def testexit(): time.sleep(5) sys....
> What if I did want to exit the program > from the thread? Apart from the method Deestan described you can call `os._exit` (notice the underscore). Before using it make sure that you understand that it does *no* cleanups (like calling `__del__` or similar).
os.system() execute command under which linux shell?
905,221
8
2009-05-25T03:30:14Z
905,258
9
2009-05-25T03:51:58Z
[ "python", "linux", "shell" ]
I am using /bin/tcsh as my default shell. However, the tcsh style command os.system('setenv VAR val') doesn't work for me. But os.system('export VAR=val') works. So my question is how can I know the os.system() run command under which shell?
These days you should be using the [Subprocess](http://docs.python.org/library/subprocess.html) module instead of `os.system()`. According to the documentation there, the default shell is `/bin/sh`. I believe that `os.system()` works the same way. Edit: I should also mention that the subprocess module allows you to se...
os.system() execute command under which linux shell?
905,221
8
2009-05-25T03:30:14Z
14,665,851
8
2013-02-02T19:54:43Z
[ "python", "linux", "shell" ]
I am using /bin/tcsh as my default shell. However, the tcsh style command os.system('setenv VAR val') doesn't work for me. But os.system('export VAR=val') works. So my question is how can I know the os.system() run command under which shell?
Was just reading [Executing BASH from Python](http://www.rubyops.net/executing-bash-from-python), then [17.1. subprocess — Subprocess management — Python v2.7.3 documentation](http://docs.python.org/2/library/subprocess.html#popen-constructor), and I saw the `executable` argument; and it seems to work: ``` $ pytho...
Python - how to implement Bridge (or Adapter) design pattern?
905,289
7
2009-05-25T04:12:43Z
905,292
21
2009-05-25T04:16:29Z
[ "python", "design-patterns" ]
I'm struggling with implementing the Bridge design pattern (or an alternative such as Adapter) in Python I want to be able to write code like this to dump database schemas based on a supplied URL: ``` urls = ['sqlite://c:\\temp\\test.db', 'oracle://user:password@tns_name']; for url in urls: db = Database(url); ...
Use a Factory pattern instead: ``` class Oracle(object): ... class SQLite(object): ... dbkind = dict(sqlite=SQLite, oracle=Oracle) def Database(url): db_type, rest = string.split(self.url, "://", 1) return dbkind[db_type](rest) ```
A neat way of extending a class attribute in subclasses
907,324
15
2009-05-25T16:28:54Z
907,423
8
2009-05-25T17:05:43Z
[ "python" ]
Let's say I have the following class ``` class Parent(object): Options = { 'option1': 'value1', 'option2': 'value2' } ``` And a subclass called Child ``` class Child(Parent): Options = Parent.Options.copy() Options.update({ 'option2': 'value2', 'option3': 'value3' }) ...
One way would be to use keyword arguments to dict to specify additional keys: ``` Parent.options = dict( option1='value1', option2='value2', ) Child.options = dict(Parent.options, option2='value2a', option3='value3', ) ``` If you want to get fancier, then using the descriptor protocol you can create ...
A neat way of extending a class attribute in subclasses
907,324
15
2009-05-25T16:28:54Z
907,476
19
2009-05-25T17:25:19Z
[ "python" ]
Let's say I have the following class ``` class Parent(object): Options = { 'option1': 'value1', 'option2': 'value2' } ``` And a subclass called Child ``` class Child(Parent): Options = Parent.Options.copy() Options.update({ 'option2': 'value2', 'option3': 'value3' }) ...
Semantically equivalent to your code but arguably neater: ``` class Child(Parent): Options = dict(Parent.Options, option2='value2', option3='value3') ``` Remember, "life is better without braces", and by calling `dict` explicitly you can often avoid braces (and extra quotes around keys that are constan...
European date input in Django Admin
907,351
6
2009-05-25T16:42:52Z
8,860,276
8
2012-01-14T05:03:44Z
[ "python", "django", "date", "django-admin" ]
Django has a DATE\_FORMAT and a DATE\_TIME\_FORMAT options that allow us to choose which format to use when viewing dates, but doesn't apparently let me change the input format for the date when editing or adding in the Django Admin. The default for the admin is: YYYY-MM-DD But would be awesome to use: DD-MM-YYYY Is...
There is an official way to do this now since the closing of [Django ticket 6483](https://code.djangoproject.com/ticket/6483) & release of Django 1.2. If you have [`USE_L10N`](https://docs.djangoproject.com/en/1.3/ref/settings/#std%3asetting-USE_L10N) set to `False`, what you should do is specify the [`DATE_INPUT_FORM...
Generating file to download with Django
908,258
76
2009-05-25T22:26:01Z
908,266
8
2009-05-25T22:29:21Z
[ "python", "django" ]
Is it possible to make a zip archive and offer it to download, but still not save a file to the hard drive?
Yes, you can use the [zipfile module](http://www.python.org/doc/2.5.2/lib/zipfile-objects.html), [zlib module](http://www.python.org/doc/2.5.2/lib/module-zlib.html) or other [compression modules](http://www.python.org/doc/2.5.2/lib/archiving.html) to create a zip archive in memory. You can make your view write the zip ...
Generating file to download with Django
908,258
76
2009-05-25T22:26:01Z
908,293
24
2009-05-25T22:42:00Z
[ "python", "django" ]
Is it possible to make a zip archive and offer it to download, but still not save a file to the hard drive?
You'll be happier creating a temporary file. This saves a lot of memory. When you have more than one or two users concurrently, you'll find the memory saving is very, very important. You can, however, write to a [StringIO](http://docs.python.org/library/stringio.html) object. ``` >>> import zipfile >>> import StringI...
Generating file to download with Django
908,258
76
2009-05-25T22:26:01Z
909,088
95
2009-05-26T05:53:30Z
[ "python", "django" ]
Is it possible to make a zip archive and offer it to download, but still not save a file to the hard drive?
To trigger a download you need to set `Content-Disposition` header: ``` from django.http import HttpResponse from wsgiref.util import FileWrapper # generate the file response = HttpResponse(FileWrapper(myfile.getvalue()), content_type='application/zip') response['Content-Disposition'] = 'attachment; filename=myfile.z...
How to write binary data in stdout in python 3?
908,331
32
2009-05-25T23:04:05Z
908,440
51
2009-05-26T00:09:34Z
[ "python", "python-3.x" ]
In python 2.x I could do this: ``` import sys, array a = array.array('B', range(100)) a.tofile(sys.stdout) ``` Now however, I get a `TypeError: can't write bytes to text stream`. Is there some secret encoding that I should use?
A better way: ``` import sys sys.stdout.buffer.write(b"some binary data") ```
Python Getting date online?
908,550
2
2009-05-26T01:21:57Z
908,649
24
2009-05-26T02:04:50Z
[ "python" ]
How can I get the current date, month & year online using Python? Thanks! EDIT-By this I mean, rather than getting it from the computer's date-visit a website & get it, so it doesn't rely on the computer.
So thinking about the "would be so trivial" part I went ahead and just made [a google app engine web app](http://just-the-time.appspot.com/) -- when you visit it, it returns a simple response claiming to be HTML but actually just a string such as `2009-05-26 02:01:12 UTC\n`. Any feature requests?-)
How can I mine an XML document with awk, Perl, or Python?
909,062
3
2009-05-26T05:35:57Z
909,076
7
2009-05-26T05:47:28Z
[ "python", "xml", "perl", "awk" ]
I have a XML file with the following data format: ``` <net NetName="abc" attr1="123" attr2="234" attr3="345".../> <net NetName="cde" attr1="456" attr2="567" attr3="678".../> .... ``` Can anyone tell me how could I data mine the XML file using an awk one-liner? For example, I would like to know attr3 of abc. It will r...
In general, [you don't](http://stackoverflow.com/questions/701166/can-you-provide-some-examples-of-why-it-is-hard-to-parse-xml-and-html-with-a-rege). XML/HTML parsing is hard enough without trying to do it concisely, and while you may be able to hack together a solution that succeeds with a limited subset of XML, event...
How can I mine an XML document with awk, Perl, or Python?
909,062
3
2009-05-26T05:35:57Z
909,363
7
2009-05-26T07:23:43Z
[ "python", "xml", "perl", "awk" ]
I have a XML file with the following data format: ``` <net NetName="abc" attr1="123" attr2="234" attr3="345".../> <net NetName="cde" attr1="456" attr2="567" attr3="678".../> .... ``` Can anyone tell me how could I data mine the XML file using an awk one-liner? For example, I would like to know attr3 of abc. It will r...
I have written a tool called `xml_grep2`, based on [XML::LibXML](http://search.cpan.org/dist/XML-LibXML), the perl interface to [libxml2](http://xmlsoft.org). You would find the value you're looking for by doing this: ``` xml_grep2 -t '//net[@NetName="abc"]/@attr3' to_grep.xml ``` The tool can be found at <http://xm...
Why is the compiler package discontinued in Python 3?
909,092
29
2009-05-26T05:54:30Z
909,172
29
2009-05-26T06:24:50Z
[ "python", "compiler-construction", "python-3.x" ]
I was just pleasantly surprised to came across the documentation of [Python's compiler package](http://docs.python.org/library/compiler), but noticed that it's gone in Python 3.0, without any clear replacement or explanation. I can't seem to find any discussion on python-dev about how this decision was made - does any...
I believe the functionality is now built in: * [compile](http://docs.python.org/3/library/functions.html#compile) * [ast](http://docs.python.org/3.3/library/ast.html)
on my local Windows machine, how do i write a script to download a comic strip every day and email it to myself?
909,618
5
2009-05-26T08:36:43Z
910,031
8
2009-05-26T10:36:14Z
[ "php", "python", "ruby", "scheduled-tasks" ]
on my local Windows machine, how do i write a script to download a comic strip every day and email it to myself? such as <http://comics.com/peanuts/> **Update**: i know how to download the image as a file. the hard part is how to email it from my local Windows machine.
This depends how precise you want to be. Downloading the entire web page wouldn't be too challenging - using wget, as Earwicker mentions above. If you want the actual image file of the comic downloaded, you would need a bit more in your arsenal. In Python - because that's what I know best - I would imagine you'd need ...
Windows Authentication with Python and urllib2
909,658
10
2009-05-26T08:48:09Z
910,023
13
2009-05-26T10:34:05Z
[ "python", "urllib2" ]
I want to grab some data off a webpage that requires my windows username and password. So far, I've got: ``` opener = build_opener() try: page = opener.open("http://somepagewhichneedsmywindowsusernameandpassword/") print page except URLError: print "Oh noes." ``` Is this supported by urllib2? I've found ...
Assuming you are writing your client code on Windows and need seamless NTLM authentication then you should read Mark Hammond's [Hooking in NTLM](http://mail.python.org/pipermail/python-win32/2008-June/007722.html) post from the python-win32 mailing list which essentially answers the same question. This points at the ss...
Resize fields in Django Admin
910,169
77
2009-05-26T11:16:16Z
911,915
40
2009-05-26T17:57:49Z
[ "python", "django", "django-models", "django-admin" ]
Django tends to fill up horizontal space when adding or editing entries on the admin, but, in some cases, is a real waste of space, when, i.e., editing a date field, 8 characters wide, or a CharField, also 6 or 8 chars wide, and then the edit box goes up to 15 or 20 chars. How can I tell the admin how wide a textbox s...
You can set arbitrary HTML attributes on a widget using its ["attrs" property](http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs). You can do this in the Django admin using formfield\_for\_dbfield: ``` class MyModelAdmin(admin.ModelAdmin): def formfield_for_dbfield(self, db_field, **...
Resize fields in Django Admin
910,169
77
2009-05-26T11:16:16Z
912,661
19
2009-05-26T20:45:00Z
[ "python", "django", "django-models", "django-admin" ]
Django tends to fill up horizontal space when adding or editing entries on the admin, but, in some cases, is a real waste of space, when, i.e., editing a date field, 8 characters wide, or a CharField, also 6 or 8 chars wide, and then the edit box goes up to 15 or 20 chars. How can I tell the admin how wide a textbox s...
A quick and dirty option is to simply provide a custom template for the model in question. If you create a template named `admin/<app label>/<class name>/change_form.html` then the admin will use that template instead of the default. That is, if you've got a model named `Person` in an app named `people`, you'd create ...
Resize fields in Django Admin
910,169
77
2009-05-26T11:16:16Z
913,565
9
2009-05-27T01:36:50Z
[ "python", "django", "django-models", "django-admin" ]
Django tends to fill up horizontal space when adding or editing entries on the admin, but, in some cases, is a real waste of space, when, i.e., editing a date field, 8 characters wide, or a CharField, also 6 or 8 chars wide, and then the edit box goes up to 15 or 20 chars. How can I tell the admin how wide a textbox s...
If you want to change the attributes on a per-field instance, you can add the "attrs" property directly in to your form entries. for example: ``` class BlogPostForm(forms.ModelForm): title = forms.CharField(label='Title:', max_length=128) body = forms.CharField(label='Post:', max_length=2000, widget=...
Resize fields in Django Admin
910,169
77
2009-05-26T11:16:16Z
1,744,292
129
2009-11-16T19:24:46Z
[ "python", "django", "django-models", "django-admin" ]
Django tends to fill up horizontal space when adding or editing entries on the admin, but, in some cases, is a real waste of space, when, i.e., editing a date field, 8 characters wide, or a CharField, also 6 or 8 chars wide, and then the edit box goes up to 15 or 20 chars. How can I tell the admin how wide a textbox s...
You should use [ModelAdmin.formfield\_overrides](http://docs.djangoproject.com/en/dev/ref/contrib/admin/). It is quite easy - in `admin.py`, define: ``` class YourModelAdmin(admin.ModelAdmin): formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size':'20'})}, models.TextField: {...
Resize fields in Django Admin
910,169
77
2009-05-26T11:16:16Z
2,137,240
7
2010-01-26T02:48:20Z
[ "python", "django", "django-models", "django-admin" ]
Django tends to fill up horizontal space when adding or editing entries on the admin, but, in some cases, is a real waste of space, when, i.e., editing a date field, 8 characters wide, or a CharField, also 6 or 8 chars wide, and then the edit box goes up to 15 or 20 chars. How can I tell the admin how wide a textbox s...
I had a similar problem with TextField. I'm using Django 1.0.2 and wanted to change the default value for 'rows' in the associated textarea. formfield\_overrides doesn't exist in this version. Overriding formfield\_for\_dbfield worked but I had to do it for each of my ModelAdmin subclasses or it would result in a recur...
Resize fields in Django Admin
910,169
77
2009-05-26T11:16:16Z
21,766,384
13
2014-02-13T21:56:18Z
[ "python", "django", "django-models", "django-admin" ]
Django tends to fill up horizontal space when adding or editing entries on the admin, but, in some cases, is a real waste of space, when, i.e., editing a date field, 8 characters wide, or a CharField, also 6 or 8 chars wide, and then the edit box goes up to 15 or 20 chars. How can I tell the admin how wide a textbox s...
**To change the width for a specific field.** Made via [ModelAdmin.get\_form](https://docs.djangoproject.com/en/1.5/ref/contrib/admin/#django.contrib.admin.ModelAdmin.get_form): ``` class YourModelAdmin(admin.ModelAdmin): def get_form(self, request, obj=None, **kwargs): form = super(YourModelAdmin, self)....
Django objects change model field
910,287
2
2009-05-26T11:44:43Z
911,863
10
2009-05-26T17:41:35Z
[ "python", "django", "django-models" ]
This doesn't work: ``` >>> pa = Person.objects.all() >>> pa[2].nickname u'arst' >>> pa[2].nickname = 'something else' >>> pa[2].save() >>> pa[2].nickname u'arst' ``` But it works if you take ``` p = Person.objects.get(pk=2) ``` and change the nick. Why so.
``` >>> type(Person.objects.all()) <class 'django.db.models.query.QuerySet'> >>> pa = Person.objects.all() # Not evaluated yet - lazy >>> type(pa) <class 'django.db.models.query.QuerySet'> ``` DB queried to give you a Person object ``` >>> pa[2] ``` DB queried again to give you yet another Person object. ``` >>> p...
Send an xmpp message using a python library
910,737
11
2009-05-26T13:39:08Z
912,629
38
2009-05-26T20:36:32Z
[ "python", "xmpp" ]
How can I send an XMPP message using one of the following Python libraries: wokkel, xmpppy, or jabber.py ? I think I am aware of the pseudo-code, but so far have not been able to get one running correctly. This is what I have tried so far: * Call some API and pass the servername and port number to connect to that ser...
This is the simplest possible xmpp client. It will send a 'hello :)' message. I'm using [`xmpppy`](https://pypi.python.org/pypi/xmpppy) in the example. And connecting to gtalk server. I think the example is self-explanatory: ``` import xmpp username = 'username' passwd = 'password' to='[email protected]' msg='hello :)...
Django/Python EnvironmentError?
911,085
2
2009-05-26T14:45:21Z
911,176
12
2009-05-26T15:04:41Z
[ "python", "django", "django-syncdb" ]
I am getting an error when I try to use `syncdb`: ``` python manage.py syncdb ``` Error message: ``` File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 83, in __init__ raise EnvironmentError, "Could not import settings '%s' (Is it on sys.path? Does it have syntax errors?): %s" % (self.SETTIN...
Your trace states: ``` Import by filename is not supported. ``` Which might indicate that you try to import (or maybe set the DJANGO\_SETTINGS\_MODULE) to the full python filename, where it should be a module path: `your.module.settings` You could also try to specify your DJANGO\_SETTINGS\_MODULE directly from comma...
Python: Inheriting from Built-In Types
911,375
2
2009-05-26T15:43:52Z
911,413
9
2009-05-26T15:53:07Z
[ "python", "oop", "graph" ]
I have a question concerning subtypes of built-in types and their constructors. I want a class to inherit both from tuple and from a custom class. Let me give you the concrete example. I work a lot with graphs, meaning nodes connected with edges. I am starting to do some work on my own graph framework. There is a cla...
Since tuples are immutable, you need to override the \_\_new\_\_ method as well. See <http://www.python.org/download/releases/2.2.3/descrintro/>#\_\_new\_\_ ``` class GraphElement: def __init__(self, graph): pass class Edge(GraphElement, tuple): def __new__(cls, graph, (source, target)): retur...
gnuplot vs Matplotlib
911,655
57
2009-05-26T16:49:02Z
911,754
16
2009-05-26T17:09:47Z
[ "python", "logging", "matplotlib", "gnuplot", "graphing" ]
I've started on a project graphing [Tomcat](http://en.wikipedia.org/wiki/Apache_Tomcat) logs using [gnuplot-py](http://gnuplot-py.sourceforge.net/), specifically correlating particular requests with memory allocation and garbage collection. What is the collective wisdom on gnuplot-py vs [Matplotlib](http://matplotlib.s...
`matplotlib` has pretty good documentation, and seems to be quite stable. The plots it produces are beautiful - "publication quality" for sure. Due to the good documentation and the amount of example code available online, it's easy to learn and use, and I don't think you'll have much trouble translating `gnuplot` code...
gnuplot vs Matplotlib
911,655
57
2009-05-26T16:49:02Z
911,765
36
2009-05-26T17:12:05Z
[ "python", "logging", "matplotlib", "gnuplot", "graphing" ]
I've started on a project graphing [Tomcat](http://en.wikipedia.org/wiki/Apache_Tomcat) logs using [gnuplot-py](http://gnuplot-py.sourceforge.net/), specifically correlating particular requests with memory allocation and garbage collection. What is the collective wisdom on gnuplot-py vs [Matplotlib](http://matplotlib.s...
* you can check the [documentation](http://matplotlib.sourceforge.net/contents.html) yourself. I find it quite comprehensive. * I have very little experience with gnuplot-py, so I can not say. * Matplotlib is written in and designed specifically for Python, so it fits very nicely with Python idioms and such. * Matplotl...
gnuplot vs Matplotlib
911,655
57
2009-05-26T16:49:02Z
911,779
7
2009-05-26T17:15:51Z
[ "python", "logging", "matplotlib", "gnuplot", "graphing" ]
I've started on a project graphing [Tomcat](http://en.wikipedia.org/wiki/Apache_Tomcat) logs using [gnuplot-py](http://gnuplot-py.sourceforge.net/), specifically correlating particular requests with memory allocation and garbage collection. What is the collective wisdom on gnuplot-py vs [Matplotlib](http://matplotlib.s...
I have played with both, and I like Matplotlib much better in terms of Python integration, options, and quality of graphs/plots.
gnuplot vs Matplotlib
911,655
57
2009-05-26T16:49:02Z
1,960,904
12
2009-12-25T10:01:31Z
[ "python", "logging", "matplotlib", "gnuplot", "graphing" ]
I've started on a project graphing [Tomcat](http://en.wikipedia.org/wiki/Apache_Tomcat) logs using [gnuplot-py](http://gnuplot-py.sourceforge.net/), specifically correlating particular requests with memory allocation and garbage collection. What is the collective wisdom on gnuplot-py vs [Matplotlib](http://matplotlib.s...
After using GNUplot (with my own Python wrapper) for a long time (and really not liking the 80s-looking output), I just started having a look at matplotlib. I must say I like it very much, the output looks really nice and the docs are high quality and extensive (although that also goes for GNUplot). The one thing I spe...
gnuplot vs Matplotlib
911,655
57
2009-05-26T16:49:02Z
23,883,352
17
2014-05-27T07:21:57Z
[ "python", "logging", "matplotlib", "gnuplot", "graphing" ]
I've started on a project graphing [Tomcat](http://en.wikipedia.org/wiki/Apache_Tomcat) logs using [gnuplot-py](http://gnuplot-py.sourceforge.net/), specifically correlating particular requests with memory allocation and garbage collection. What is the collective wisdom on gnuplot-py vs [Matplotlib](http://matplotlib.s...
## Matplotlib = ease of use, Gnuplot = performance I know this post is old and answered but I was passing by and wanted to put my two cents. Here is my conclusion: as said above, if you have a not-so-big data set, you should use Matplotlib. It's easier and looks better. However, if you need performance, I would recomm...
Extracting titles from PDF files?
911,672
9
2009-05-26T16:52:40Z
911,708
11
2009-05-26T16:58:14Z
[ "python", "pdf" ]
I want to write a script to rename downloaded papers with their titles automatically, I'm wondering if there is any library or tricks i can make use of? The PDFs are all generated by TeX and should have some 'formal' structures.
You could try to use [pyPdf](http://pybrary.net/pyPdf/) and [this example](http://blog.isnotworking.com/2006/08/extract-pdf-title-from-all-files-on.html). **for example:** ``` from pyPdf import PdfFileWriter, PdfFileReader def get_pdf_title(pdf_file_path): with open(pdf_file_path) as f: pdf_reader = PdfF...
detecting idle time using python
911,856
14
2009-05-26T17:39:35Z
912,223
16
2009-05-26T19:17:19Z
[ "python", "winapi" ]
How do I detect if the system is idle on Windows using Python (i.e. no keyboard or mouse activity). This has already been asked [before](http://stackoverflow.com/questions/217157/how-can-i-determine-the-display-idle-time-from-python-in-windows-linux-and-maco), but there doesn't seem to be a `GetLastInputInfo` in the `p...
``` from ctypes import Structure, windll, c_uint, sizeof, byref class LASTINPUTINFO(Structure): _fields_ = [ ('cbSize', c_uint), ('dwTime', c_uint), ] def get_idle_duration(): lastInputInfo = LASTINPUTINFO() lastInputInfo.cbSize = sizeof(lastInputInfo) windll.user32.GetLastInputInf...
Detect if a NumPy array contains at least one non-numeric value?
911,871
34
2009-05-26T17:43:47Z
913,499
49
2009-05-27T00:55:50Z
[ "python", "numpy" ]
I need to write a function which will detect if the input contains at least one value which is non-numeric. If a non-numeric value is found I will raise an error (because the calculation should only return a numeric value). The number of dimensions of the input array is not known in advance - the function should give t...
This should be faster than iterating and will work regardless of shape. ``` numpy.isnan(myarray).any() ``` Edit: 30x faster: ``` import timeit s = 'import numpy;a = numpy.arange(10000.).reshape((100,100));a[10,10]=numpy.nan' ms = [ 'numpy.isnan(a).any()', 'any(numpy.isnan(x) for x in a.flatten())'] for m in ...
Class attributes with a "calculated" name
912,412
3
2009-05-26T19:57:28Z
912,428
11
2009-05-26T20:03:41Z
[ "python", "exec", "class-attributes" ]
When defining class attributes through "calculated" names, as in: ``` class C(object): for name in (....): exec("%s = ..." % (name,...)) ``` is there a different way of handling the numerous attribute definitions than by using an exec? getattr(C, name) does not work because C is not defined, during class ...
How about: ``` class C(object): blah blah for name in (...): setattr(C, name, "....") ``` That is, do the attribute setting after the definition.
How do I pass lots of variables to and from a function in Python?
912,526
3
2009-05-26T20:20:05Z
912,558
15
2009-05-26T20:25:40Z
[ "python", "pass-by-reference", "pass-by-value" ]
I do scientific programming, and often want to show users prompts and variable pairs, let them edit the variables, and then do the calulations with the new variables. I do this so often, that I wrote a wxPython class to move this code out of the main program. You set up a list for each variable with the type of the var...
The simplest thing to do would be to create a class. Instead of dealing with a list of variables, the class will have attributes. Then you just use a single instance of the class.
How do I pass lots of variables to and from a function in Python?
912,526
3
2009-05-26T20:20:05Z
912,578
9
2009-05-26T20:29:08Z
[ "python", "pass-by-reference", "pass-by-value" ]
I do scientific programming, and often want to show users prompts and variable pairs, let them edit the variables, and then do the calulations with the new variables. I do this so often, that I wrote a wxPython class to move this code out of the main program. You set up a list for each variable with the type of the var...
There are two decent options that come to mind. The first is to use a dictionary to gather all the variables in one place: ``` d = {} d['var1'] = [1,2,3] d['var2'] = 'asdf' foo(d) ``` The second is to use a class to bundle all the arguments. This could be something as simple as: ``` class Foo(object): pass f = ...
Using subprocess to run Python script on Windows
912,830
31
2009-05-26T21:22:12Z
912,847
45
2009-05-26T21:26:10Z
[ "python", "windows", "subprocess" ]
Is there a simple way to run a Python script on Windows/Linux/OS X? On the latter two, `subprocess.Popen("/the/script.py")` works, but on Windows I get the following error: ``` Traceback (most recent call last): File "test_functional.py", line 91, in test_functional log = tvnamerifiy(tmp) File "test_functiona...
Just found `sys.executable` - the full path to the current Python executable, which can be used to run the script (instead of relying on the shbang, which obviously doesn't work on Windows) ``` import sys import subprocess theproc = subprocess.Popen([sys.executable, "myscript.py"]) theproc.communicate() ```
Using subprocess to run Python script on Windows
912,830
31
2009-05-26T21:22:12Z
1,036,086
15
2009-06-24T01:48:17Z
[ "python", "windows", "subprocess" ]
Is there a simple way to run a Python script on Windows/Linux/OS X? On the latter two, `subprocess.Popen("/the/script.py")` works, but on Windows I get the following error: ``` Traceback (most recent call last): File "test_functional.py", line 91, in test_functional log = tvnamerifiy(tmp) File "test_functiona...
How about this: ``` import sys import subprocess theproc = subprocess.Popen("myscript.py", shell = True) theproc.communicate() # ^^^^^^^^^^^^ ``` This tells `subprocess` to use the OS shell to open your script, and works on anything that you can just run in cmd.exe. Additionally, this will search ...
Dynamic Finders and Method Missing in Python
913,020
5
2009-05-26T22:10:42Z
913,438
7
2009-05-27T00:34:53Z
[ "python", "google-app-engine", "web-applications" ]
I'm trying to implement something like Rails dynamic-finders in Python (for webapp/GAE). The dynamic finders work like this: * Your Person has some fields: name, age and email. * Suppose you want to find all the users whose name is "Robot". The Person class has a method called "find\_by\_name" that receives the name ...
There's really no need to use GQL here - it just complicates matters. Here's a simple implementation: ``` class FindableModel(db.Model): def __getattr__(self, name): if not name.startswith("find_by_"): raise AttributeError(name) field = name[len("find_by_"):] return lambda value: self.all().filter(...
Is it possible to install python 3 and 2.6 on same PC?
913,204
3
2009-05-26T23:02:23Z
913,216
9
2009-05-26T23:06:24Z
[ "python", "python-3.x" ]
How would I do this? The reason being I wanted to try some pygame out, but I have python 3 installed currently and have been learning with that. I'm also interested in trying out wxpython or something like that, but I haven't looked at their compatibilities yet. EDIT:: im on a windows vista 64-bit
If you are on Windows, then just install another version of Python using the installer. It would be installed into another directory. Then if you install other packages using the installer, it would ask you for which python installation to apply. If you use installation from source or easy\_install, then just make sur...
Django forms, inheritance and order of form fields
913,589
53
2009-05-27T01:46:50Z
1,133,470
94
2009-07-15T19:29:22Z
[ "python", "django", "django-forms" ]
I'm using Django forms in my website and would like to control the order of the fields. Here's how I define my forms: ``` class edit_form(forms.Form): summary = forms.CharField() description = forms.CharField(widget=forms.TextArea) class create_form(edit_form): name = forms.CharField() ``` The name is ...
I had this same problem and I found another technique for reordering fields in the [Django CookBook](http://code.djangoproject.com/wiki/CookBookNewFormsFieldOrdering): ``` class EditForm(forms.Form): summary = forms.CharField() description = forms.CharField(widget=forms.TextArea) class CreateForm(EditForm): ...
Django forms, inheritance and order of form fields
913,589
53
2009-05-27T01:46:50Z
2,619,586
11
2010-04-12T02:38:58Z
[ "python", "django", "django-forms" ]
I'm using Django forms in my website and would like to control the order of the fields. Here's how I define my forms: ``` class edit_form(forms.Form): summary = forms.CharField() description = forms.CharField(widget=forms.TextArea) class create_form(edit_form): name = forms.CharField() ``` The name is ...
I used the solution posted by Selene but found that it removed all fields which weren't assigned to keyOrder. The form that I'm subclassing has a lot of fields so this didn't work very well for me. I coded up this function to solve the problem using akaihola's answer, but if you want it to work like Selene's all you ne...
Django forms, inheritance and order of form fields
913,589
53
2009-05-27T01:46:50Z
8,476,642
7
2011-12-12T15:26:51Z
[ "python", "django", "django-forms" ]
I'm using Django forms in my website and would like to control the order of the fields. Here's how I define my forms: ``` class edit_form(forms.Form): summary = forms.CharField() description = forms.CharField(widget=forms.TextArea) class create_form(edit_form): name = forms.CharField() ``` The name is ...
You could also create a decorator to order fields (inspired by Joshua's solution): ``` def order_fields(*field_list): def decorator(form): original_init = form.__init__ def init(self, *args, **kwargs): original_init(self, *args, **kwargs) for field in field_list[::-1...
Django forms, inheritance and order of form fields
913,589
53
2009-05-27T01:46:50Z
23,615,361
9
2014-05-12T17:35:17Z
[ "python", "django", "django-forms" ]
I'm using Django forms in my website and would like to control the order of the fields. Here's how I define my forms: ``` class edit_form(forms.Form): summary = forms.CharField() description = forms.CharField(widget=forms.TextArea) class create_form(edit_form): name = forms.CharField() ``` The name is ...
It appears that at some point the underlying structure of field order was changed from a django specific `SordedDict` to a python standard `OrderedDict` Thus, in 1.7 I had to do the following: ``` from collections import OrderedDict class MyForm(forms.Form): def __init__(self, *args, **kwargs): super(My...
django error 'too many values to unpack'
913,590
13
2009-05-27T01:46:50Z
8,206,621
12
2011-11-21T02:24:40Z
[ "python", "django", "sqlite" ]
I'm learning Django by building a simple recipes app. I have a 1 table model using the 'choices' field option for recipe categories rather than using a 2nd 'categories' table and a foreign key relationship. So i created db table via syncdb and then loaded table with test data. When i go to admin and click on the 'Recip...
**Edit: Updated in light of kibibu's correction.** I have encountered what I believe is this same error, producing the message: ``` Caught ValueError while rendering: too many values to unpack ``` My form class was as follows: ``` class CalcForm(forms.Form): item = forms.ChoiceField(choices=(('17815', '17816'))...
What is the underlying data structure for Python lists?
914,233
44
2009-05-27T06:22:56Z
914,248
21
2009-05-27T06:29:28Z
[ "python", "list", "data-structures" ]
What is the typical underlying data structure used to implement Python's built-in list data type?
CPython: ``` typedef struct { PyObject_VAR_HEAD /* Vector of pointers to list elements. list[0] is ob_item[0], etc. */ PyObject **ob_item; /* ob_item contains space for 'allocated' elements. The number * currently in use is ob_size. * Invariants: * 0 <= ob_size <= allocated *...
What is the underlying data structure for Python lists?
914,233
44
2009-05-27T06:22:56Z
914,271
9
2009-05-27T06:35:03Z
[ "python", "list", "data-structures" ]
What is the typical underlying data structure used to implement Python's built-in list data type?
In the [Jython implementation](http://fisheye3.atlassian.com/browse/jython/trunk/jython/src/org/python/core/PyList.java?r1=6244&r2=6257&u=-1&ignore=&k=), it's an `ArrayList<PyObject>`.
What is the underlying data structure for Python lists?
914,233
44
2009-05-27T06:22:56Z
915,593
34
2009-05-27T13:04:07Z
[ "python", "list", "data-structures" ]
What is the typical underlying data structure used to implement Python's built-in list data type?
> List objects are implemented as > arrays. They are optimized for fast > fixed-length operations and incur O(n) > memory movement costs for pop(0) and > insert(0, v) operations which change > both the size and position of the > underlying data representation. See also: <http://docs.python.org/library/collections.html...
best practice for user preferences in $HOME in Python
914,675
3
2009-05-27T08:49:25Z
914,812
8
2009-05-27T09:26:06Z
[ "python", "preferences" ]
For some small programs in Python, I would like to set, store and retrieve user preferences in a file in a portable (multi-platform) way. I am thinking about a very simple ConfigParser file like "~/.program" or "~/.program/program.cfg". Is `os.path.expanduser()` the best way for achieving this or is there something m...
``` os.path.expanduser("~") ``` is more portable than ``` os.environ['HOME'] ``` so it should be ok to use the first.
Python: Looping through all but the last item of a list
914,715
61
2009-05-27T08:59:35Z
914,733
136
2009-05-27T09:04:36Z
[ "python" ]
I would like to loop through a list checking each item against the one following it. Is there a way I can loop through all but the last item using for x in y? I would prefer to do it without using indexes if I can. **Note** freespace answered my actual question, which is why I accepted the answer, but SilentGhost an...
``` for x in y[:-1] ``` If `y` is a generator, then the above will not work.
Python: Looping through all but the last item of a list
914,715
61
2009-05-27T08:59:35Z
914,786
15
2009-05-27T09:18:47Z
[ "python" ]
I would like to loop through a list checking each item against the one following it. Is there a way I can loop through all but the last item using for x in y? I would prefer to do it without using indexes if I can. **Note** freespace answered my actual question, which is why I accepted the answer, but SilentGhost an...
If you want to get all the elements in the sequence pair wise, use this approach (the pairwise function is from the examples in the itertools module). ``` from itertools import tee, izip, chain def pairwise(seq): a,b = tee(seq) b.next() return izip(a,b) for current_item, next_item in pairwise(y): if ...
Python: Looping through all but the last item of a list
914,715
61
2009-05-27T08:59:35Z
914,815
32
2009-05-27T09:26:29Z
[ "python" ]
I would like to loop through a list checking each item against the one following it. Is there a way I can loop through all but the last item using for x in y? I would prefer to do it without using indexes if I can. **Note** freespace answered my actual question, which is why I accepted the answer, but SilentGhost an...
the easiest way to compare the sequence item with the following: ``` for i, j in zip(a, a[1:]): # compare i (the current) to j (the following) ```
How to convert specific character sequences in a string to upper case using Python?
915,391
2
2009-05-27T12:16:37Z
915,460
11
2009-05-27T12:29:50Z
[ "python" ]
I am looking to accomplish the following and am wondering if anyone has a suggestion as to how best go about it. I have a string, say 'this-is,-toronto.-and-this-is,-boston', and I would like to convert all occurrences of ',-[a-z]' to ',-[A-Z]'. In this case the result of the conversion would be 'this-is,-Toronto.-and...
re.sub can take a function which returns the replacement string: ``` import re s = 'this-is,-toronto.-and-this-is,-boston' t = re.sub(',-[a-z]', lambda x: x.group(0).upper(), s) print t ``` prints ``` this-is,-Toronto.-and-this-is,-Boston ```
django auth User truncating email field
915,910
9
2009-05-27T14:06:33Z
916,176
12
2009-05-27T14:49:41Z
[ "python", "mysql", "django", "authentication" ]
I have an issue with the django.contrib.auth User model where the email max\_length is 75. I am receiving email addresses that are longer than 75 characters from the facebook api, and I need to (would really like to) store them in the user for continuity among users that are from facebook connect and others. I am abl...
EmailField 75 chars length is hardcoded in django. You can fix this like that: ``` from django.db.models.fields import EmailField def email_field_init(self, *args, **kwargs): kwargs['max_length'] = kwargs.get('max_length', 200) CharField.__init__(self, *args, **kwargs) EmailField.__init__ = email_field_init ``` b...
Would it be possible to write a 3D game as large as World of Warcraft in pure Python?
916,663
10
2009-05-27T16:16:05Z
916,686
14
2009-05-27T16:19:57Z
[ "python", "3d", "direct3d" ]
Would it be possible to write a 3D game as large as World of Warcraft in pure Python? Assuming the use of DirectX / D3D bindings or OpenGL bindings. If not, what would be the largest hold-up to doing such a project in Python? I know games tend to fall into the realm of C and C++ but sometimes people do things out of h...
Yes. How it will perform is another question. A good development pattern would be to develop it in pure python, and then profile it, and rewrite performance-critical bottlenecks, either in C/C++/Cython or even python itself but with more efficient code.
Would it be possible to write a 3D game as large as World of Warcraft in pure Python?
916,663
10
2009-05-27T16:16:05Z
916,701
7
2009-05-27T16:21:14Z
[ "python", "3d", "direct3d" ]
Would it be possible to write a 3D game as large as World of Warcraft in pure Python? Assuming the use of DirectX / D3D bindings or OpenGL bindings. If not, what would be the largest hold-up to doing such a project in Python? I know games tend to fall into the realm of C and C++ but sometimes people do things out of h...
Technically, anything is possible in any Turing Complete programming language. Practically though, you will run into trouble making the networking stack out of a high level language, because the server will have to be VERY fast to handle so many players. The gaming side of things on the client, there should be no pro...
Would it be possible to write a 3D game as large as World of Warcraft in pure Python?
916,663
10
2009-05-27T16:16:05Z
916,740
14
2009-05-27T16:30:00Z
[ "python", "3d", "direct3d" ]
Would it be possible to write a 3D game as large as World of Warcraft in pure Python? Assuming the use of DirectX / D3D bindings or OpenGL bindings. If not, what would be the largest hold-up to doing such a project in Python? I know games tend to fall into the realm of C and C++ but sometimes people do things out of h...
While I don't know all the technical details of World of Warcraft, I would say that an MMO of its size could be built in [Stackless Python](http://en.wikipedia.org/wiki/Stackless%5FPython). EVE Online uses it and they have one server for 200,000 users.
Would it be possible to write a 3D game as large as World of Warcraft in pure Python?
916,663
10
2009-05-27T16:16:05Z
916,753
7
2009-05-27T16:32:33Z
[ "python", "3d", "direct3d" ]
Would it be possible to write a 3D game as large as World of Warcraft in pure Python? Assuming the use of DirectX / D3D bindings or OpenGL bindings. If not, what would be the largest hold-up to doing such a project in Python? I know games tend to fall into the realm of C and C++ but sometimes people do things out of h...
The game [Minions of Mirth](http://minionsofmirth.com/) is a full MMO more or less on the scale of WoW, and was done [mostly in Python](http://www.garagegames.com/community/forums/viewthread/37703). The client side used the Torque Game Engine, which is written in C++, but the server code and behaviours were all Python.
How does Python OOP compare to PHP OOP?
916,962
15
2009-05-27T17:09:28Z
916,974
21
2009-05-27T17:12:51Z
[ "php", "python", "oop", "comparison" ]
I'm basically wondering if Python has any OOP shortcomings like PHP does. PHP has been developing their OOP practices for the last few versions. It's getting better in PHP but it's still not perfect. I'm new to Python and I'm just wondering if Python's OOP support is better or just comparable. If there are some issues...
I would say that Python's OOP support is much better given the fact that it was introduced into the language in its infancy as opposed to PHP which bolted OOP onto an existing procedural model.
How does Python OOP compare to PHP OOP?
916,962
15
2009-05-27T17:09:28Z
917,005
8
2009-05-27T17:21:57Z
[ "php", "python", "oop", "comparison" ]
I'm basically wondering if Python has any OOP shortcomings like PHP does. PHP has been developing their OOP practices for the last few versions. It's getting better in PHP but it's still not perfect. I'm new to Python and I'm just wondering if Python's OOP support is better or just comparable. If there are some issues...
Python's OOP support is very strong; it does allow multiple inheritance, and everything is manipulable as a first-class object (including classes, methods, etc). Polymorphism is expressed through duck typing. For example, you can iterate over a list, a tuple, a dictionary, a file, a web resource, and more all in the s...
How does Python OOP compare to PHP OOP?
916,962
15
2009-05-27T17:09:28Z
917,143
7
2009-05-27T17:56:20Z
[ "php", "python", "oop", "comparison" ]
I'm basically wondering if Python has any OOP shortcomings like PHP does. PHP has been developing their OOP practices for the last few versions. It's getting better in PHP but it's still not perfect. I'm new to Python and I'm just wondering if Python's OOP support is better or just comparable. If there are some issues...
One aspect of Python's OOP model that is unusual is its encapsulation mechanism. Basically, Python assumes that programmers don't do bad things, and so it doesn't go out of its way to any extent to protect private member variables or methods. It works by mangling names of members that begin with a two underscores and ...
Python equivalent of maplist?
916,978
11
2009-05-27T17:13:40Z
917,028
11
2009-05-27T17:29:30Z
[ "python", "functional-programming", "lisp" ]
What's the best Python equivalent of Common Lisp's `maplist` function? From the [maplist documentation](http://www.ai.mit.edu/projects/iiip/doc/CommonLISP/HyperSpec/Body/fun%5Fmapccm%5Fma%5Fistcm%5Fmapcon.html): > maplist is like mapcar except that > function is applied to successive > sublists of the lists. function ...
You can write a little function for that ``` def maplist(func, values): return [map(func, values[i:]) for i in xrange(len(values))] >>> maplist(lambda a: a* 2, [1,2,3]) [[2, 4, 6], [4, 6], [6]] ``` **[Edit]** if you want to apply the function on the sublists you can change the function to this: ``` def maplist...
Does Ruby have an equivalent of Python's twisted framework as a networking abstraction layer?
917,369
6
2009-05-27T18:44:57Z
917,538
7
2009-05-27T19:17:45Z
[ "python", "ruby-on-rails", "ruby", "twisted" ]
From my understanding, Python's twisted framework provides a higher-level abstraction for networking communications (?). I am looking for a Ruby equivalent of twisted to use in a Rails application.
Take a look at [EventMachine](http://eventmachine.rubyforge.org/). It's not as extensive as Twisted but it's built around the same concepts of event-driven network programming.
Relative paths in Python
918,154
71
2009-05-27T21:43:21Z
918,178
94
2009-05-27T21:47:50Z
[ "python", "relative-path", "path" ]
I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relati...
In the file that has the script, you want to do something like this: ``` import os dir = os.path.dirname(__file__) filename = os.path.join(dir, '/relative/path/to/file/you/want') ``` This will give you the absolute path to the file you're looking for. Note that if you're using setuptools, you should probably use its ...
Relative paths in Python
918,154
71
2009-05-27T21:43:21Z
9,768,491
33
2012-03-19T10:24:27Z
[ "python", "relative-path", "path" ]
I'm building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don't, however, have the absolute path to the directory where the templates are stored. I do have a relative path from the script but when I call the script it treats that as a path relati...
you need `os.path.realpath` (sample below adds the parent directory to your path) ``` import sys,os sys.path.append(os.path.realpath('..')) ```
Python unicode in Mac os X terminal
918,294
7
2009-05-27T22:17:54Z
918,364
8
2009-05-27T22:52:42Z
[ "python", "osx", "unicode", "terminal" ]
Can someone explain to me this odd thing: When in python shell I type the following Cyrillic string: ``` >>> print 'абвгд' абвгд ``` but when I type: ``` >>> print u'абвгд' Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode characte...
In addition to ensuring your OS X terminal is set to UTF-8, you may wish to set your python sys default encoding to UTF-8 or better. Create a file in `/Library/Python/2.5/site-packages` called `sitecustomize.py`. In this file put: ``` import sys sys.setdefaultencoding('utf-8') ``` The `setdefaultencoding` method is a...
Python unicode in Mac os X terminal
918,294
7
2009-05-27T22:17:54Z
918,425
16
2009-05-27T23:12:40Z
[ "python", "osx", "unicode", "terminal" ]
Can someone explain to me this odd thing: When in python shell I type the following Cyrillic string: ``` >>> print 'абвгд' абвгд ``` but when I type: ``` >>> print u'абвгд' Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode characte...
``` >>> print 'абвгд' абвгд ``` When you type in some characters, your terminal decides how these characters are represented to the application. Your terminal might give the characters to the application encoded as utf-8, ISO-8859-5 or even something that only your terminal understands. Python gets these cha...
Python unicode in Mac os X terminal
918,294
7
2009-05-27T22:17:54Z
9,930,894
12
2012-03-29T18:05:07Z
[ "python", "osx", "unicode", "terminal" ]
Can someone explain to me this odd thing: When in python shell I type the following Cyrillic string: ``` >>> print 'абвгд' абвгд ``` but when I type: ``` >>> print u'абвгд' Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeEncodeError: 'ascii' codec can't encode characte...
As of Python 2.6, you can use the environment variable `PYTHONIOENCODING` to tell Python that your terminal is UTF-8 capable. The easiest way to make this permanent is by adding the following line to your `~/.bash_profile`: ``` export PYTHONIOENCODING=utf-8 ``` ![Terminal.app showing unicode output from Python](http:...
Are asynchronous Django model queries possible?
918,298
18
2009-05-27T22:19:00Z
918,410
11
2009-05-27T23:07:42Z
[ "python", "mysql", "django", "multithreading", "django-models" ]
I'm new to Django, but the application that I have in mind might end up having URLs that look like this: ``` http://mysite/compare/id_1/id_2 ``` Where "id\_1" and "id\_2" are identifiers of two distinct Model objects. In the handler for "compare" I'd like to asynchronously, and in parallel, query and retrieve objects...
There aren't strictly asynchronous operations as you've described, but I think you can achieve the same effect by using django's [in\_bulk](http://docs.djangoproject.com/en/dev/ref/models/querysets/#in-bulk) query operator, which takes a list of ids to query. Something like this for the `urls.py`: ``` urlpatterns = p...
My python program executes faster than my java version of the same program. What gives?
918,359
15
2009-05-27T22:48:42Z
918,397
7
2009-05-27T23:04:37Z
[ "java", "python", "microbenchmark" ]
**Update: 2009-05-29** Thanks for all the suggestions and advice. **I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.** In the end I was able to make the java code the fastest. Lessons: * My example code below shows the insertion of primi...
It has generally been my experience that python programs run faster than java programs, despite the fact that java is a bit "lower level" language. Incidently, both languages are compiled into byte code (that's what those .pyc file are -- you can think of them as kind of like .class files). Both languages are byte-code...
My python program executes faster than my java version of the same program. What gives?
918,359
15
2009-05-27T22:48:42Z
918,409
7
2009-05-27T23:06:52Z
[ "java", "python", "microbenchmark" ]
**Update: 2009-05-29** Thanks for all the suggestions and advice. **I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.** In the end I was able to make the java code the fastest. Lessons: * My example code below shows the insertion of primi...
Another possible explanation is that sets in Python are implemented natively in C code, while HashSet's in Java are implemented in Java itself. So, sets in Python should be inherently much faster.
My python program executes faster than my java version of the same program. What gives?
918,359
15
2009-05-27T22:48:42Z
919,844
12
2009-05-28T08:46:54Z
[ "java", "python", "microbenchmark" ]
**Update: 2009-05-29** Thanks for all the suggestions and advice. **I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.** In the end I was able to make the java code the fastest. Lessons: * My example code below shows the insertion of primi...
I suspect that is that Python uses the integer value itself as its hash and the hashtable based implementation of set uses that value directly. From the comments in the [source](http://svn.python.org/view/python/trunk/Objects/dictobject.c?revision=72958&view=markup): > This isn't necessarily bad! To the contrary, in a...
My python program executes faster than my java version of the same program. What gives?
918,359
15
2009-05-27T22:48:42Z
919,966
20
2009-05-28T09:26:11Z
[ "java", "python", "microbenchmark" ]
**Update: 2009-05-29** Thanks for all the suggestions and advice. **I used your suggestions to make my production code execute 2.5 times faster on average than my best result a couple of days ago.** In the end I was able to make the java code the fastest. Lessons: * My example code below shows the insertion of primi...
You're not really testing Java vs. Python, you're testing `java.util.HashSet` using autoboxed Integers vs. Python's native set and integer handling. Apparently, the Python side in this particular microbenchmark is indeed faster. I tried replacing HashSet with `TIntHashSet` from [GNU trove](http://trove4j.sourceforge....
Case insensitive replace
919,056
74
2009-05-28T03:35:24Z
919,067
104
2009-05-28T03:39:13Z
[ "python", "string", "case-insensitive" ]
What's the easiest way to do a case-insensitive string replacement in Python?
The `string` type doesn't support this. You're probably best off using [the regular expression sub method](http://docs.python.org/library/re.html#re.RegexObject.sub) with the [re.IGNORECASE](http://docs.python.org/library/re.html#re.IGNORECASE) option. ``` >>> import re >>> insensitive_hippo = re.compile(re.escape('hi...
Case insensitive replace
919,056
74
2009-05-28T03:35:24Z
919,074
56
2009-05-28T03:41:04Z
[ "python", "string", "case-insensitive" ]
What's the easiest way to do a case-insensitive string replacement in Python?
``` import re pattern = re.compile("hello", re.IGNORECASE) pattern.sub("bye", "hello HeLLo HELLO") # 'bye bye bye' ```
Case insensitive replace
919,056
74
2009-05-28T03:35:24Z
9,709,563
16
2012-03-14T20:14:03Z
[ "python", "string", "case-insensitive" ]
What's the easiest way to do a case-insensitive string replacement in Python?
Very simple, in a single line: ``` import re re.sub("(?i)hello","bye", "hello HeLLo HELLO") #'bye bye bye' re.sub("(?i)he\.llo","bye", "he.llo He.LLo HE.LLO") #'bye bye bye' ``` Or, use the optional "flags" argument: ``` import re re.sub("hello", "bye", "hello HeLLo HELLO", flags=re.I) #'bye bye bye' re.sub("he\.llo...
Can a variable number of arguments be passed to a function?
919,680
180
2009-05-28T07:50:10Z
919,684
229
2009-05-28T07:51:54Z
[ "python" ]
In a similar way to using varargs in C or C++: ``` fn(a, b) fn(a, b, c, d, ...) ```
Yes. This is simple and works if you disregard keyword arguments: ``` def manyArgs(*arg): print "I was called with", len(arg), "arguments:", arg >>> manyArgs(1) I was called with 1 arguments: (1,) >>> manyArgs(1, 2,3) I was called with 3 arguments: (1, 2, 3) ``` As you can see, Python will give you a single tuple...
Can a variable number of arguments be passed to a function?
919,680
180
2009-05-28T07:50:10Z
919,720
146
2009-05-28T07:59:58Z
[ "python" ]
In a similar way to using varargs in C or C++: ``` fn(a, b) fn(a, b, c, d, ...) ```
Adding to unwinds post: You can send multiple key-value args too. ``` def myfunc(**kwargs): # kwargs is a dictionary. for k,v in kwargs.iteritems(): print "%s = %s" % (k, v) myfunc(abc=123, efh=456) # abc = 123 # efh = 456 ``` And you can mix the two: ``` def myfunc2(*args, **kwargs): for a in ...
Can a variable number of arguments be passed to a function?
919,680
180
2009-05-28T07:50:10Z
9,449,581
9
2012-02-26T00:56:32Z
[ "python" ]
In a similar way to using varargs in C or C++: ``` fn(a, b) fn(a, b, c, d, ...) ```
Adding to the other excellent posts. Sometimes you don't want to specify the number of arguments **and** want to use keys for them (the compiler will complain if one argument passed in a dictionary is not used in the method). ``` def manyArgs1(args): print args.a, args.b #note args.c is not used here def manyArgs2...
How to find a thread id in Python
919,897
68
2009-05-28T09:04:24Z
919,928
85
2009-05-28T09:13:40Z
[ "python", "multithreading" ]
I have a multi-threading Python program, and a utility function, writeLog(message), that writes out a timestamp followed by the message. Unfortunately, the resultant log file gives no indication of which thread is generating which message. I would like writeLog() to be able to add something to the message to identify ...
[`thread.get_ident()`](http://docs.python.org/library/threading.html#threading.Thread.ident) works, though `thread` is deprecated, or [`threading.current_thread()`](http://docs.python.org/library/threading.html#threading.current_thread) (or `threading.currentThread()` for Python < 2.6).
How to find a thread id in Python
919,897
68
2009-05-28T09:04:24Z
2,357,652
37
2010-03-01T17:19:18Z
[ "python", "multithreading" ]
I have a multi-threading Python program, and a utility function, writeLog(message), that writes out a timestamp followed by the message. Unfortunately, the resultant log file gives no indication of which thread is generating which message. I would like writeLog() to be able to add something to the message to identify ...
Using the [logging](http://docs.python.org/library/logging.html) module you can automatically add the current thread identifier in each log entry. Just use one of these [LogRecord](http://docs.python.org/library/logging.html#logging.LogRecord) mapping keys in your logger format string: > *%(thread)d :* Thread ID (if a...
Stuck on official Django Tutorial
919,927
3
2009-05-28T09:13:27Z
919,945
8
2009-05-28T09:18:32Z
[ "python", "django" ]
I am just started out learning Python and also started looking into Django a little bit. So I copied this piece of code from the tutorial: ``` # Create your models here. class Poll(models.Model): question = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __unicode...
You have three underscores before "unicode\_\_" on the Choice class, it should be only two like in your Poll class, like this: ``` def __unicode__(self): return u'%s' % self.choice ```
When to use While or the For in python
920,645
15
2009-05-28T12:44:27Z
920,652
8
2009-05-28T12:46:14Z
[ "python", "loops" ]
I am currently finding problems in when I should use the `while loop` or the `for loop` in python. What it looks like is that people prefer using the `for loop` *(less code lines?)*. Is there any specific situation which I should use one or the other? Is it a matter of personal preference? The codes I had read so far m...
The `for` is the more pythonic choice for iterating a list since it is simpler and easier to read. For example this: ``` for i in range(11): print i ``` is much simpler and easier to read than this: ``` i = 0 while i <= 10: print i i = i + 1 ```
When to use While or the For in python
920,645
15
2009-05-28T12:44:27Z
920,686
12
2009-05-28T12:55:01Z
[ "python", "loops" ]
I am currently finding problems in when I should use the `while loop` or the `for loop` in python. What it looks like is that people prefer using the `for loop` *(less code lines?)*. Is there any specific situation which I should use one or the other? Is it a matter of personal preference? The codes I had read so far m...
`while` is useful in scenarios where the break condition doesn't logically depend on any kind of sequence. For example, consider unpredictable interactions: ``` while user_is_sleeping(): wait() ``` Of course, you *could* write an appropriate iterator to encapsulate that action and make it accessible via `for` â...
When to use While or the For in python
920,645
15
2009-05-28T12:44:27Z
920,692
36
2009-05-28T12:55:59Z
[ "python", "loops" ]
I am currently finding problems in when I should use the `while loop` or the `for loop` in python. What it looks like is that people prefer using the `for loop` *(less code lines?)*. Is there any specific situation which I should use one or the other? Is it a matter of personal preference? The codes I had read so far m...
Yes, there is a huge difference between while and for. The **for** statement iterates through a collection or iterable object or generator function. The **while** statement simply loops until a condition is False. It isn't preference. It's a question of what your data structures are. Often, we represent the values ...
Sending Multipart html emails which contain embedded images
920,910
36
2009-05-28T13:45:57Z
920,928
82
2009-05-28T13:48:27Z
[ "python", "email", "mime", "attachment", "multipart" ]
I've been playing around with the email module in python but I want to be able to know how to embed images which are included in the html. So for example if the body is something like ``` <img src="../path/image.png"></img> ``` I would like to embed *image.png* into the email, and the `src` attribute should be repla...
Here is an example I found. > [**Recipe 473810: Send an HTML email with embedded image and plain text alternate**](http://code.activestate.com/recipes/473810/): > > HTML is the method of choice for those > wishing to send emails with rich text, > layout and graphics. Often it is > desirable to embed the graphics withi...
How to use classes derived from Python's list class
921,334
6
2009-05-28T15:05:13Z
921,510
9
2009-05-28T15:31:42Z
[ "python", "class" ]
This is a followup to question 912526 - <http://stackoverflow.com/questions/912526/how-do-i-pass-lots-of-variables-to-and-from-a-function-in-python>. There are lots of variables that need to get passed around in the program I'm writing, and from my previous question I understand that I should put these variables into ...
There are several issues in your code: 1.If you make any list operation the result will be a native list: ``` layers1 = Layers() layers2 = Layers() layers1 + layers2 -> the result will be a native list ``` 2.Why define input\_string when you can override [`__repr__`](http://docs.python.org/reference/datamodel.html#o...
Retrieving all Cookies in Python
921,532
14
2009-05-28T15:35:09Z
921,744
21
2009-05-28T16:11:27Z
[ "python", "cookies" ]
How do I read back all of the cookies in Python without knowing their names?
Not sure if this is what you are looking for, but here is a simple example where you put cookies in a cookiejar and read them back: ``` from urllib2 import Request, build_opener, HTTPCookieProcessor, HTTPHandler import cookielib #Create a CookieJar object to hold the cookies cj = cookielib.CookieJar() #Create an open...
Learning parser in python
921,792
12
2009-05-28T16:18:45Z
922,930
10
2009-05-28T20:17:54Z
[ "python", "parsing" ]
I recall I have read about a parser which you just have to feed some sample lines, for it to know how to parse some text. It just determines the difference between two lines to know what the variable parts are. I thought it was written in python, but i'm not sure. Does anyone know what library that was?
Probably you mean *[TemplateMaker](http://code.google.com/p/templatemaker/)*, I haven't tried it yet, but it builds on well-researched *longest-common-substring* algorithms and thus should work reasonably... If you are interested in different (more complex) approaches, you can easily find a lot of material on Google Sc...
How to mark a global as deprecated in Python?
922,550
6
2009-05-28T18:48:00Z
922,693
13
2009-05-28T19:16:29Z
[ "python", "hook", "decorator", "global", "deprecated" ]
[I've seen decorators](http://wiki.python.org/moin/PythonDecoratorLibrary#Smartdeprecationwarnings.28withvalidfilenames.2Clinenumbers.2Cetc..29) that let you mark a function a deprecated so that a warning is given whenever that function is used. I'd like to do the same thing but for a global variable, but I can't think...
You can't do this directly, since theres no way of intercepting the module access. However, you can replace that module with an object of your choosing that acts as a proxy, looking for accesses to certain properties: ``` import sys, warnings def WrapMod(mod, deprecated): """Return a wrapped object that warns abo...
Syntax Highlight for Mako in Eclipse or TextMate?
922,771
12
2009-05-28T19:34:26Z
929,130
8
2009-05-30T06:03:34Z
[ "python", "templates", "mako" ]
Does anyone know of a syntax highlight for Mako templates for Eclipse or for TextMate? I know that there is a `.mako` syntax highlighter for the default text editor in Ubuntu.
I just did some [googlin'](http://www.google.com/search?q=mako%2Bbundle%2Btextmate). There is a [Mako bundle](http://svn.makotemplates.org/contrib/textmate/Mako.tmbundle/). I installed it under `~/Library/Application Support/TextMate/Bundles/` like so: ``` cd ~/Library/Application\ Support/TextMate/Bundles/ svn co ht...
Check if input is a list/tuple of strings or a single string
922,774
17
2009-05-28T19:35:21Z
922,796
27
2009-05-28T19:39:05Z
[ "python" ]
I've a method that I want to be able to accept either a single string (a path, but not necessarily one that exists on the machine running the code) or a list/tuple of strings. Given that strings act as lists of characters, how do I tell which the method has received? I'd like to be able to accept either standard or u...
You can check if a variable is a string or unicode string with ``` isinstance(some_object, basestring) ``` This will return `True` for both strings and unicode strings Edit: You could do something like this: ``` if isinstance(some_object, basestring): ... elif all(isinstance(item, basestring) for item in some_...
Writing a kernel mode profiler for processes in python
922,788
2
2009-05-28T19:37:54Z
922,814
7
2009-05-28T19:42:20Z
[ "python", "kernel" ]
I would like seek some guidance in writing a "process profiler" which runs in kernel mode. I am asking for a kernel mode profiler is because I run loads of applications and I do not want my profiler to be swapped out. When I said "process profiler" I mean to something that would monitor resource usage by the process. ...
It's going to be very difficult to do the process monitoring part in Python, since the python interpreter doesn't run in the kernel. I suspect there are two easy approaches to this: 1. use the /proc filesystem if you have one (you don't mention your OS) 2. Use dtrace if you have dtrace (again, without the OS, who kno...
SPNEGO (kerberos token generation/validation) for SSO using Python
922,805
6
2009-05-28T19:40:12Z
1,001,619
8
2009-06-16T13:49:51Z
[ "python", "active-directory", "single-sign-on", "kerberos", "spnego" ]
I'm attempting to implement a simple Single Sign On scenario where some of the participating servers will be windows (IIS) boxes. It looks like SPNEGO is a reasonable path for this. Here's the scenario: * User logs in to my SSO service using his username and password. I authenticate him using some mechanism. * At som...
This is exactly what Apple does with its [Calendar Server](http://trac.calendarserver.org/). They have a [python gssapi](http://trac.calendarserver.org/browser/PyKerberos) library for the kerberos part of the process, in order to implement [SPNEGO](http://www.ietf.org/rfc/rfc4559.txt). Look in CalendarServer/twistedca...
NameError using execfile in python
922,897
2
2009-05-28T20:07:09Z
14,722,331
8
2013-02-06T05:38:23Z
[ "python", "class", "scope", "namespaces" ]
My application has a button to execute a python script dynamically using *execfile*. If I define a function inside the script (eg. *spam()*) and try to use that function inside another function (eg. *eggs()*), I get this error: ``` NameError: global name 'spam' is not defined ``` What is the correct way to call the *...
You're 3 years 8 months wiser since you posted so I'm assuming you'd have figured the first issue out, but given that a solution has not yet been posted (primarily because no one seemed to have a problem with the first issue), the following is my solution. ## [UPDATED] The last solution I provided was incorrect. Belo...
How can I capture the stdout output of a child process?
923,079
7
2009-05-28T20:45:45Z
923,108
14
2009-05-28T20:49:38Z
[ "python", "subprocess", "stdout" ]
I'm trying to write a program in Python and I'm told to run an .exe file. When this .exe file is run it spits out a lot of data and I need a certain line printed out to the screen. I'm pretty sure I need to use `subprocess.popen` or something similar but I'm new to subprocess and have no clue. Anyone have an easy way f...
Something like this: ``` import subprocess process = subprocess.Popen(["yourcommand"], stdout=subprocess.PIPE) result = process.communicate()[0] ```