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 |
|---|---|---|---|---|---|---|---|---|---|
Simple threading in Python 2.6 using thread.start_new_thread() | 849,674 | 11 | 2009-05-11T19:32:17Z | 849,896 | 14 | 2009-05-11T20:19:04Z | [
"python",
"multithreading",
"python-2.6"
] | I'm following a tutorial on simple threading. They give this example and when I try to use it I'm getting unintelligible errors from the interpreter. Can you please tell me why this isn't working? I'm on WinXP SP3 w/ Python 2.6 current
```
import thread
def myfunction(mystring,*args):
print mystring
if __name__... | You need to wait until your Thread finishes its work, so you have to use Thread.join() :
```
from threading import Thread
def myfunction(mystring,*args):
print mystring
if __name__ == '__main__':
try:
t = Thread(None,myfunction,None,('MyStringHere',1))
t.start()
t.join()
except E... |
Is there a way to set multiple defaults on a Python dict using another dict? | 849,806 | 7 | 2009-05-11T20:01:46Z | 849,849 | 7 | 2009-05-11T20:07:05Z | [
"python",
"dictionary"
] | Suppose I've got two dicts in Python:
```
mydict = { 'a': 0 }
defaults = {
'a': 5,
'b': 10,
'c': 15
}
```
I want to be able to expand `mydict` using the default values from `defaults`, such that 'a' remains the same but 'b' and 'c' are filled in. I know about [`dict.setdefault()`](http://docs.python.org/... | Couldnt you make mydict be a copy of default, That way, mydict would have all the correct values to start with?
```
mydict = default.copy()
``` |
Python -- Regex -- How to find a string between two sets of strings | 849,912 | 5 | 2009-05-11T20:23:49Z | 849,950 | 14 | 2009-05-11T20:32:41Z | [
"python",
"regex",
"string",
"tags"
] | Consider the following:
```
<div id=hotlinklist>
<a href="foo1.com">Foo1</a>
<div id=hotlink>
<a href="/">Home</a>
</div>
<div id=hotlink>
<a href="/extract">Extract</a>
</div>
<div id=hotlink>
<a href="/sitemap">Sitemap</a>
</div>
</div>
```
How would you go about taking out the sitemap lin... | Don't use a regex. Use [BeautfulSoup](http://www.crummy.com/software/BeautifulSoup/), an HTML parser.
```
from BeautifulSoup import BeautifulSoup
html = \
"""
<div id=hotlinklist>
<a href="foo1.com">Foo1</a>
<div id=hotlink>
<a href="/">Home</a>
</div>
<div id=hotlink>
<a href="/extract">Extract</a>
... |
What's the most efficient way to insert thousands of records into a table (MySQL, Python, Django) | 850,117 | 11 | 2009-05-11T21:13:26Z | 850,127 | 11 | 2009-05-11T21:16:21Z | [
"python",
"sql",
"mysql",
"django",
"insert"
] | I have a database table with a unique string field and a couple of integer fields. The string field is usually 10-100 characters long.
Once every minute or so I have the following scenario: I receive a list of 2-10 thousand tuples corresponding to the table's record structure, e.g.
```
[("hello", 3, 4), ("cat", 5, 3)... | For MySQL specifically, the fastest way to load data is using [LOAD DATA INFILE](http://dev.mysql.com/doc/refman/5.1/en/load-data.html), so if you could convert the data into the format that expects, it'll probably be the fastest way to get it into the table. |
What's the most efficient way to insert thousands of records into a table (MySQL, Python, Django) | 850,117 | 11 | 2009-05-11T21:13:26Z | 850,129 | 10 | 2009-05-11T21:16:29Z | [
"python",
"sql",
"mysql",
"django",
"insert"
] | I have a database table with a unique string field and a couple of integer fields. The string field is usually 10-100 characters long.
Once every minute or so I have the following scenario: I receive a list of 2-10 thousand tuples corresponding to the table's record structure, e.g.
```
[("hello", 3, 4), ("cat", 5, 3)... | You can write the rows to a file in the format
"field1", "field2", .. and then use LOAD DATA to load them
```
data = '\n'.join(','.join('"%s"' % field for field in row) for row in data)
f= open('data.txt', 'w')
f.write(data)
f.close()
```
Then execute this:
```
LOAD DATA INFILE 'data.txt' INTO TABLE db2.my_table;
``... |
Can a Python module use the imports from another file? | 850,566 | 3 | 2009-05-11T23:48:29Z | 850,611 | 13 | 2009-05-12T00:11:58Z | [
"python"
] | I have something like this:
```
# a.py
import os
class A:
...
# b.py
import a
class B(A):
...
```
In class B (b.py) I'd like to be able to use the modules imported in a.py (os in this case). Is it possible to achieve this behavior in Python or should I import the modules in both files?
Edit: I'm not w... | Yes you can use the imports from the other file by going a.os.
However, the pythonic way is to just import the exact modules you need without making a chain out of it (which can lead to circular references).
When you import a module, the code is compiled and inserted into a dictionary of names -> module objects. The ... |
Python *.py, *.pyo, *.pyc: Which can be eliminated for an Embedded System? | 850,630 | 10 | 2009-05-12T00:18:59Z | 850,646 | 13 | 2009-05-12T00:27:43Z | [
"python",
"embedded"
] | To squeeze into the limited amount of filesystem storage available in an embedded system I'm currently playing with, I would like to eliminate any files that could reasonably be removed without significantly impacting functionality or performance. The \*.py, \*.pyo, and \*.pyc files in the Python library account for a ... | <http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html>
> When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in â.pyoâ files. The optimizer currently doesn't help much; it only removes assert statements.
>
> Passing two -O flags to the Python interpreter (... |
Check whether a path exists on a remote host using paramiko | 850,749 | 9 | 2009-05-12T01:24:59Z | 1,391,409 | 15 | 2009-09-08T00:29:06Z | [
"python",
"ssh",
"scp",
"paramiko"
] | Paramiko's [SFTPClient](http://www.metasnark.com/paramiko/docs/paramiko.SFTP-class.html) apparently does not have an `exists` method. This is my current implementation:
```
def rexists(sftp, path):
"""os.path.exists for paramiko's SCP object
"""
try:
sftp.stat(path)
except IOError, e:
i... | See the [`errno` module](http://docs.python.org/library/errno.html#errno.ENOENT) for constants defining all those error codes. Also, it's a bit clearer to use the `errno` attribute of the exception than the expansion of the `__init__` args, so I'd do this:
```
except IOError, e: # or "as" if you're using Python 3.0
... |
Clearing Python lists | 850,795 | 119 | 2009-05-12T01:46:55Z | 850,831 | 229 | 2009-05-12T02:03:16Z | [
"python"
] | Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python:
```
old_list = []
old_list = list()
```
The reason I ask is that I just saw this in some running code:
```
del old_list[ 0:len(old_list) ]
``` | Clearing a list in place will affect all other references of the same list.
For example, this method doesn't affect other references:
```
>>> a = [1, 2, 3]
>>> b = a
>>> a = []
>>> print(a)
[]
>>> print(b)
[1, 2, 3]
```
But this one does:
```
>>> a = [1, 2, 3]
>>> b = a
>>> del a[:] # equivalent to del a[0:l... |
Clearing Python lists | 850,795 | 119 | 2009-05-12T01:46:55Z | 850,832 | 10 | 2009-05-12T02:03:32Z | [
"python"
] | Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python:
```
old_list = []
old_list = list()
```
The reason I ask is that I just saw this in some running code:
```
del old_list[ 0:len(old_list) ]
``` | ~~It appears to me that del will give you the memory back, while assigning a new list will make the old one be deleted only when the gc runs.matter.~~
This may be useful for large lists, but for small list it should be negligible.
**Edit**: As Algorias, it doesn't matter.
Note that
```
del old_list[ 0:len(old_list)... |
Clearing Python lists | 850,795 | 119 | 2009-05-12T01:46:55Z | 12,970,184 | 22 | 2012-10-19T08:23:54Z | [
"python"
] | Is there any reason to do anything more complicated than one of these two lines when you want to clear a list in Python:
```
old_list = []
old_list = list()
```
The reason I ask is that I just saw this in some running code:
```
del old_list[ 0:len(old_list) ]
``` | There is a very simple way to delete a python list. Use **del list\_name[:]**.
For example:
```
a = [1, 2, 3]
b = a
del a[:]
print b
``` |
Faster way to sum a list of numbers than with a for-loop? | 850,877 | 8 | 2009-05-12T02:20:32Z | 850,882 | 32 | 2009-05-12T02:22:50Z | [
"python",
"algorithm",
"for-loop"
] | Is there a way to sum up a list of numbers faster than with a for-loop, perhaps in the Python library? Or is that something really only multi-threading / vector processing can do efficiently?
Edit: Just to clarify, it could be a list of any numbers, unsorted, just input from the user. | You can use sum() to sum the values of an array.
```
a = [1,9,12]
print sum(a)
``` |
Can you pass a class (not an object) as a parameter to a method in python? | 850,921 | 5 | 2009-05-12T02:35:23Z | 850,929 | 7 | 2009-05-12T02:37:44Z | [
"python",
"static",
"parameters"
] | I want to do something like the following
```
class A:
def static_method_A():
print "hello"
def main(param=A):
param.static_method_A()
```
I want this to be equivalent to `A.static_method()`. Is this possible? | Sure. Classes are first-class objects in Python.
Although, in your example, you should use the `@classmethod` (class object as initial argument) or `@staticmethod` (no initial argument) decorator for your method. |
How does Python import modules from .egg files? | 851,420 | 12 | 2009-05-12T06:31:41Z | 851,430 | 18 | 2009-05-12T06:35:16Z | [
"python",
"module",
"packages"
] | How can I open `__init__.pyc` here?
```
>>> import stompservice
<module 'stompservice' from 'C:\Python25\lib\site-packages\stompservice-0.1.0-py2.5.egg\stompservice\__init__.pyc'>
```
All I see in `C:\Python25\lib\site-packages\` is the .egg file, but where are the internal files of the package? | <http://peak.telecommunity.com/DevCenter/PythonEggs>
.egg files are simply renamed zip files.
Open the egg with your zip program, or just rename the extension to .zip, and extract. |
How does Python import modules from .egg files? | 851,420 | 12 | 2009-05-12T06:31:41Z | 15,497,487 | 10 | 2013-03-19T10:54:35Z | [
"python",
"module",
"packages"
] | How can I open `__init__.pyc` here?
```
>>> import stompservice
<module 'stompservice' from 'C:\Python25\lib\site-packages\stompservice-0.1.0-py2.5.egg\stompservice\__init__.pyc'>
```
All I see in `C:\Python25\lib\site-packages\` is the .egg file, but where are the internal files of the package? | For example, if you want to import the suds module which is available as .egg file:
In your python script:
```
egg_path='/home/shahid/suds_2.4.egg'
sys.path.append(egg_path)
import suds
#... rest of code
``` |
Django -- User.DoesNotExist does not exist? | 851,628 | 26 | 2009-05-12T07:49:16Z | 851,888 | 16 | 2009-05-12T09:11:26Z | [
"python",
"django",
"authentication",
"django-models",
"pydev"
] | I'm trying to get hold of Django. I use Pydev on Eclipse. I have written a simple signup page that I can't get to work. Eclipse complains that User.DoesNotExist is undefined. Most likely, I am missing something trivial. Here's the relevant portion of the code:
```
from django.contrib.auth.models import User
...
class ... | The problem is really with PyDev, not your code. What you have done is absolutely correct, but IDEs will always have difficulty resolving attributes in a dynamic language like Python. In the case of the DoesNotExist exception, it is added via a `__metaclass__` rather than through normal object inheritance, so PyDev is ... |
Django -- User.DoesNotExist does not exist? | 851,628 | 26 | 2009-05-12T07:49:16Z | 851,937 | 7 | 2009-05-12T09:29:50Z | [
"python",
"django",
"authentication",
"django-models",
"pydev"
] | I'm trying to get hold of Django. I use Pydev on Eclipse. I have written a simple signup page that I can't get to work. Eclipse complains that User.DoesNotExist is undefined. Most likely, I am missing something trivial. Here's the relevant portion of the code:
```
from django.contrib.auth.models import User
...
class ... | Pydev has a workaround for such cases (when the members are defined at runtime).
Just add #@UndefinedVariable at the end of the string which cause the warning (or ctrl+1 on keyboard when the cursor is at "DoesNotExist"), and it won't complain. |
Django -- User.DoesNotExist does not exist? | 851,628 | 26 | 2009-05-12T07:49:16Z | 1,391,255 | 19 | 2009-09-07T23:00:34Z | [
"python",
"django",
"authentication",
"django-models",
"pydev"
] | I'm trying to get hold of Django. I use Pydev on Eclipse. I have written a simple signup page that I can't get to work. Eclipse complains that User.DoesNotExist is undefined. Most likely, I am missing something trivial. Here's the relevant portion of the code:
```
from django.contrib.auth.models import User
...
class ... | I just discovered Pydev actually has a nice workaround for this.
Go to **Window** > **Preferences**, then **Pydev** > **Editor** > **Code Analysis**.
Click the **Undefined** tab and add "DoesNotExist" to the text box titled **Consider the following names as globals**. |
How to read path from a txt file and copy those file to a new directory? | 851,689 | 2 | 2009-05-12T08:12:54Z | 851,799 | 8 | 2009-05-12T08:46:03Z | [
"python",
"file-io",
"copy"
] | > ```
> from shutil import copy
> f = open(r'C:\temp.txt', 'r')
> for i in f.readlines():
> print i
> copy(i,r"C:\opencascade")
>
> f.close()
> ```
I am reading path from temp.txt file which has 500 lines each line is a path for specific file to be copied to location "C:\opencascade"
How to convert 'i' in... | You have a `\n` at the and of the filename.
Try:
```
copy(i.strip(), r"C:\opencascade")
``` |
Django ImageField issue | 851,830 | 10 | 2009-05-12T08:55:06Z | 852,022 | 12 | 2009-05-12T09:57:01Z | [
"python",
"django",
"django-models"
] | I have a similar model
```
Class Student(models.Model):
"""A simple class which holds the basic info
of a student."""
name = models.CharField(max_length=50)
age = models.PositiveIntegerField()
photo = models.ImageField(upload_to='foobar', blank=True, null=True)
```
As we can see photo field is optional. I wanted all... | It doesn't work because [field lookups](http://docs.djangoproject.com/en/dev/topics/db/queries/#field-lookups) only work on other models. Here, `name` is an attribute on the return value of your `photo` field.
Try this instead:
```
Student.objects.exclude(photo__isnull=True)
```
It is preferred to use `isnull` inste... |
Build a GQL query (for Google App Engine) that has a condition on ReferenceProperty | 852,055 | 5 | 2009-05-12T10:06:18Z | 854,910 | 10 | 2009-05-12T21:17:11Z | [
"python",
"google-app-engine",
"gql"
] | Say I have the following model:
```
class Schedule(db.Model):
tripCode = db.StringProperty(required=True)
station = db.ReferenceProperty(Station, required=True)
arrivalTime = db.TimeProperty(required=True)
departureTime = db.TimeProperty(required=True)
```
And let's say I have a Station object sto... | You shouldn't be inserting user data into a GQL string using string substitution. GQL supports parameter substitution, so you can do this:
```
db.GqlQuery("SELECT * FROM Schedule WHERE station = $1", foo.key())
```
or, using the Query interface:
```
Schedule.all().filter("station =", foo.key())
``` |
Build a GQL query (for Google App Engine) that has a condition on ReferenceProperty | 852,055 | 5 | 2009-05-12T10:06:18Z | 1,788,018 | 7 | 2009-11-24T05:35:40Z | [
"python",
"google-app-engine",
"gql"
] | Say I have the following model:
```
class Schedule(db.Model):
tripCode = db.StringProperty(required=True)
station = db.ReferenceProperty(Station, required=True)
arrivalTime = db.TimeProperty(required=True)
departureTime = db.TimeProperty(required=True)
```
And let's say I have a Station object sto... | An even easier thing to do is to change the model definition by adding the 'collection\_name' field to the ReferenceProperty:
> station = db.ReferenceProperty(Station, required=True, collection\_name="schedules")
Then you can just do:
> foo.schedules
whenever you want to get all the stations' schedules. |
How the method resolution and invocation works internally in Python? | 852,308 | 5 | 2009-05-12T11:39:13Z | 870,650 | 7 | 2009-05-15T20:10:24Z | [
"java",
"python"
] | How the methods invocation works in Python?
I mean, how the python virtual machine interpret it.
It's true that the python method resolution could be slower in Python that in Java.
What is late binding?
What are the differences on the reflection mechanism in these two languages?
Where to find good resources explainin... | Method invocation in Python consists of two distinct separable steps. First an attribute lookup is done, then the result of that lookup is invoked. This means that the following two snippets have the same semantics:
```
foo.bar()
method = foo.bar
method()
```
Attribute lookup in Python is a rather complex process. S... |
M2Crypto Encrypt/Decrypt using AES256 | 852,332 | 6 | 2009-05-12T11:47:20Z | 854,417 | 12 | 2009-05-12T19:24:30Z | [
"python",
"aes",
"m2crypto"
] | Can someone provide me code to encrypt / decrypt using m2crypto aes256 CBC using Python | M2Crypto's documentation is terrible. Sometimes the OpenSSL documentation (m2crypto wraps OpenSSL) can help. Your best bet is to look at the M2Crypto unit tests -- <http://svn.osafoundation.org/m2crypto/trunk/tests/test_evp.py> -- look for the `test_AES()` method. |
Python: getting a reference to a function from inside itself | 852,401 | 18 | 2009-05-12T12:06:30Z | 852,455 | 19 | 2009-05-12T12:16:43Z | [
"python",
"function",
"self-reference"
] | If I define a function:
```
def f(x):
return x+3
```
I can later store objects as attributes of the function, like so:
```
f.thing="hello!"
```
I would like to do this from inside the code of the function itself. Problem is, how do I get a reference to the function from inside itself? | The same way, just use its name.
```
>>> def g(x):
... g.r = 4
...
>>> g
<function g at 0x0100AD68>
>>> g(3)
>>> g.r
4
``` |
How to dynamically compose an OR query filter in Django? | 852,414 | 45 | 2009-05-12T12:08:51Z | 852,423 | 7 | 2009-05-12T12:11:18Z | [
"python",
"django",
"django-q"
] | From an example you can see a multiple OR query filter:
```
Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
```
For example, this results in:
```
[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
```
However, I want to create this query filter from a list. How to do that?
e.g. `[1, 2, 3] -> ... | See the [docs](http://docs.djangoproject.com/en/dev/ref/models/querysets/#in-bulk-id-list):
```
>>> Blog.objects.in_bulk([1])
{1: <Blog: Beatles Blog>}
>>> Blog.objects.in_bulk([1, 2])
{1: <Blog: Beatles Blog>, 2: <Blog: Cheddar Talk>}
>>> Blog.objects.in_bulk([])
{}
```
Note that this method only works for primary k... |
How to dynamically compose an OR query filter in Django? | 852,414 | 45 | 2009-05-12T12:08:51Z | 852,428 | 15 | 2009-05-12T12:12:40Z | [
"python",
"django",
"django-q"
] | From an example you can see a multiple OR query filter:
```
Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
```
For example, this results in:
```
[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
```
However, I want to create this query filter from a list. How to do that?
e.g. `[1, 2, 3] -> ... | Maybe it's better to use sql IN statement.
```
Article.objects.filter(id__in=[1, 2, 3])
```
See [queryset api reference](http://docs.djangoproject.com/en/1.0/ref/models/querysets/#in).
If you really need to make queries with dynamic logic, you can do something like this (ugly + not tested):
```
query = Q(field=1)
f... |
How to dynamically compose an OR query filter in Django? | 852,414 | 45 | 2009-05-12T12:08:51Z | 852,481 | 73 | 2009-05-12T12:21:28Z | [
"python",
"django",
"django-q"
] | From an example you can see a multiple OR query filter:
```
Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
```
For example, this results in:
```
[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
```
However, I want to create this query filter from a list. How to do that?
e.g. `[1, 2, 3] -> ... | You could chain your queries as follows:
```
values = [1,2,3]
# Turn list of values into list of Q objects
queries = [Q(pk=value) for value in values]
# Take one Q object from the list
query = queries.pop()
# Or the Q object with the ones remaining in the list
for item in queries:
query |= item
# Query the mod... |
How to dynamically compose an OR query filter in Django? | 852,414 | 45 | 2009-05-12T12:08:51Z | 897,884 | 30 | 2009-05-22T13:36:12Z | [
"python",
"django",
"django-q"
] | From an example you can see a multiple OR query filter:
```
Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
```
For example, this results in:
```
[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
```
However, I want to create this query filter from a list. How to do that?
e.g. `[1, 2, 3] -> ... | A shorter way of writing Dave Webb's answer using [python's reduce function](http://docs.python.org/library/functions.html#reduce):
```
values = [1,2,3]
# Turn list of values into one big Q objects
query = reduce(lambda q,value: q|Q(pk=value), values, Q())
# Query the model
Article.objects.filter(query)
``` |
How to dynamically compose an OR query filter in Django? | 852,414 | 45 | 2009-05-12T12:08:51Z | 898,170 | 19 | 2009-05-22T14:34:19Z | [
"python",
"django",
"django-q"
] | From an example you can see a multiple OR query filter:
```
Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
```
For example, this results in:
```
[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
```
However, I want to create this query filter from a list. How to do that?
e.g. `[1, 2, 3] -> ... | ```
values = [1, 2, 3]
query = reduce(operator.or_, (Q(pk=x) for x in values))
``` |
How to dynamically compose an OR query filter in Django? | 852,414 | 45 | 2009-05-12T12:08:51Z | 29,149,972 | 22 | 2015-03-19T16:26:07Z | [
"python",
"django",
"django-q"
] | From an example you can see a multiple OR query filter:
```
Article.objects.filter(Q(pk=1) | Q(pk=2) | Q(pk=3))
```
For example, this results in:
```
[<Article: Hello>, <Article: Goodbye>, <Article: Hello and goodbye>]
```
However, I want to create this query filter from a list. How to do that?
e.g. `[1, 2, 3] -> ... | To build more complex queries there is also the option to use built in Q() object's constants Q.OR and Q.AND together with the add() method like so:
```
list = [1, 2, 3]
# it gets a bit more complicated if we want to dynamically build
# OR queries with dynamic/unknown db field keys, let's say with a list
# of db field... |
How can I find the locations of an item in a Python list of lists? | 853,023 | 5 | 2009-05-12T14:18:36Z | 853,335 | 7 | 2009-05-12T15:19:58Z | [
"python"
] | I want to find the location(s) of a specific item in a list of lists. It should return a list of tuples, where each tuple represents the indexes for a specific instance of the item. For example:
```
list = [['1', '2', '4', '6'], ['7', '0', '1', '4']]
getPosition('1') #returns [(0, 0), (1, 2)]
and getPosition('7') #re... | If you want something that will both
* find duplicates and
* handle nested lists (lists of lists of lists of ...)
you can do something like the following:
```
def get_positions(xs, item):
if isinstance(xs, list):
for i, it in enumerate(xs):
for pos in get_positions(it, item):
... |
Django ORM: Selecting related set | 853,184 | 11 | 2009-05-12T14:50:25Z | 853,228 | 12 | 2009-05-12T15:00:07Z | [
"python",
"django",
"orm"
] | Say I have 2 models:
```
class Poll(models.Model):
category = models.CharField(u"Category", max_length = 64)
[...]
class Choice(models.Model):
poll = models.ForeignKey(Poll)
[...]
```
Given a Poll object, I can query its choices with:
```
poll.choice_set.all()
```
But, is there a utility function t... | I think what you're saying is, "I want all Choices for a set of Polls." If so, try this:
```
polls = Poll.objects.filter(category='foo')
choices = Choice.objects.filter(poll__in=polls)
``` |
Django ORM: Selecting related set | 853,184 | 11 | 2009-05-12T14:50:25Z | 854,077 | 10 | 2009-05-12T18:11:29Z | [
"python",
"django",
"orm"
] | Say I have 2 models:
```
class Poll(models.Model):
category = models.CharField(u"Category", max_length = 64)
[...]
class Choice(models.Model):
poll = models.ForeignKey(Poll)
[...]
```
Given a Poll object, I can query its choices with:
```
poll.choice_set.all()
```
But, is there a utility function t... | **Update**: Since Django 1.4, this feature is built in: see [prefetch\_related](https://docs.djangoproject.com/en/stable/ref/models/querysets/#prefetch-related).
First answer: don't waste time writing something like qbind until you've already written a working application, profiled it, and demonstrated that N queries ... |
Django ORM: Selecting related set | 853,184 | 11 | 2009-05-12T14:50:25Z | 11,374,381 | 15 | 2012-07-07T10:56:21Z | [
"python",
"django",
"orm"
] | Say I have 2 models:
```
class Poll(models.Model):
category = models.CharField(u"Category", max_length = 64)
[...]
class Choice(models.Model):
poll = models.ForeignKey(Poll)
[...]
```
Given a Poll object, I can query its choices with:
```
poll.choice_set.all()
```
But, is there a utility function t... | Time has passed and this functionality is now available in Django 1.4 with the introduction of the [prefetch\_related()](https://docs.djangoproject.com/en/1.4/ref/models/querysets/#prefetch-related) QuerySet function. This function effectively does what is performed by the suggested `qbind` function. ie. Two queries ar... |
How can you migrate Django models similar to Ruby on Rails migrations? | 853,248 | 5 | 2009-05-12T15:04:24Z | 853,468 | 10 | 2009-05-12T15:46:14Z | [
"python",
"django",
"migration"
] | Django has a number of open source projects that tackle one of the framework's more notable [missing features](http://code.djangoproject.com/wiki/SchemaEvolution): model "evolution". Ruby on Rails has native support for [migrations](http://api.rubyonrails.org/classes/ActiveRecord/Migration.html), but I'm curious if any... | South has the most steam behind it. dmigrations is too basic IMO. django-evolution screams if you ever touch the db outside of it.
South is the strongest contender by far. With the model freezing and auto-migrations it's come a long way. |
What do I need to read Microsoft Access databases using Python? | 853,370 | 24 | 2009-05-12T15:29:23Z | 853,424 | 10 | 2009-05-12T15:39:23Z | [
"python",
"linux",
"ms-access",
"python-module"
] | How can I access Microsoft Access databases in Python? With SQL?
I'd prefere a solution that works with Linux, but I could also settle for Windows.
I only require read access. | How about [pyodbc](http://code.google.com/p/pyodbc/)? [This SO question](http://stackoverflow.com/questions/827502/pyodbc-and-microsoft-access-inconsistent-results-from-simple-query) demonstrates it's possible to read MS Access using it. |
What do I need to read Microsoft Access databases using Python? | 853,370 | 24 | 2009-05-12T15:29:23Z | 855,212 | 17 | 2009-05-12T22:33:26Z | [
"python",
"linux",
"ms-access",
"python-module"
] | How can I access Microsoft Access databases in Python? With SQL?
I'd prefere a solution that works with Linux, but I could also settle for Windows.
I only require read access. | I've used [PYODBC](https://pypi.python.org/pypi/pyodbc/) to connect succesfully to an MS Access db - on Windows though. Install was easy, usage is fairly simple, you just need to set the right connection string (the one for MS Access is given in the list) and of you go with the examples. |
What do I need to read Microsoft Access databases using Python? | 853,370 | 24 | 2009-05-12T15:29:23Z | 855,788 | 8 | 2009-05-13T02:32:10Z | [
"python",
"linux",
"ms-access",
"python-module"
] | How can I access Microsoft Access databases in Python? With SQL?
I'd prefere a solution that works with Linux, but I could also settle for Windows.
I only require read access. | You've got what sounds like some good solutions. Another one that might be a bit closer to the "metal" than you'd like is MDB Tools.
[MDB Tools](http://sourceforge.net/projects/mdbtools/) is a set of open source libraries and utilities to facilitate exporting data from MS Access databases (mdb files) without using the... |
What do I need to read Microsoft Access databases using Python? | 853,370 | 24 | 2009-05-12T15:29:23Z | 15,400,363 | 25 | 2013-03-14T02:56:02Z | [
"python",
"linux",
"ms-access",
"python-module"
] | How can I access Microsoft Access databases in Python? With SQL?
I'd prefere a solution that works with Linux, but I could also settle for Windows.
I only require read access. | On Linux, MDBTools is your only chance as of now. [[disputed]](http://stackoverflow.com/questions/853370/#comment53931912_15400363)
On Windows, you can deal with mdb files with pypyodbc.
To create an Access mdb file:
```
import pypyodbc
pypyodbc.win_create_mdb( "D:\\Your_MDB_file_path.mdb" )
```
[Here is an Hello W... |
Strange python behaviour | 853,407 | 7 | 2009-05-12T15:36:58Z | 853,449 | 16 | 2009-05-12T15:42:53Z | [
"python",
"ipython"
] | I was bored and playing around with the ipython console and came upon the following behaviour I don't really understand
```
In [1]: 2**2
Out[1]: 4
In [2]: 2**2**2
Out[2]: 16
In [3]: 2**2**2**2
Out[3]: 65536
In [4]: 2**2**2**2**2
```
The answer to [4] is *not* 4294967296L, it's a very long number, but I can't reall... | Python is going right to left on the mathematical power operation. For example, IN[2] is doing:
2\*\*(4) = 16
IN[3] = 2\*\*2\*\*2\*\*2 = 2\*\*2\*\*(4) = 2\*\*16 = 65536
You would need parenthesis if you want it to calculate from left to right. The reason OUT[4] is not outputting the answer you want is because the nu... |
Strange python behaviour | 853,407 | 7 | 2009-05-12T15:36:58Z | 853,460 | 7 | 2009-05-12T15:44:27Z | [
"python",
"ipython"
] | I was bored and playing around with the ipython console and came upon the following behaviour I don't really understand
```
In [1]: 2**2
Out[1]: 4
In [2]: 2**2**2
Out[2]: 16
In [3]: 2**2**2**2
Out[3]: 65536
In [4]: 2**2**2**2**2
```
The answer to [4] is *not* 4294967296L, it's a very long number, but I can't reall... | The precedence of the \*\* operator makes the evaluation goes from right-to-left (instead of the expected left-to-right). In other words:
```
2**2**2**2 == (2**(2**(2**2)))
``` |
Change keyboard locks in Python | 854,393 | 16 | 2009-05-12T19:19:37Z | 854,442 | 14 | 2009-05-12T19:28:17Z | [
"python",
"windows"
] | Is there any way, in Python, to programmatically *change* the CAPS LOCK/NUM LOCK/SCROLL LOCK states?
This isn't really a joke question - more like a real question for a joke program. I intend to use it for making the lights do funny things... | If you're using windows you can use [SendKeys](https://pypi.python.org/pypi/SendKeys/) for this I believe.
[http://www.rutherfurd.net/python/sendkeys](https://web.archive.org/web/20121125032946/http://www.rutherfurd.net/python/sendkeys)
```
import SendKeys
SendKeys.SendKeys("""
{CAPSLOCK}
{SCROLLOCK}
{NUMLOCK}
""")
... |
Change keyboard locks in Python | 854,393 | 16 | 2009-05-12T19:19:37Z | 858,992 | 14 | 2009-05-13T16:32:23Z | [
"python",
"windows"
] | Is there any way, in Python, to programmatically *change* the CAPS LOCK/NUM LOCK/SCROLL LOCK states?
This isn't really a joke question - more like a real question for a joke program. I intend to use it for making the lights do funny things... | On Linux here's a Python program to blink all the keyboard LEDs on and off:
```
import fcntl
import os
import time
KDSETLED = 0x4B32
SCR_LED = 0x01
NUM_LED = 0x02
CAP_LED = 0x04
console_fd = os.open('/dev/console', os.O_NOCTTY)
all_on = SCR_LED | NUM_LED | CAP_LED
all_off = 0
while 1:
fcntl.ioctl(console_fd... |
Can I restrict nose coverage output to directory (rather than package)? | 855,114 | 13 | 2009-05-12T22:06:28Z | 855,172 | 15 | 2009-05-12T22:23:05Z | [
"python",
"code-coverage",
"nose",
"nosetests"
] | My SUT looks like:
```
foo.py
bar.py
tests/__init__.py [empty]
tests/foo_tests.py
tests/bar_tests.py
tests/integration/__init__.py [empty]
tests/integration/foo_tests.py
tests/integration/bar_tests.py
```
When I run `nosetests --with-coverage`, I get details for all sorts of
modules that I'd rather ignore. But I can'... | You can use it like this:
```
--cover-package=foo --cover-package=bar
```
I had a quick look at nose source code to confirm: [This is the line](https://github.com/nose-devs/nose/blob/master/nose/plugins/cover.py)
```
if options.cover_packages:
for pkgs in [tolist(x) for x in options.cover_packages]:
``` |
Can I restrict nose coverage output to directory (rather than package)? | 855,114 | 13 | 2009-05-12T22:06:28Z | 7,691,689 | 9 | 2011-10-07T18:58:42Z | [
"python",
"code-coverage",
"nose",
"nosetests"
] | My SUT looks like:
```
foo.py
bar.py
tests/__init__.py [empty]
tests/foo_tests.py
tests/bar_tests.py
tests/integration/__init__.py [empty]
tests/integration/foo_tests.py
tests/integration/bar_tests.py
```
When I run `nosetests --with-coverage`, I get details for all sorts of
modules that I'd rather ignore. But I can'... | You can use:
```
--cover-package=.
```
or even set environment variable
```
NOSE_COVER_PACKAGE=.
```
Tested with nose 1.1.2 |
How Big can a Python Array Get? | 855,191 | 70 | 2009-05-12T22:27:33Z | 855,213 | 21 | 2009-05-12T22:33:28Z | [
"python",
"arrays",
"size"
] | In Python, how big can an array/list get? I need an array of about 12000 elements. Will I still be able to run array/list methods such as sorting, etc? | Sure it is OK. Actually you can see for yourself easily:
```
l = range(12000)
l = sorted(l, reverse=True)
```
Running the those lines on my machine took:
```
real 0m0.036s
user 0m0.024s
sys 0m0.004s
```
But sure as everyone else said. The larger the array the slower the operations will be. |
How Big can a Python Array Get? | 855,191 | 70 | 2009-05-12T22:27:33Z | 855,455 | 124 | 2009-05-12T23:48:21Z | [
"python",
"arrays",
"size"
] | In Python, how big can an array/list get? I need an array of about 12000 elements. Will I still be able to run array/list methods such as sorting, etc? | According to the [source code](http://svn.python.org/view/python/trunk/Objects/listobject.c?revision=69227&view=markup), the maximum size of a list is `PY_SSIZE_T_MAX/sizeof(PyObject*)`.
`PY_SSIZE_T_MAX` is defined in [pyport.h](http://svn.python.org/view/python/trunk/Include/pyport.h?revision=70489&view=markup) to be... |
How Big can a Python Array Get? | 855,191 | 70 | 2009-05-12T22:27:33Z | 15,739,630 | 20 | 2013-04-01T07:45:18Z | [
"python",
"arrays",
"size"
] | In Python, how big can an array/list get? I need an array of about 12000 elements. Will I still be able to run array/list methods such as sorting, etc? | As the [Python documentation says](http://docs.python.org/2/library/sys.html#sys.maxsize):
**sys.maxsize**
> The largest positive integer supported by the platformâs Py\_ssize\_t type, and thus the maximum size lists, strings, dicts, and many other containers can have.
In my computer (Linux x86\_64):
```
>>> impo... |
referenced before assignment error in python | 855,493 | 32 | 2009-05-13T00:08:33Z | 855,511 | 70 | 2009-05-13T00:24:28Z | [
"python"
] | In Python I'm getting the following error:
```
UnboundLocalError: local variable 'total' referenced before assignment
```
At the start of the file (before the function where the error comes from), I declare 'total' using the global keyword. Then, in the body of the program, before the function that uses 'total' is ca... | I think you are using 'global' incorrectly. See [Python reference](http://docs.python.org/reference/simple%5Fstmts.html#the-global-statement). You should declare variable without global and then inside the function when you want to access global variable you declare it 'global yourvar'.
```
#!/usr/bin/python
total
d... |
Python try-else | 855,759 | 308 | 2009-05-13T02:15:11Z | 855,764 | 531 | 2009-05-13T02:18:22Z | [
"python",
"exception-handling"
] | What is the intended use of the optional `else` clause of the `try` statement? | The statements in the `else` block are executed if execution falls off the bottom of the `try` - if there was no exception. Honestly, I've never found a need.
However, [Handling Exceptions](http://docs.python.org/tutorial/errors.html#handling-exceptions) notes:
> The use of the else clause is better
> than adding add... |
Python try-else | 855,759 | 308 | 2009-05-13T02:15:11Z | 855,781 | 7 | 2009-05-13T02:26:42Z | [
"python",
"exception-handling"
] | What is the intended use of the optional `else` clause of the `try` statement? | Even though you can't think of a use of it right now, you can bet there has to be a use for it. Here is an unimaginative sample:
With `else`:
```
a = [1,2,3]
try:
something = a[2]
except:
print "out of bounds"
else:
print something
```
Without `else`:
```
try:
something = a[2]
except:
print "out... |
Python try-else | 855,759 | 308 | 2009-05-13T02:15:11Z | 855,796 | 12 | 2009-05-13T02:34:26Z | [
"python",
"exception-handling"
] | What is the intended use of the optional `else` clause of the `try` statement? | I find it really useful when you've got cleanup to do that has to be done even if there's an exception:
```
try:
data = something_that_can_go_wrong()
except Exception as e: # yes, I know that's a bad way to do it...
handle_exception(e)
else:
do_stuff(data)
finally:
clean_up()
``` |
Python try-else | 855,759 | 308 | 2009-05-13T02:15:11Z | 855,803 | 31 | 2009-05-13T02:36:39Z | [
"python",
"exception-handling"
] | What is the intended use of the optional `else` clause of the `try` statement? | One use: test some code that should raise an exception.
```
try:
this_should_raise_TypeError()
except TypeError:
pass
except:
assert False, "Raised the wrong exception type"
else:
assert False, "Didn't raise any exception"
```
(This code should be abstracted into a more generic test in practice.) |
Python try-else | 855,759 | 308 | 2009-05-13T02:15:11Z | 14,590,478 | 42 | 2013-01-29T19:13:57Z | [
"python",
"exception-handling"
] | What is the intended use of the optional `else` clause of the `try` statement? | There is one **big** reason to use `else` - style and readability. It's generally a good idea to keep code that can cause exceptions near the code that deals with them. For example, compare these:
```
try:
from EasyDialogs import AskPassword
// 20 other lines
getpass = AskPassword
except ImportError:
g... |
Python try-else | 855,759 | 308 | 2009-05-13T02:15:11Z | 18,357,464 | 7 | 2013-08-21T12:29:59Z | [
"python",
"exception-handling"
] | What is the intended use of the optional `else` clause of the `try` statement? | From [Errors and Exceptions # Handling exceptions - docs.python.org](http://docs.python.org/2/tutorial/errors.html#handling-exceptions)
> The `try ... except` statement has an optional `else` clause, which,
> when present, must follow all except clauses. It is useful for code
> that must be executed if the try clause ... |
Python try-else | 855,759 | 308 | 2009-05-13T02:15:11Z | 28,443,901 | 9 | 2015-02-10T23:31:25Z | [
"python",
"exception-handling"
] | What is the intended use of the optional `else` clause of the `try` statement? | > # Python try-else
>
> What is the intended use of the optional `else` clause of the try statement?
## Summary
The `else` statement runs if there are *no* exceptions and if not interrupted by a `return`, `continue`, or `break` statement.
## The other answers miss that last part.
[From the docs:](https://docs.pytho... |
Please introduce a multi-processing library in Perl or Ruby | 855,805 | 5 | 2009-05-13T02:37:32Z | 855,820 | 12 | 2009-05-13T02:44:24Z | [
"python",
"ruby",
"perl"
] | In python we can use multiprocessing modules.
If there is a similar library in Perl and Ruby, would you teach it?
I would appreciate it if you can include a brief sample. | **Ruby:**
* [Working with multiple processes in Ruby](http://stackoverflow.com/questions/710785/working-with-multiple-processes-in-ruby)
* [Concurrency is a Myth in Ruby](http://www.igvita.com/2008/11/13/concurrency-is-a-myth-in-ruby/)
**Perl:**
* [Harnessing the power of multicore](http://computationalbiologynews.b... |
Please introduce a multi-processing library in Perl or Ruby | 855,805 | 5 | 2009-05-13T02:37:32Z | 856,035 | 9 | 2009-05-13T04:14:55Z | [
"python",
"ruby",
"perl"
] | In python we can use multiprocessing modules.
If there is a similar library in Perl and Ruby, would you teach it?
I would appreciate it if you can include a brief sample. | With Perl, you have options. One option is to use processes as below. I need to look up how to write the analogous program using threads but <http://perldoc.perl.org/perlthrtut.html> should give you an idea.
```
#!/usr/bin/perl
use strict;
use warnings;
use Parallel::ForkManager;
my @data = (0 .. 19);
my $pm = Par... |
Auto-populating created_by field with Django admin site | 855,816 | 18 | 2009-05-13T02:42:01Z | 855,837 | 22 | 2009-05-13T02:50:42Z | [
"python",
"django",
"django-models",
"django-admin"
] | I want to use the Django admin interface for a very simple web application but I can't get around a problem that should not be that hard to resolve ..
Consider the following:
```
class Contact(models.Model):
name = models.CharField(max_length=250, blank=False)
created_by = models.ForeignKey(User, blank=False)... | <http://code.djangoproject.com/wiki/CookBookNewformsAdminAndUser>
Involves implementing save methods on your ModelAdmin objects. |
Changing LD_LIBRARY_PATH at runtime for ctypes | 856,116 | 25 | 2009-05-13T04:52:49Z | 856,287 | 30 | 2009-05-13T05:57:52Z | [
"python",
"ctypes"
] | How do you update this environment variable at runtime so that ctypes can load a library wherever? I've tried the following and neither seem to work.
```
from ctypes import *
os.environ['LD_LIBRARY_PATH'] = "/home/starlon/Projects/pyCFA635/lib"
os.putenv('LD_LIBRARY_PATH', "/home/starlon/Projects/pyCFA635/lib")
li... | By the time a program such as Python is running, the dynamic loader (ld.so.1 or something similar) has already read LD\_LIBRARY\_PATH and won't notice any changes thereafter. So, unless the Python software itself evaluates LD\_LIBRARY\_PATH and uses it to build the possible path name of the library for `dlopen()` or an... |
Changing LD_LIBRARY_PATH at runtime for ctypes | 856,116 | 25 | 2009-05-13T04:52:49Z | 1,226,278 | 11 | 2009-08-04T08:20:48Z | [
"python",
"ctypes"
] | How do you update this environment variable at runtime so that ctypes can load a library wherever? I've tried the following and neither seem to work.
```
from ctypes import *
os.environ['LD_LIBRARY_PATH'] = "/home/starlon/Projects/pyCFA635/lib"
os.putenv('LD_LIBRARY_PATH', "/home/starlon/Projects/pyCFA635/lib")
li... | CDLL can be passed a fully qualified path name, so for example I am using the following in one of my scripts where the .so is in the same directory as the python script.
```
import os
path = os.path.dirname(os.path.realpath(__file__))
dll = CDLL("%s/iface.so"%path)
```
In your case the following should suffice.
```
... |
Changing LD_LIBRARY_PATH at runtime for ctypes | 856,116 | 25 | 2009-05-13T04:52:49Z | 4,326,241 | 18 | 2010-12-01T15:58:50Z | [
"python",
"ctypes"
] | How do you update this environment variable at runtime so that ctypes can load a library wherever? I've tried the following and neither seem to work.
```
from ctypes import *
os.environ['LD_LIBRARY_PATH'] = "/home/starlon/Projects/pyCFA635/lib"
os.putenv('LD_LIBRARY_PATH', "/home/starlon/Projects/pyCFA635/lib")
li... | Even if you give a fully qualified path to CDLL or cdll.LoadLibrary(), you may still need to set LD\_LIBRARY\_PATH before invoking Python. If the shared library you load explicitly refers to another shared library and no "rpath" is set in the .so for that library, then it won't be found, even if it has already been loa... |
2D arrays in Python | 856,948 | 23 | 2009-05-13T09:22:51Z | 856,976 | 8 | 2009-05-13T09:28:51Z | [
"python",
"arrays",
"list",
"tuples",
"multidimensional-array"
] | What's the best way to create 2D arrays in Python?
What I want is want is to store values like this:
```
X , Y , Z
```
so that I access data like `X[2],Y[2],Z[2]` or `X[n],Y[n],Z[n]` where `n` is variable.
I don't know in the beginning how big `n` would be so I would like to append values at the end. | In Python one would usually use [lists](http://docs.python.org/tutorial/datastructures.html) for this purpose. Lists can be nested arbitrarily, thus allowing the creation of a 2D array. Not every sublist needs to be the same size, so that solves your other problem. Have a look at the examples I linked to. |
2D arrays in Python | 856,948 | 23 | 2009-05-13T09:22:51Z | 856,978 | 20 | 2009-05-13T09:29:01Z | [
"python",
"arrays",
"list",
"tuples",
"multidimensional-array"
] | What's the best way to create 2D arrays in Python?
What I want is want is to store values like this:
```
X , Y , Z
```
so that I access data like `X[2],Y[2],Z[2]` or `X[n],Y[n],Z[n]` where `n` is variable.
I don't know in the beginning how big `n` would be so I would like to append values at the end. | ```
>>> a = []
>>> for i in xrange(3):
... a.append([])
... for j in xrange(3):
... a[i].append(i+j)
...
>>> a
[[0, 1, 2], [1, 2, 3], [2, 3, 4]]
>>>
``` |
2D arrays in Python | 856,948 | 23 | 2009-05-13T09:22:51Z | 857,034 | 7 | 2009-05-13T09:42:42Z | [
"python",
"arrays",
"list",
"tuples",
"multidimensional-array"
] | What's the best way to create 2D arrays in Python?
What I want is want is to store values like this:
```
X , Y , Z
```
so that I access data like `X[2],Y[2],Z[2]` or `X[n],Y[n],Z[n]` where `n` is variable.
I don't know in the beginning how big `n` would be so I would like to append values at the end. | If you want to do some serious work with arrays then you should use the [numpy library](http://numpy.scipy.org/). This will allow you for example to do vector addition and matrix multiplication, and for large arrays it is much faster than Python lists.
However, numpy requires that the size is predefined. Of course you... |
2D arrays in Python | 856,948 | 23 | 2009-05-13T09:22:51Z | 857,169 | 9 | 2009-05-13T10:21:14Z | [
"python",
"arrays",
"list",
"tuples",
"multidimensional-array"
] | What's the best way to create 2D arrays in Python?
What I want is want is to store values like this:
```
X , Y , Z
```
so that I access data like `X[2],Y[2],Z[2]` or `X[n],Y[n],Z[n]` where `n` is variable.
I don't know in the beginning how big `n` would be so I would like to append values at the end. | Depending what you're doing, you may not really have a 2-D array.
80% of the time you have simple list of "row-like objects", which might be proper sequences.
```
myArray = [ ('pi',3.14159,'r',2), ('e',2.71828,'theta',.5) ]
myArray[0][1] == 3.14159
myArray[1][1] == 2.71828
```
More often, they're instances of a cla... |
How to save django FileField to user folder? | 858,213 | 3 | 2009-05-13T14:16:48Z | 858,576 | 8 | 2009-05-13T15:13:25Z | [
"python",
"django",
"django-models",
"upload"
] | I've got a model like this
> ```
> def upload_location(instance, filename):
> return 'validate/%s/builds/%s' % (get_current_user(), filename)
>
> class MidletPair(models.Model):
> jad_file = models.FileField(upload_to = upload_location)
> jar_file = models.FileField(upload_to = upload_location)
> uplo... | The current user is stored in the request object, and you can't get that in a model method unless you pass it in from elsewhere - which you can't do in the upload\_to function.
So you'll need to approach this in a different manner - I would suggest doing it at the form level. You can pass the request object into the f... |
How to recognize whether a script is running on a tty? | 858,623 | 43 | 2009-05-13T15:24:06Z | 858,628 | 46 | 2009-05-13T15:24:45Z | [
"python",
"shell"
] | I would like my script to act differently in an interactive shell session and when running with redirected stdout (for example when piped to some other command).
How do I recognize which of these two happen in a Python script?
Example of such behavior in existing program: grep --color=auto highlights matches when run... | ```
import os, sys
os.isatty(sys.stdout.fileno())
```
or
```
sys.stdout.isatty()
``` |
How to redirect python warnings to a custom stream? | 858,916 | 4 | 2009-05-13T16:18:21Z | 858,928 | 7 | 2009-05-13T16:20:28Z | [
"python",
"warnings",
"io"
] | Let's say I have a file-like object like StreamIO and want the python's warning module write all warning messages to it. How do I do that? | Try reassigning [warnings.showwarning](http://docs.python.org/library/warnings.html#warnings.showwarning) i.e.
```
#!/sw/bin/python2.5
import warnings, sys
def customwarn(message, category, filename, lineno, file=None, line=None):
sys.stdout.write(warnings.formatwarning(message, category, filename, lineno))
war... |
About 20 models in 1 django app | 859,192 | 34 | 2009-05-13T17:06:36Z | 859,222 | 64 | 2009-05-13T17:10:40Z | [
"python",
"django",
"django-models"
] | I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python.
There's one problem: I have at least 20 models and each will have many functions. Quite simply it's going to cr... | This is a pretty common need... I can't imagine wading through a models.py file that's 10,000 lines long :-)
You can split up the `models.py` file (and views.py too) into a pacakge. In this case, your project tree will look like:
```
/my_proj
/myapp
/models
__init__.py
person.py
``... |
About 20 models in 1 django app | 859,192 | 34 | 2009-05-13T17:06:36Z | 859,436 | 15 | 2009-05-13T17:58:37Z | [
"python",
"django",
"django-models"
] | I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python.
There's one problem: I have at least 20 models and each will have many functions. Quite simply it's going to cr... | > The models are all related so I cant's
> simply make them into separate apps
> can I?
You **can** separate them into separate apps. To use a model in one app from another app you just import it in the same way you would import django.contrib apps. |
About 20 models in 1 django app | 859,192 | 34 | 2009-05-13T17:06:36Z | 859,442 | 29 | 2009-05-13T18:00:12Z | [
"python",
"django",
"django-models"
] | I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python.
There's one problem: I have at least 20 models and each will have many functions. Quite simply it's going to cr... | "I have at least 20 models" -- this is probably more than one Django "app" and is more like a Django "project" with several small "apps"
I like to partition things around topics or subject areas that have a few (1 to 5) models. This becomes a Django "app" -- and is the useful unit of reusability.
The overall "project... |
Getting the template name in django template | 859,319 | 4 | 2009-05-13T17:34:35Z | 860,260 | 8 | 2009-05-13T20:34:22Z | [
"python",
"django"
] | For debugging purposes, I would like to have a variable in all my templates holding the path of the template being rendered. For example, if a view renders templates/account/logout.html I would like {{ template\_name }} to contain the string templates/account/logout.html.
I don't want to go and change any views (speci... | **The easy way:**
Download and use the [django debug toolbar](http://github.com/robhudson/django-debug-toolbar/tree/master). You'll get an approximation of what you're after and a bunch more.
**The less easy way:**
Replace `Template.render` with `django.test.utils.instrumented_test_render`, listen for the `django.te... |
Can't find my PYTHONPATH | 859,594 | 9 | 2009-05-13T18:28:59Z | 859,613 | 11 | 2009-05-13T18:32:31Z | [
"python",
"windows",
"path"
] | I'm trying to change my PYTHONPATH. I've tried to change it in "My Computer" etc, but it doesn't exist there. I searched in the registry in some places, and even ran a whole search for the word 'PYTHONPATH', but to no avail.
However, it Python I can easily see it exists. So where is it? | At runtime, you can change it with:
```
import sys
sys.path.append('...')
```
In My Computer, right-click Properties (or press Win-Break), System tab, Environment Variables, System. You can add it if it's not already there.
Finally, in the CMD prompt:
```
set PYTHONPATH C:\Python25\Lib;C:\MyPythonLib
```
Or in `ba... |
whoami in python | 860,140 | 24 | 2009-05-13T20:09:24Z | 860,154 | 18 | 2009-05-13T20:12:10Z | [
"python",
"posix"
] | What is the best way to find out the user that a python process is running under?
I could do this:
```
name = os.popen('whoami').read()
```
But that has to start a whole new process.
```
os.environ["USER"]
```
works sometimes, but sometimes that environment variable isn't set. | This should work under Unix.
```
import os
print os.getuid() # numeric uid
import pwd
print pwd.getpwuid(os.getuid()) # full /etc/passwd info
``` |
whoami in python | 860,140 | 24 | 2009-05-13T20:09:24Z | 860,156 | 50 | 2009-05-13T20:12:15Z | [
"python",
"posix"
] | What is the best way to find out the user that a python process is running under?
I could do this:
```
name = os.popen('whoami').read()
```
But that has to start a whole new process.
```
os.environ["USER"]
```
works sometimes, but sometimes that environment variable isn't set. | ```
import getpass
print getpass.getuser()
```
See the documentation of the [getpass](http://docs.python.org/library/getpass.html) module.
> getpass.getuser()
>
> Return the âlogin nameâ of the user. Availability: Unix, Windows.
>
> This function checks the environment variables LOGNAME, USER,
> LNAME and USERNAM... |
django and mod_wsgi having database connection issues | 860,169 | 2 | 2009-05-13T20:13:16Z | 861,806 | 8 | 2009-05-14T06:15:16Z | [
"python",
"django",
"mod-wsgi"
] | I've noticed that whenever I enable the database settings on my django project (starting to notice a trend in my questions?) it gives me an internal server error. Setting the database settings to be blank makes the error go away. Here are the apache error logs that it outputs.
```
mod_wsgi (pid=770): Exception occurre... | You need to set the `PYTHON_EGG_CACHE` environment variable. Apache/mod\_wsgi is trying to extract the egg into a directory that Apache doesn't have write access to....or that doesn't exist.
It's explained in the [Django docs here](http://docs.djangoproject.com/en/dev/howto/deployment/modpython/#using-eggs-with-mod-py... |
Emacs function to add symbol to __all__ in Python mode? | 860,357 | 5 | 2009-05-13T20:50:43Z | 860,569 | 10 | 2009-05-13T21:40:04Z | [
"python",
"emacs"
] | Is there an existing Emacs function that adds the symbol currently under the point to `__all__` when editing Python code?
E.g., say the cursor was on the first `o` in `foo`:
```
# v---- cursor is on that 'o'
def foo():
return 42
```
If you did **M-x python-add-to-all** (or whatever) it would add `'foo'` to `_... | Not being a python programmer, I'm not sure this covers all the cases, but works for me in a simple case. It'll add the symbol to the array if the array exists, and create `__all__` if it doesn't exist. *Note: it does not parse the array to avoid double insertion.*
```
(defun python-add-to-all ()
"take the symbol un... |
Is python automagically parallelizing IO- and CPU- or memory-bound sections? | 860,893 | 3 | 2009-05-13T23:21:09Z | 861,004 | 8 | 2009-05-13T23:58:13Z | [
"python",
"linux",
"performance",
"text-files"
] | This is a follow-up questions on a [previous one](http://stackoverflow.com/questions/849058/is-it-possible-to-speed-up-python-io).
Consider this code, which is less toyish than the one in the [previous question](http://stackoverflow.com/questions/849058/is-it-possible-to-speed-up-python-io) (but still much simpler tha... | > Obviously data.append() is happening in parallel with the IO.
I'm afraid not. It *is* possible to parallelize IO and computation in Python, but it doesn't happen magically.
One thing you could do is use `posix_fadvise(2)` to give the OS a hint that you plan to read the file sequentially (`POSIX_FADV_SEQUENTIAL`).
... |
How to do this join query in Django | 860,941 | 8 | 2009-05-13T23:34:24Z | 860,997 | 10 | 2009-05-13T23:55:05Z | [
"python",
"sql",
"django"
] | In Django, I have two models:
```
class Product(models.Model):
name = models.CharField(max_length = 50)
categories = models.ManyToManyField(Category)
class ProductRank(models.Model):
product = models.ForeignKey(Product)
rank = models.IntegerField(default = 0)
```
I put the rank into a separate table ... | This can be done in Django, but you will need to restructure your models a little bit differently:
```
class Product(models.Model):
name = models.CharField(max_length=50)
product_rank = models.OneToOneField('ProductRank')
class ProductRank(models.Model):
rank = models.IntegerField(default=0)
```
Now, whe... |
A class method which behaves differently when called as an instance method? | 861,055 | 24 | 2009-05-14T00:26:24Z | 861,109 | 35 | 2009-05-14T00:56:35Z | [
"python",
"class",
"methods"
] | I'm wondering if it's possible to make a method which behaves differently when called as a class method than when called as an instance method.
For example, as a skills-improvement project, I'm writing a `Matrix` class (yes, I know there are perfectly good matrix classes already out there). I've created a class method... | Questionably useful Python hacks are my forte.
```
from types import *
class Foo(object):
def __init__(self):
self.bar = methodize(bar, self)
self.baz = 999
@classmethod
def bar(cls, baz):
return 2 * baz
def methodize(func, instance):
return MethodType(func, instance, instan... |
A class method which behaves differently when called as an instance method? | 861,055 | 24 | 2009-05-14T00:26:24Z | 861,137 | 7 | 2009-05-14T01:14:02Z | [
"python",
"class",
"methods"
] | I'm wondering if it's possible to make a method which behaves differently when called as a class method than when called as an instance method.
For example, as a skills-improvement project, I'm writing a `Matrix` class (yes, I know there are perfectly good matrix classes already out there). I've created a class method... | @Unknown What's the difference between your's and this:
```
class Foo(object):
def _bar(self, baz):
print "_bar, baz:", baz
def __init__(self, bar):
self.bar = self._bar
self.baz = bar
@classmethod
def bar(cls, baz):
print "bar, baz:", baz
In [1]: import foo
In [2]:... |
Ordering a list of dictionaries in python | 861,190 | 7 | 2009-05-14T01:41:03Z | 861,238 | 23 | 2009-05-14T01:59:25Z | [
"python",
"list",
"dictionary",
"order"
] | I've got a python list of dictionaries:
```
mylist = [
{'id':0, 'weight':10, 'factor':1, 'meta':'ABC'},
{'id':1, 'weight':5, 'factor':1, 'meta':'ABC'},
{'id':2, 'weight':5, 'factor':2, 'meta':'ABC'},
{'id':3, 'weight':1, 'factor':1, 'meta':'ABC'}
]
```
Whats the most efficient/cleanest way to order that list by weigh... | ```
mylist.sort(key=lambda d: (d['weight'], d['factor']))
```
or
```
import operator
mylist.sort(key=operator.itemgetter('weight', 'factor'))
``` |
Is there a "safe" subset of Python for use as an embedded scripting language? | 861,864 | 7 | 2009-05-14T06:37:43Z | 861,961 | 8 | 2009-05-14T07:12:56Z | [
"python",
"security",
"scripting",
"scripting-language",
"embedded-language"
] | In the many Python applications I've created, I often create simple modules containing nothing but constants to be used as config files. Additionally, because the config file is actually a Python code file, I can add simple logic for changing variables depending on a debug level, etc.
While this works great for intern... | Here are a couple of links to give you an idea on what you're up against:
* [How can I run an untrusted Python script safely (i.e. Sandbox)](https://wiki.python.org/moin/Asking%20for%20Help/How%20can%20I%20run%20an%20untrusted%20Python%20script%20safely%20%28i.e.%20Sandbox%29)
* [Capabilities for Python?](http://neopy... |
Get a unique list/tuple element given a condition in python | 862,158 | 2 | 2009-05-14T08:18:22Z | 862,191 | 11 | 2009-05-14T08:27:07Z | [
"python",
"list",
"tuples",
"condition"
] | How do I get a tuple/list element given a condition in python?
This occurs pretty often and I am looking for a nice-few-lines-pythonic way of doing this.
here could be an example:
Consider a tuple containing 2D points coordinates like this:
```
points = [[x1, y1],[x2, y2],[x3, y3], ...]
```
And I would like to get ... | ```
min(points, key=lambda x: dist(pointToCompare2, x))
```
[min is a built-in function](http://docs.python.org/library/functions.html#min). |
How to download a file using python in a 'smarter' way? | 862,173 | 63 | 2009-05-14T08:21:42Z | 862,198 | 38 | 2009-05-14T08:28:43Z | [
"python",
"http",
"download"
] | I need to download several files via http in Python.
The most obvious way to do it is just using urllib2:
```
import urllib2
u = urllib2.urlopen('http://server.com/file.html')
localFile = open('file.html', 'w')
localFile.write(u.read())
localFile.close()
```
But I'll have to deal with the URLs that are nasty in some... | Download scripts like that tend to push a header telling the user-agent what to name the file:
```
Content-Disposition: attachment; filename="the filename.ext"
```
If you can grab that header, you can get the proper filename.
There's [another thread](http://stackoverflow.com/questions/163009/urllib2-file-name) that ... |
How to download a file using python in a 'smarter' way? | 862,173 | 63 | 2009-05-14T08:21:42Z | 863,017 | 33 | 2009-05-14T12:23:12Z | [
"python",
"http",
"download"
] | I need to download several files via http in Python.
The most obvious way to do it is just using urllib2:
```
import urllib2
u = urllib2.urlopen('http://server.com/file.html')
localFile = open('file.html', 'w')
localFile.write(u.read())
localFile.close()
```
But I'll have to deal with the URLs that are nasty in some... | Based on comments and @Oli's anwser, I made a solution like this:
```
from os.path import basename
from urlparse import urlsplit
def url2name(url):
return basename(urlsplit(url)[2])
def download(url, localFileName = None):
localName = url2name(url)
req = urllib2.Request(url)
r = urllib2.urlopen(req)
... |
How to download a file using python in a 'smarter' way? | 862,173 | 63 | 2009-05-14T08:21:42Z | 2,067,142 | 22 | 2010-01-14T19:54:30Z | [
"python",
"http",
"download"
] | I need to download several files via http in Python.
The most obvious way to do it is just using urllib2:
```
import urllib2
u = urllib2.urlopen('http://server.com/file.html')
localFile = open('file.html', 'w')
localFile.write(u.read())
localFile.close()
```
But I'll have to deal with the URLs that are nasty in some... | Combining much of the above, here is a more pythonic solution:
```
import urllib2
import shutil
import urlparse
import os
def download(url, fileName=None):
def getFileName(url,openUrl):
if 'Content-Disposition' in openUrl.info():
# If the response has Content-Disposition, try to get filename f... |
Is it possible to have multiple statements in a python lambda expression? | 862,412 | 45 | 2009-05-14T09:31:34Z | 862,498 | 67 | 2009-05-14T09:55:37Z | [
"python"
] | I am a python newbie trying to achieve the following:
I have a list of lists:
```
lst = [[567,345,234],[253,465,756, 2345],[333,777,111, 555]]
```
I want map lst into another list containing only the second smallest number from each sublist. So the result should be:
```
[345, 465, 333]
```
For example if I were ju... | There are several different answers I can give here, from your specific question to more general concerns. so from most specific to most general:
**Q.** Can you put multiple statements in a lambda?
**A.** No. But you don't actually need to use a lambda. You can put the statements in a `def` instead. ie:
```
def seco... |
Is it possible to have multiple statements in a python lambda expression? | 862,412 | 45 | 2009-05-14T09:31:34Z | 17,604,249 | 15 | 2013-07-11T21:59:36Z | [
"python"
] | I am a python newbie trying to achieve the following:
I have a list of lists:
```
lst = [[567,345,234],[253,465,756, 2345],[333,777,111, 555]]
```
I want map lst into another list containing only the second smallest number from each sublist. So the result should be:
```
[345, 465, 333]
```
For example if I were ju... | Time traveler here. If you generally want to have multiple statements within a lambda, you can pass other lambdas as arguments to that lambda.
```
(lambda x, f: list((y[1] for y in f(x))))(lst, lambda x: (sorted(y) for y in x))
```
You can't actually have multiple statements, but you can simulate that by passing lamb... |
Is it possible to have multiple statements in a python lambda expression? | 862,412 | 45 | 2009-05-14T09:31:34Z | 18,528,195 | 35 | 2013-08-30T08:20:18Z | [
"python"
] | I am a python newbie trying to achieve the following:
I have a list of lists:
```
lst = [[567,345,234],[253,465,756, 2345],[333,777,111, 555]]
```
I want map lst into another list containing only the second smallest number from each sublist. So the result should be:
```
[345, 465, 333]
```
For example if I were ju... | Putting the statements in a list may simulate multiple statements:
E.g.:
```
lambda x: [f1(x), f2(x), f3(x), x+1]
``` |
How would you write a @debuggable decorator in python? | 862,807 | 7 | 2009-05-14T11:26:37Z | 862,899 | 19 | 2009-05-14T11:52:07Z | [
"python",
"decorator"
] | When debugging, I like to print out all the inputs and outputs of a function (I know I need a better IDE, but humour me, this could be used for error reporting). So, I'd ideally like to have:
```
@debuggable
def myfunc(argA,argB,argC):
return argB+1
```
and use a global variable to switch on or off debugging. No,... | Use a debugger. Seriously. Decorating every function you want to keep track is a bad idea.
Python [has a debugger included](http://docs.python.org/library/pdb.html), so you don't need a good IDE.
If you don't want to use a debugger, you can use the [trace function](http://docs.python.org/library/sys.html#sys.settrace... |
Python: adding namespaces in lxml | 863,183 | 6 | 2009-05-14T12:58:32Z | 863,834 | 8 | 2009-05-14T14:59:28Z | [
"python",
"lxml",
"xml-namespaces"
] | I'm trying to specify a namespace using *lxml* similar to this example (taken from [here](http://www.maconstateit.net/tutorials/XML/XML03/xml03-01.htm)):
```
<TreeInventory xsi:noNamespaceSchemaLocation="Trees.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
</TreeInventory>
```
I'm not sure how to add the... | In some more steps, for clarity:
```
>>> NS = 'http://www.w3.org/2001/XMLSchema-instance'
```
As far as I can see, it is the attribute `noNameSpaceSchemaLocation` that you want namespaced, not the `TreeInventory` element. So:
```
>>> location_attribute = '{%s}noNameSpaceSchemaLocation' % NS
>>> elem = etree.Element(... |
How to generate XML documents with namespaces in Python | 863,774 | 22 | 2009-05-14T14:51:01Z | 864,030 | 19 | 2009-05-14T15:26:47Z | [
"python",
"xml",
"dom",
"namespaces"
] | I'm trying to generate an XML document with namespaces, currently with Python's xml.dom.minidom:
```
import xml.dom.minidom
doc = xml.dom.minidom.Document()
el = doc.createElementNS('http://example.net/ns', 'el')
doc.appendChild(el)
print(doc.toprettyxml())
```
The namespace is saved (`doc.childNodes[0].namespaceURI`... | `createElementNS()` is defined as:
```
def createElementNS(self, namespaceURI, qualifiedName):
prefix, localName = _nssplit(qualifiedName)
e = Element(qualifiedName, namespaceURI, prefix)
e.ownerDocument = self
return e
```
soâ¦
```
import xml.dom.minidom
doc = xml.dom.minidom.Document()
el = doc.cr... |
A data-structure for 1:1 mappings in python? | 863,935 | 24 | 2009-05-14T15:14:18Z | 864,071 | 25 | 2009-05-14T15:34:35Z | [
"python",
"data-structures"
] | I have a problem which requires a reversable 1:1 mapping of keys to values.
That means sometimes I want to find the value given a key, but at other times I want to find the key given the value. Both keys and values are guaranteed unique.
```
x = D[y]
y == D.inverse[x]
```
The obvious solution is to simply invert the... | > *The other alternative is to make a new
> class which unites two dictionaries,
> one for each kind of lookup. That
> would most likely be fast but would
> use up twice as much memory as a
> single dict.*
Not really. Have you measured that? Since both dictionaries would use references to the **same objects** as keys ... |
A data-structure for 1:1 mappings in python? | 863,935 | 24 | 2009-05-14T15:14:18Z | 1,374,617 | 11 | 2009-09-03T16:46:21Z | [
"python",
"data-structures"
] | I have a problem which requires a reversable 1:1 mapping of keys to values.
That means sometimes I want to find the value given a key, but at other times I want to find the key given the value. Both keys and values are guaranteed unique.
```
x = D[y]
y == D.inverse[x]
```
The obvious solution is to simply invert the... | ```
class TwoWay:
def __init__(self):
self.d = {}
def add(self, k, v):
self.d[k] = v
self.d[v] = k
def remove(self, k):
self.d.pop(self.d.pop(k))
def get(self, k):
return self.d[k]
``` |
how to modify choices on admin pages - django | 864,433 | 7 | 2009-05-14T16:42:16Z | 16,367,595 | 7 | 2013-05-03T21:09:39Z | [
"python",
"django",
"django-models",
"django-admin"
] | I have a model that has a field named "state":
```
class Foo(models.Model):
...
state = models.IntegerField(choices = STATES)
...
```
For every state, possible choices are a certain subset of all STATES. For example:
```
if foo.state == STATES.OPEN: #if foo is open, possible states are CLOSED, CANCEL... | When you create a new admin interface for a model (e.g. MyModelAdmin) there are specific methods for override the default choices of a field. For a generic [choice field](https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_choice_field):
```
class MyModelAdmin(admin.M... |
How do I write a float list of lists to file in Python | 864,883 | 5 | 2009-05-14T18:16:54Z | 864,910 | 7 | 2009-05-14T18:22:43Z | [
"python",
"file-io"
] | I need to write a series of matrices out to a plain text file from python. All my matricies are in float format so the simple
file.write() and file.writelines()
do not work. Is there a conversion method I can employ that doesn't have me looping through all the lists (matrix = list of lists in my case) converting the i... | the following works for me:
```
with open(fname, 'w') as f:
f.writelines(','.join(str(j) for j in i) + '\n' for i in matrix)
``` |
How do I write a float list of lists to file in Python | 864,883 | 5 | 2009-05-14T18:16:54Z | 864,916 | 7 | 2009-05-14T18:23:25Z | [
"python",
"file-io"
] | I need to write a series of matrices out to a plain text file from python. All my matricies are in float format so the simple
file.write() and file.writelines()
do not work. Is there a conversion method I can employ that doesn't have me looping through all the lists (matrix = list of lists in my case) converting the i... | ```
m = [[1.1, 2.1, 3.1], [4.1, 5.1, 6.1], [7.1, 8.1, 9.1]]
file.write(str(m))
```
If you want more control over the format of each value:
```
def format(value):
return "%.3f" % value
formatted = [[format(v) for v in r] for r in m]
file.write(str(formatted))
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.