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 |
|---|---|---|---|---|---|---|---|---|---|
newbie python subprocess: "write error: Broken pipe" | 4,106,565 | 9 | 2010-11-05T14:03:05Z | 4,106,633 | 8 | 2010-11-05T14:10:11Z | [
"python",
"subprocess",
"popen"
] | Thanks to the helpful suggestions below:
So it seems to be fixed when I
1. separate commands into individual calls to Popen
2. stderr=subprocess.PIPE as an argument to each Popen chain.
The New code:
```
import subprocess
import shlex
import logging
def run_shell_commands(cmds):
""" Run commands and return out... | From the recipes on [subprocess](http://docs.python.org/library/subprocess.html#replacing-shell-pipeline) docs:
```
# To replace shell pipeline like output=`dmesg | grep hda`
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
``` |
Understanding objects in Python | 4,107,740 | 7 | 2010-11-05T16:09:22Z | 4,107,787 | 7 | 2010-11-05T16:15:19Z | [
"python",
"object",
"object-model"
] | I am a little confused by the object model of Python. I have two classes, one inherits from the other.
```
class Node():
def __init__(identifier):
self.identifier = identifier
class Atom(Node):
def __init__(symbol)
self.symbol = symbol
```
What I am trying to do is not to override the **\_\_*init*\_\_**(... | ```
>>> class Node(object):
... def __init__(self, id_):
... self.id_ = id_
...
>>> class Atom(Node):
... def __init__(self, symbol, id_):
... super(Atom, self).__init__(id_)
... self.symbol = symbol
...
>>> a = Atom("FE", 1)
>>> a.symbol
'FE'
>>> a.id_
1
>>> type(a)
<class... |
Update model django through kwargs | 4,108,258 | 14 | 2010-11-05T17:09:06Z | 4,108,308 | 11 | 2010-11-05T17:15:07Z | [
"python",
"django"
] | How can i pass a dict which contain fields to update a Django model?
This is not to create an object, but to update it.
example:
```
obj = Object.objects.create(index=id, **fields)
``` | ```
def update_object(obj, **kwargs):
for k, v in kwargs.items():
setattr(obj, k, v)
obj.save()
``` |
Update model django through kwargs | 4,108,258 | 14 | 2010-11-05T17:09:06Z | 4,108,318 | 21 | 2010-11-05T17:16:25Z | [
"python",
"django"
] | How can i pass a dict which contain fields to update a Django model?
This is not to create an object, but to update it.
example:
```
obj = Object.objects.create(index=id, **fields)
``` | As long as the PK is the same, the existing row will be overwritten.
```
obj = Object(index=id, **fields)
obj.save()
``` |
Generating an ascending list of numbers of arbitrary length in python | 4,108,341 | 3 | 2010-11-05T17:19:18Z | 4,108,359 | 11 | 2010-11-05T17:21:36Z | [
"python"
] | Is there a function I can call that returns a list of ascending numbers? I.e., `function(10)` would return `[0,1,2,3,4,5,6,7,8,9]`? | You want [`range()`](http://docs.python.org/library/functions.html#range). |
How to exclude a character from a regex group? | 4,108,561 | 11 | 2010-11-05T17:45:58Z | 4,108,628 | 18 | 2010-11-05T17:54:08Z | [
"python",
"regex"
] | I want to strip all non-alphanumeric characters EXCEPT the hyphen from a string (python).
How can I change this regular expression to match any non-alphanumeric char except the hyphen?
```
re.compile('[\W_]')
```
Thanks. | You could just use a negated character class instead:
```
re.compile(r"[^a-zA-Z0-9-]")
```
This will match anything that is not in the alphanumeric ranges or a hyphen. It also matches the underscore, as per your current regex.
```
>>> r = re.compile(r"[^a-zA-Z0-9-]")
>>> s = "some#%te_xt&with--##%--5 hy-phens *#"
>... |
Difference between '' and "" in Python | 4,108,743 | 5 | 2010-11-05T18:07:46Z | 4,108,755 | 8 | 2010-11-05T18:08:50Z | [
"python"
] | What is the difference between apostrophes and quotation marks in Python?
So far I've only been able to find one difference
```
print "'"
print '"'
print '''
print """
```
The first print statement will output **'** while the second **"**. However the third statement starts a comment block.
Any other differences... | > Python has a facility multiline string that starts with triple quotes.
They are also commonly used for docstrings.
* <http://www.python.org/dev/peps/pep-0257/>
An example of multiline string:
```
>>> x = """ wdd2ed
... 2wdqd
... d
... dd
... d
... """
>>>
>>> print x
wdd2ed
2wdqd
d
dd
d
>>>
```
String literal... |
Difference between '' and "" in Python | 4,108,743 | 5 | 2010-11-05T18:07:46Z | 4,108,775 | 14 | 2010-11-05T18:11:08Z | [
"python"
] | What is the difference between apostrophes and quotation marks in Python?
So far I've only been able to find one difference
```
print "'"
print '"'
print '''
print """
```
The first print statement will output **'** while the second **"**. However the third statement starts a comment block.
Any other differences... | `print 'Hello'` and `print "Hello"` are the same and what you use is your personal preference. `"""` and `'''` are for multiline strings.
```
>>> print """First
Second
Third"""
First
Second
Third
``` |
Python regex: string does not contain "jpg" and must have "-" and lowercase | 4,109,088 | 2 | 2010-11-05T18:50:57Z | 4,109,814 | 9 | 2010-11-05T20:31:50Z | [
"python",
"regex",
"django",
"django-urls"
] | I'm having troubles figuring out a python regex for django urls. I have a certain criteria, but can't seem to come up with the magic formula. In the end its so I can identify which page is a CMS page and pass to the django function the alias url it should load.
Here are some examples of valid strings which would match... | I'm puzzled as to why several of the commentators find that this is hard to do in a regex. This is exactly what regular expressions are good at.
```
if re.match(
r"""^ # match start of the string
(?=.*-) # assert that there is a dash
(?!.*\.(?:jpg|gif|png|css|js)) # assert that these... |
How would I use a South migration to load data into Django's auth_group table? | 4,109,186 | 4 | 2010-11-05T19:05:51Z | 4,109,342 | 8 | 2010-11-05T19:31:28Z | [
"python",
"django",
"django-south"
] | I have some new groups that I'd like to add to Django's "auth\_group" table and I'd prefer to use South to "migrate" that data into the database. Unfortunately, I'm not sure what steps I should take to create the migration file and then have it load my fixture.
Any thoughts? | The South docs have a [section about fixtures](http://south.aeracode.org/docs/fixtures.html) that includes this sample:
```
def forwards(self, orm):
from django.core.management import call_command
call_command("loaddata", "my_fixture.json")
``` |
How can I use third party 'libraries' in python? | 4,109,206 | 4 | 2010-11-05T19:09:32Z | 4,109,275 | 8 | 2010-11-05T19:19:48Z | [
"python",
"eclipse",
"libraries"
] | **Disclaimer**: This is a very basic question, but keep in mind I come from a Microsoft background, and I've programmed mostly in .NET with Visual Studio (this may help you help me with analogies perhaps)
---
I started programming a little python for the fun of it, so I downloaded [eclipse](http://www.eclipse.org/), ... | > I went ahead and downloaded it, but I
> had problems when I tried to use it.
> Apparently the download includes
> source files, and I had absolutely no
> idea how to use it in my "project" in
> eclipse.
you should use [pip](http://pypi.python.org/pypi/pip) in your line of command type :
```
pip install python-dateu... |
Processing multiple values for one single option using getopt/optparse? | 4,109,436 | 22 | 2010-11-05T19:44:07Z | 10,404,816 | 14 | 2012-05-01T21:44:52Z | [
"python",
"getopt"
] | Is it possible to fetch multiple values for one option using getopt or optparse, as shown in the example below:
```
./hello_world -c arg1 arg2 arg3 -b arg4 arg5 arg6 arg7
```
Please note that the number of actual values for each option (-c, -b) could be either 1 or 100. I do not want to use:
`./hello_world -c "arg1 a... | Yes, it can be done with optparse.
This is an example:
```
./test.py --categories=aaa --categories=bbb --categories ccc arg1 arg2 arg3
```
which prints:
```
arguments: ['arg1', 'arg2', 'arg3']
options: {'categories': ['aaa', 'bbb', 'ccc']}
```
Full working example below:
```
#!/usr/bin/env python
import os, sys
... |
Processing multiple values for one single option using getopt/optparse? | 4,109,436 | 22 | 2010-11-05T19:44:07Z | 14,824,041 | 7 | 2013-02-12T01:29:51Z | [
"python",
"getopt"
] | Is it possible to fetch multiple values for one option using getopt or optparse, as shown in the example below:
```
./hello_world -c arg1 arg2 arg3 -b arg4 arg5 arg6 arg7
```
Please note that the number of actual values for each option (-c, -b) could be either 1 or 100. I do not want to use:
`./hello_world -c "arg1 a... | Sorry to come late to the party but I just solved this with optparse using the nargs flag.
```
parser.add_option('-c','--categories', dest='Categories', nargs=4 )
```
<http://docs.python.org/2/library/optparse.html#optparse.Option.nargs>
It is also worth noting, that argparse (suggested by unutbu) is now part of the... |
Python class definition syntax | 4,109,552 | 20 | 2010-11-05T19:59:26Z | 4,109,575 | 8 | 2010-11-05T20:02:33Z | [
"python",
"class"
] | Is there a difference between
```
class A:
...
```
and
```
class A():
...
```
I just realized that a couple of my classes are defined as the former and they work just fine. Do the empty parenthesis make any difference? | The latter is a syntax error on older versions of Python. In Python 2.x you should derive from `object` whenever possible though, since several useful features are only available with [new-style classes](http://www.python.org/doc/newstyle/) (deriving from `object` is optional in Python 3.x, since new-style classes are ... |
Python class definition syntax | 4,109,552 | 20 | 2010-11-05T19:59:26Z | 4,109,579 | 20 | 2010-11-05T20:02:54Z | [
"python",
"class"
] | Is there a difference between
```
class A:
...
```
and
```
class A():
...
```
I just realized that a couple of my classes are defined as the former and they work just fine. Do the empty parenthesis make any difference? | While it might not be syntactically incorrect to use the empty parentheses in a class definition, parentheses after a class definition are used to indicate inheritance, e.g:
```
class A(baseClass):
...
```
In Python, the preferred syntax for a class declaration without any base classes is simply:
```
class A:
... |
python(or numpy) equivalent of match in R | 4,110,059 | 11 | 2010-11-05T21:02:36Z | 4,110,103 | 19 | 2010-11-05T21:07:47Z | [
"python",
"numpy"
] | Is there any easy way in python to accomplish what the match function does in R?
what match in R does is that it returns a vector of the positions of (first) matches of its first argument in its second.
For example, the following R snippet.
```
> a <- c(5,4,3,2,1)
> b <- c(2,3)
> match(a,b)
[1] NA NA 2 1 NA
```
Tr... | ```
>>> a = [5,4,3,2,1]
>>> b = [2,3]
>>> [ b.index(x) if x in b else None for x in a ]
[None, None, 1, 0, None]
```
Sum 1 if you really need position "one based" instead of "zero based".
```
>>> [ b.index(x)+1 if x in b else None for x in a ]
[None, None, 2, 1, None]
```
You can make this one-liner reusable if you ... |
Can I improve on the current Python code? | 4,110,477 | 2 | 2010-11-05T22:02:18Z | 4,110,510 | 7 | 2010-11-05T22:07:14Z | [
"python",
"loops",
"conditional"
] | I am just starting out with Python and decided to try this little project from [Python Wiki](http://en.wikibooks.org/wiki/Python_Programming/Conditional_Statements):
*Write a password guessing program to keep track of how many times the user has entered the password wrong. If it is more than 3 times, print You have be... | You can replace your while loop with the following function:
```
def login():
for i in range(3):
password = raw_input('Please enter a password: ')
if password != 'SecretPassword':
print 'You have entered invalid password {0} times.'.format(i + 1)
else:
print 'Access ... |
Change filename before save file in Django | 4,110,581 | 2 | 2010-11-05T22:19:25Z | 4,110,707 | 7 | 2010-11-05T22:42:56Z | [
"python",
"django",
"django-admin",
"django-models"
] | I have the next code to rename my files when upload in django admin (in models.py)
```
def get_file_path(instance, filename):
ext = filename.split('.')[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
return os.path.join('directory/', filename)
class Archivo(models.Model):
archivo = models.FileField(uploa... | If your goal is just preventing the files to fill up the given directory (this is a concern because depending on the filesystem, some operations over a directory with too many entries can be expensive), upload\_to can contain strftime formatting, which will be replaced by the date/time of the upload.
```
archivo = mod... |
Sort nested dictionary by value, and remainder by another value, in Python | 4,110,665 | 11 | 2010-11-05T22:35:38Z | 4,110,711 | 13 | 2010-11-05T22:43:14Z | [
"python",
"sorting",
"dictionary",
"python-2.5"
] | Consider this dictionary format.
```
{'KEY1':{'name':'google','date':20100701,'downloads':0},
'KEY2':{'name':'chrome','date':20071010,'downloads':0},
'KEY3':{'name':'python','date':20100710,'downloads':100}}
```
I'd like the dictionary sorted by downloads first, and then all items with no downloads sorted by date. ... | Use the `key` argument for `sorted()`. It lets you specify a function that, given the actual item being sorted, returns a value that should be sorted by. If this value is a tuple, then it sorts like tuples sort - by the first value, and then by the second value.
```
sorted(your_list, key=lambda x: (your_dict[x]['downl... |
Python How to simply redirect output of print to a TXT file with a new line created for each redirect | 4,110,891 | 21 | 2010-11-05T23:10:34Z | 4,110,906 | 60 | 2010-11-05T23:15:35Z | [
"python",
"printing",
"redirect"
] | I have searched with Google, Stack over flow and my Python users guide and have not found a simple, workable answer for the question, "How do I redirect a print to a .txt" file
I created a file in c: named goat.txt on a W7x64 machine and am attempting to print "test" in the file.
And have tried the following based up... | If you're on Python 2.5 or earlier, open the file and then use the file object in your redirection:
```
log = open("c:\\goat.txt", "w")
print >>log, "test"
```
If you're on Python 2.6 or 2.7, you can use print as a function:
```
from __future__ import print_function
log = open("c:\\goat.txt", "w")
print("test", file... |
Python How to simply redirect output of print to a TXT file with a new line created for each redirect | 4,110,891 | 21 | 2010-11-05T23:10:34Z | 4,111,084 | 25 | 2010-11-05T23:56:15Z | [
"python",
"printing",
"redirect"
] | I have searched with Google, Stack over flow and my Python users guide and have not found a simple, workable answer for the question, "How do I redirect a print to a .txt" file
I created a file in c: named goat.txt on a W7x64 machine and am attempting to print "test" in the file.
And have tried the following based up... | To redirect output for **all** prints, you can do this:
```
import sys
with open('c:\\goat.txt', 'w') as f:
sys.stdout = f
print "test"
``` |
Python How to simply redirect output of print to a TXT file with a new line created for each redirect | 4,110,891 | 21 | 2010-11-05T23:10:34Z | 26,557,993 | 8 | 2014-10-25T00:10:28Z | [
"python",
"printing",
"redirect"
] | I have searched with Google, Stack over flow and my Python users guide and have not found a simple, workable answer for the question, "How do I redirect a print to a .txt" file
I created a file in c: named goat.txt on a W7x64 machine and am attempting to print "test" in the file.
And have tried the following based up... | A slightly hackier way (that is different than the answers above, which are all valid) would be to just direct the output into a file via console.
So imagine you had `main.py`
```
if True:
print "hello world"
else:
print "goodbye world"
```
You can do
```
python main.py >> text.log
```
and then text.log wi... |
Python how to iterate through a list and compare lists of strings found within | 4,111,129 | 2 | 2010-11-06T00:07:47Z | 4,111,157 | 11 | 2010-11-06T00:15:04Z | [
"python",
"iteration",
"nested-lists"
] | If I have a nested list that looks like this:
`bigstringlist = [['rob', 'bob', 'sam', 'angie'], ['jim', 'angie', 'tom', 'sam'], ['sam', 'mary', 'angie', 'sally']]`
How do I iterate through this list and extract a list of names that appear in all the nested lists? i.e.:
```
finallist = ['sam', 'angie']
```
Would thi... | ```
reduce(set.intersection, map(set , bigstringlist))
``` |
Get a list of all installed applications in Django and their attributes | 4,111,244 | 24 | 2010-11-06T00:39:59Z | 4,111,265 | 8 | 2010-11-06T00:44:41Z | [
"python",
"django",
"django-models"
] | In my Django website, I'm creating a class that interact dynamically with other applications installed in the website. I have to do a manipulation on each field of each application.
So I want to save the name of all installed applications in a list and get the attributes of each one. There is a way to do that using an... | settings.INSTALLED\_APPS ???
[edit]
All applications are registered in the `settings.py` file.
```
In [1]: from django.conf import settings
In [2]: print(settings.INSTALLED_APPS)
['django.contrib.auth', 'django.contrib.contenttypes',
'django.contrib.sessions', 'django.contrib.sites',
'django.contrib.messages', ... |
Get a list of all installed applications in Django and their attributes | 4,111,244 | 24 | 2010-11-06T00:39:59Z | 4,112,290 | 44 | 2010-11-06T07:10:01Z | [
"python",
"django",
"django-models"
] | In my Django website, I'm creating a class that interact dynamically with other applications installed in the website. I have to do a manipulation on each field of each application.
So I want to save the name of all installed applications in a list and get the attributes of each one. There is a way to do that using an... | Under Django 1.6 and below.
If you want all models, try:
```
from django.db.models import get_models
for model in get_models():
# Do something with your model here
print model.__name__, [x.name for x in model._meta.fields]
```
Under Django 1.7 and above (thanks Colin Anderson):
```
from django.apps import ap... |
How do I get a list of indices of non zero elements in a list? | 4,111,412 | 20 | 2010-11-06T01:26:59Z | 4,111,417 | 39 | 2010-11-06T01:29:40Z | [
"list",
"python",
"list-comprehension"
] | I have a list that will always contain only ones and zeroes.
I need to get a list of the non-zero indices of the list:
```
a = [0, 1, 0, 1, 0, 0, 0, 0]
b = []
for i in range(len(a)):
if a[i] == 1: b.append(i)
print b
```
What would be the 'pythonic' way of achieving this ? | ```
[i for i, e in enumerate(a) if e != 0]
``` |
How do I get a list of indices of non zero elements in a list? | 4,111,412 | 20 | 2010-11-06T01:26:59Z | 6,145,753 | 18 | 2011-05-26T22:14:17Z | [
"list",
"python",
"list-comprehension"
] | I have a list that will always contain only ones and zeroes.
I need to get a list of the non-zero indices of the list:
```
a = [0, 1, 0, 1, 0, 0, 0, 0]
b = []
for i in range(len(a)):
if a[i] == 1: b.append(i)
print b
```
What would be the 'pythonic' way of achieving this ? | Not really a "new" answer but [numpy](http://numpy.scipy.org/) has this built in as well.
```
import numpy as np
a = [0, 1, 0, 1, 0, 0, 0, 0]
nonzeroind = np.nonzero(a)[0] # the return is a little funny so I use the [0]
print nonzeroind
[1 3]
``` |
how to "reimport" module to python then code be changed after import | 4,111,640 | 31 | 2010-11-06T02:49:55Z | 4,111,670 | 42 | 2010-11-06T02:58:21Z | [
"python",
"runtime",
"overloading",
"python-import"
] | I have a `foo.py`
```
def foo():
print "test"
```
In IPython I use:
```
In [6]: import foo
In [7]: foo.foo()
test
```
Then I changed the `foo()` to:
```
def foo():
print "test changed"
```
In IPython, the result for invoking is still `test`:
```
In [10]: import foo
In [11]: foo.foo()
test
```
Then I... | ```
foo = reload(foo)
``` |
how to "reimport" module to python then code be changed after import | 4,111,640 | 31 | 2010-11-06T02:49:55Z | 4,113,189 | 30 | 2010-11-06T13:01:46Z | [
"python",
"runtime",
"overloading",
"python-import"
] | I have a `foo.py`
```
def foo():
print "test"
```
In IPython I use:
```
In [6]: import foo
In [7]: foo.foo()
test
```
Then I changed the `foo()` to:
```
def foo():
print "test changed"
```
In IPython, the result for invoking is still `test`:
```
In [10]: import foo
In [11]: foo.foo()
test
```
Then I... | In addition to gnibbler's answer:
This changed in Python 3 to:
```
>>> import imp
>>> imp.reload(foo)
```
As @onnodb points out, `imp` is deprecated in favor of `importlib` since Python 3.4:
```
>>> import importlib
>>> importlib.reload(foo)
``` |
What is the most efficient way to concatenate two strings and remove everything before the first ',' in Python? | 4,111,711 | 6 | 2010-11-06T03:15:27Z | 4,111,793 | 9 | 2010-11-06T03:47:16Z | [
"python",
"algorithm",
"concatenation"
] | In Python, I have a string which is a comma separated list of values. e.g. '5,2,7,8,3,4'
I need to add a new value onto the end and remove the first value,
e.g.
'5,22,7,814,3,4' -> '22,7,814,3,4,1'
Currently, I do this as follows:
```
mystr = '5,22,7,814,3,4'
latestValue='1'
mylist = mystr.split(',')
mystr = ''
for... | Use this:
```
if mystr == '':
mystr = latestValue
else:
mystr = mystr[mystr.find(",")+1:] + "," + latestValue
```
This should be much faster than any solution which splits the list. It only finds the first occurrence of `,` and "removes" the beginning of the string. Also, if the list is empty, then `mystr` wi... |
How to zip lists in a list | 4,112,265 | 45 | 2010-11-06T06:59:28Z | 4,112,271 | 75 | 2010-11-06T07:01:35Z | [
"python",
"functional-programming"
] | I want to zip the following list of lists:
```
>>> zip([[1,2], [3,4], [5,6]])
[[1,3,5], [2,4,6]]
```
This could be achieved with the current `zip` implementation only if the list is split into individual components:
```
>>> zip([1,2], [3,4], [5,6])
(1, 3, 5), (2, 4, 6)]
```
Can't figure out how to split the list... | Try this:
```
>>> zip(*[[1,2], [3,4], [5,6]])
[(1, 3, 5), (2, 4, 6)]
```
See [Unpacking Argument Lists](http://docs.python.org/tutorial/controlflow.html#tut-unpacking-arguments):
> The reverse situation occurs when the arguments are already in a list or tuple but need to be unpacked for a function call requiring sep... |
Regular expressions in SQLalchemy queries? | 4,112,337 | 15 | 2010-11-06T07:31:12Z | 4,112,402 | 15 | 2010-11-06T08:08:15Z | [
"python",
"regex",
"sqlalchemy"
] | Is it possible to use a regex in a way similar to `session.query(MyObject).filter_by(REGEX)`?
If not, how can I use sqlAlchemy to retrieve records that have a varchar PK beginning with a certain value (e.g. all those whose *city* field begins with "SA")? Thanks. | I think I got it:
```
session.query(Object).filter(Object.column.op('regexp')(REGEX))
``` |
How to make a class method in python? | 4,112,608 | 7 | 2010-11-06T09:43:18Z | 4,112,632 | 8 | 2010-11-06T09:53:05Z | [
"python",
"ruby",
"oop"
] | In ruby you can do this:
```
class A
def self.a
'A.a'
end
end
puts A.a #-> A.a
```
How can this be done in python. I need a method of a class to be called without it being called on an instance of the class. When I try to do this I get this error:
```
unbound method METHOD must be called with CLASS ... | There are two ways to do this:
```
@staticmethod
def foo(): # No implicit parameter
print 'foo'
@classmethod
def foo(cls): # Class as implicit paramter
print cls
```
The difference is that a static method has no implicit parameters at all. A class method receives the class that it is called on in ex... |
How to make a class method in python? | 4,112,608 | 7 | 2010-11-06T09:43:18Z | 4,112,635 | 17 | 2010-11-06T09:53:25Z | [
"python",
"ruby",
"oop"
] | In ruby you can do this:
```
class A
def self.a
'A.a'
end
end
puts A.a #-> A.a
```
How can this be done in python. I need a method of a class to be called without it being called on an instance of the class. When I try to do this I get this error:
```
unbound method METHOD must be called with CLASS ... | What you're looking for is the `staticmethod` decorator, which can be used to make methods that don't require a first implicit argument. It can be used like this:
```
class A(object):
@staticmethod
def a():
return 'A.a'
```
On the other hand, if you wish to access the class (not the instance) from the... |
Writing to a .txt file (UTF-8), python | 4,112,894 | 6 | 2010-11-06T11:24:57Z | 4,112,897 | 12 | 2010-11-06T11:26:33Z | [
"python",
"save"
] | I want to save the output (`contents`) to a file (saving it in UTF-8). The file shouldn't be overwritten, it should be saved as a new file - e.g. `file2.txt`
So, I fists open a `file.txt`, encode it in UTF-8, do some stuff and then wanna save it to `file2.txt` in UTF-8. How do I do this?
```
import codecs
def openfile... | The short way:
```
file('file2.txt','w').write( file('file.txt').read().encode('utf-8') )
```
The long way:
```
data = file('file.txt').read()
... process data ...
data = data.encode('utf-8')
file('file2.txt','w').write( data )
```
And using 'codecs' explicitly:
```
codecs.getwriter('utf-8')(file('/tmp/bla3','w'))... |
Scrapy pipeline spider_opened and spider_closed not being called | 4,113,275 | 10 | 2010-11-06T13:29:32Z | 4,113,308 | 10 | 2010-11-06T13:39:49Z | [
"python",
"pipeline",
"scrapy"
] | I am having some trouble with a scrapy pipeline. My information is being scraped form sites ok and the process\_item method is being called correctly. However the spider\_opened and spider\_closed methods are not being called.
```
class MyPipeline(object):
def __init__(self):
log.msg("Initializing Pipelin... | Sorry, found it just after I posted this. You have to add:
```
dispatcher.connect(self.spider_opened, signals.spider_opened)
dispatcher.connect(self.spider_closed, signals.spider_closed)
```
in `__init__` otherwise it never receives the signal to call it |
python psycogp2 inserting into postgresql help | 4,113,910 | 3 | 2010-11-06T16:11:03Z | 4,113,922 | 8 | 2010-11-06T16:14:38Z | [
"python",
"sql",
"postgresql",
"psycopg2"
] | I have the following code to insert do an insert into my postgresql database
```
conn = psycopg2.connect("my connection setting are in here")
cur = conn.cursor()
cur.execute('INSERT INTO src_event (location_id, catname, title, name) VALUES (%i, \"%s\", \"%s\", \"%s\")' % (1441, "concert", item['title'], item['artists'... | You really, really shouldn't use python string formatting to build queries - they are prone to [SQL injection](http://initd.org/psycopg/docs/usage.html#sql-injection). And your actual problem is that you use " for quoting while you have to use ' for quoting (" quotes table/column names etc, ' quotes strings).
Use the ... |
How do I create a new file on a remote host in fabric (python deployment tool)? | 4,114,712 | 11 | 2010-11-06T19:14:12Z | 7,027,399 | 32 | 2011-08-11T14:10:42Z | [
"python",
"bash",
"fabric"
] | I'd like to create a file with the name passenger\_wsgi.py on a remote host. I'd like to use the following string to create the file's content:
```
'''
import sys, os
sys.path.insert(0, "/ruby/%s/www/%s/django-projects")
sys.path.insert(0, "/ruby/%s/www/%s/django-projects/project")
import django.core.handlers.wsgi
o... | Use StringIO with put:
```
put(StringIO(
'''
import sys, os
sys.path.insert(0, "/ruby/%s/www/%s/django-projects")
sys.path.insert(0, "/ruby/%s/www/%s/django-projects/project")
import django.core.handlers.wsgi
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'
application = django.core.handlers.wsgi.WSGIHandle... |
Python html parsing that actually works | 4,114,722 | 15 | 2010-11-06T19:17:05Z | 4,114,878 | 10 | 2010-11-06T19:49:44Z | [
"python",
"html",
"parsing"
] | I'm trying to parse some html in Python. There were some methods that actually worked before... but nowadays there's nothing I can actually use without workarounds.
* beautifulsoup has problems after SGMLParser went away
* html5lib cannot parse half of what's "out there"
* lxml is trying to be "too correct" for typica... | I've used pyparsing for a number of HTML page scraping projects. It is a sort of middle-ground between BeautifulSoup and the full HTML parsers on one end, and the too-low-level approach of regular expressions (that way lies madness).
With pyparsing, you can often get good HTML scraping results by identifying the speci... |
Python html parsing that actually works | 4,114,722 | 15 | 2010-11-06T19:17:05Z | 4,114,879 | 20 | 2010-11-06T19:49:51Z | [
"python",
"html",
"parsing"
] | I'm trying to parse some html in Python. There were some methods that actually worked before... but nowadays there's nothing I can actually use without workarounds.
* beautifulsoup has problems after SGMLParser went away
* html5lib cannot parse half of what's "out there"
* lxml is trying to be "too correct" for typica... | Make sure that you use the `html` module when you parse HTML with `lxml`:
```
>>> from lxml import html
>>> doc = """<html>
... <head>
... <title> Meh
... </head>
... <body>
... Look at this interesting use of <p>
... rather than using <br /> tags as line breaks <p>
... </body>"""
>>> html.document_fromstring(doc)
<... |
negative pow in python | 4,114,740 | 7 | 2010-11-06T19:21:15Z | 4,114,756 | 24 | 2010-11-06T19:23:34Z | [
"python",
"math",
"pow"
] | I have this problem
```
>>> import math
>>> math.pow(-1.07,1.3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
```
any suggestion ? | (-1.07)1.3 will not be a real number, thus the Math domain error.
If you need a complex number, ab must be rewritten into eb ln a, e.g.
```
>>> import cmath
>>> cmath.exp(1.3 * cmath.log(-1.07))
(-0.6418264288034731-0.8833982926856789j)
```
If you just want to return NaN, catch that exception.
```
>>> import math
>... |
negative pow in python | 4,114,740 | 7 | 2010-11-06T19:21:15Z | 4,114,776 | 9 | 2010-11-06T19:26:39Z | [
"python",
"math",
"pow"
] | I have this problem
```
>>> import math
>>> math.pow(-1.07,1.3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
```
any suggestion ? | Don't use pow, and make the exponent complex (add `0j` to it). Here is an example:
```
In [15]: (-1.07)**(1.3+0j)
Out[15]: (-0.64182642880347307-0.88339829268567893j)
```
No need for math functions :) |
Python argparse: nargs + or * depending on prior argument | 4,114,996 | 8 | 2010-11-06T20:24:37Z | 4,115,347 | 12 | 2010-11-06T21:49:45Z | [
"python",
"argparse"
] | I'm writing a server querying tool, and I have a little bit of code to parse arguments at the very top:
```
# Parse arguments
p = argparse.ArgumentParser()
g = p.add_mutually_exclusive_group(required=True)
g.add_argument('--odam', dest='query_type', action='store_const',
const='odam', help="Odamex Master query... | You can do this with an custom [argparse.Action](http://docs.python.org/dev/library/argparse.html#action):
```
import argparse
import sys
class AddressAction(argparse.Action):
def __call__(self, parser, args, values, option = None):
args.address=values
if args.query_type=='odam' and not args.addre... |
Converting UTC datetime to user's local date and time | 4,115,310 | 5 | 2010-11-06T21:39:25Z | 4,117,482 | 8 | 2010-11-07T11:23:20Z | [
"python",
"django",
"google-app-engine",
"localization"
] | I'm using python on Django and Google App Engine. I'm also using the DateTimeProperty in one of my models. Occasionally I would like to display that date and time to the user.
What is the best to convert the datetime stored in DateTimeProperty into the user's datetime?
Or a more precise way of framing the question: W... | This is more a Python question, than a GAE one, unless GAE has some infrastructure to facilitate this (I've made a quick scan but haven't found any reference).
Basically, you want to store date/times in UTC timezone (e.g. use datetime.datetime.utcnow) along with user timezones, which you can either try to extract from... |
OData Python Library available? | 4,115,506 | 37 | 2010-11-06T22:29:06Z | 5,788,020 | 13 | 2011-04-26T08:50:28Z | [
"python",
"odata"
] | I was wondering if any OData Python libraries are available to produce and consume OData?
There are implementations for different languages:
<http://www.odata.org/libraries/>
But I couldn't find Python so far. I don't mean IronPython by the way. The library should be just usable in Python. | i am the author of the library at <http://code.google.com/p/odata-py/>
it's still in its early stages but it provides the most basic functionalities (create, read, update). Don't hesitate to drop a message if you see a bug or want to contribute ;) |
Importing everything ( * ) dynamically from a module | 4,116,061 | 15 | 2010-11-07T01:20:40Z | 4,526,709 | 16 | 2010-12-24T13:59:35Z | [
"python",
"import",
"python-module"
] | I have a Python module that I want to dynamically import given only a string of the module name. Normally I use `importlib` or `__import__` and this works quite well given that I know which objects I want to import from the module, but is there a way to do the equivalent of `import *` dynamically. Or is there a better ... | Use [`update`](http://docs.python.org/library/stdtypes.html#dict.update) for dicts:
```
test = __import__('os', globals(), locals())
globals().update(test.__dict__)
```
If you need to import a package which is not top-level like `os`, it's more convenient to use `importlib`:
```
globals().update(importlib.import_mod... |
Parsing the results of askopenfilenames()? | 4,116,249 | 7 | 2010-11-07T02:28:24Z | 4,116,292 | 13 | 2010-11-07T02:45:48Z | [
"python",
"windows",
"python-3.x",
"tkinter"
] | I'm trying to get a list of filenames from tkinter.filedialog.askopenfilenames() in Python 3.2.
```
files = askopenfilenames(initialdir="C:\\Users\\BVCAP\\Videos", title="Select files")
self.num_files.set(len(files))
```
I was expecting the output to be a tuple (or maybe a list) with each element containing a... | This is actually a bug on the Windows version that has been present since around the 2.6 release of Python. You can find the issue [on their tracker](http://bugs.python.org/issue5712), and there's a workaround in the comments (I have not personally tried this workaround because I'm on Linux, which returns a proper tupl... |
Converting Python Code to PHP | 4,116,596 | 10 | 2010-11-07T05:18:04Z | 4,116,618 | 13 | 2010-11-07T05:29:36Z | [
"php",
"python",
"code-translation",
"transpiler"
] | Is there a software converter out there that can automatically convert this python code to PHP?
```
#!/usr/bin/python
import math
def calcNumEntropyBits(s):
if len(s) <= 0: return 0.0
symCount = {}
for c in s:
if c not in symCount: symCount[c] = 1
else: symCount... | I'm not aware of any Python-to-PHP converter in the wild, but it should be a trivial task to port and the similarities are quite easy to spot:
```
function calcNumEntropyBits($s) {
if (strlen($s) <= 0) return 0.0;
$symCount = array();
foreach (str_split($s) as $c) {
if (!in_arra... |
Faster numpy cartesian to spherical coordinate conversion? | 4,116,658 | 21 | 2010-11-07T05:52:19Z | 4,116,803 | 11 | 2010-11-07T07:10:32Z | [
"python",
"numpy",
"coordinate"
] | I have an array of 3 million data points from a 3-axiz accellerometer (XYZ), and I want to add 3 columns to the array containing the equivalent spherical coordinates (r, theta, phi). The following code works, but seems way too slow. How can I do better?
```
import numpy as np
import math as m
def cart2sph(x,y,z):
... | Here's a quick Cython code that I wrote up for this:
```
cdef extern from "math.h":
long double sqrt(long double xx)
long double atan2(long double a, double b)
import numpy as np
cimport numpy as np
cimport cython
ctypedef np.float64_t DTYPE_t
@cython.boundscheck(False)
@cython.wraparound(False)
def appendS... |
Faster numpy cartesian to spherical coordinate conversion? | 4,116,658 | 21 | 2010-11-07T05:52:19Z | 4,116,899 | 22 | 2010-11-07T07:54:27Z | [
"python",
"numpy",
"coordinate"
] | I have an array of 3 million data points from a 3-axiz accellerometer (XYZ), and I want to add 3 columns to the array containing the equivalent spherical coordinates (r, theta, phi). The following code works, but seems way too slow. How can I do better?
```
import numpy as np
import math as m
def cart2sph(x,y,z):
... | This is similar to [Justin Peel](http://stackoverflow.com/questions/4116658/faster-numpy-cartesian-to-spherical-coordinate-conversion/4116803#4116803)'s answer, but using just `numpy` and taking advantage of its built-in vectorization:
```
def appendSpherical_np(xyz):
ptsnew = np.hstack((xyz, np.zeros(xyz.shape)))... |
python: iterate through list and replace elements with corresponding dictionary values | 4,117,123 | 3 | 2010-11-07T09:14:51Z | 4,117,135 | 13 | 2010-11-07T09:19:30Z | [
"python",
"list",
"dictionary",
"replace"
] | I am trying to replace list element value with value looked up in dictionary how do I do that?
```
list = [1, 3, 2, 10]
d = {'id': 1, 'val': 30},{'id': 2, 'val': 53}, {'id': 3, 'val': 1}, {'id': 4, 'val': 9}, {'id': 5, 'val': 2}, {'id': 6, 'val': 6}, {'id': 7, 'val': 11}, {'id': 8, 'val': 89}, {'id': 9, 'val': 2}, ... | ```
D2 = dict((x['id'], x['val']) for x in D)
L2 = [D2[x] for x in L]
``` |
PHP in command line | 4,117,447 | 5 | 2010-11-07T11:15:11Z | 4,117,451 | 7 | 2010-11-07T11:16:24Z | [
"php",
"python",
"command-line",
"terminal",
"code-testing"
] | Using Python I can test my code in the terminal / command line by typing
```
python
python> print "hello world"
```
I would like to do this with PHP too, but when typing:
```
php
echo "hello world";
```
it does not work.. Is this possible? what should I do?
A quick search on the internet gives a lot of results tha... | Try
```
php -a
```
which starts an [interactive PHP shell](http://www.php.net/manual/en/features.commandline.interactive.php). Be aware that this requires PHP to be built with **--with-readline** (which is not the case if you're using the bundeled PHP with Mac OS X e.g.).
Alternatively, if you don't require the inte... |
sys.argv[1] meaning in script | 4,117,530 | 45 | 2010-11-07T11:41:50Z | 4,117,534 | 18 | 2010-11-07T11:44:02Z | [
"python"
] | I'm currently teaching myself Python and was just wondering (In reference to my example below) in simplified terms what the sys.argv[1] represents. Is it simply asking for an input?
```
#!/usr/bin/python3.1
# import modules used here -- sys is a very standard one
import sys
# Gather our code in a main() function
def... | [sys.argv[1]](http://docs.python.org/library/sys.html#sys.argv) contains the first [command line](http://en.wikipedia.org/wiki/Command-line_interface) [argument](http://en.wikipedia.org/wiki/Command-line_argument) passed to your script.
For example, if your script is named `hello.py` and you issue:
```
$ python3.1 he... |
sys.argv[1] meaning in script | 4,117,530 | 45 | 2010-11-07T11:41:50Z | 4,117,591 | 9 | 2010-11-07T11:59:22Z | [
"python"
] | I'm currently teaching myself Python and was just wondering (In reference to my example below) in simplified terms what the sys.argv[1] represents. Is it simply asking for an input?
```
#!/usr/bin/python3.1
# import modules used here -- sys is a very standard one
import sys
# Gather our code in a main() function
def... | Just adding to Frederic's answer, for example if you call your script as follows:
`./myscript.py foo bar`
`sys.argv[0]` would be "./myscript.py"
`sys.argv[1]` would be "foo" and
`sys.argv[2]` would be "bar" ... and so forth.
In your example code, if you call the script as follows `./myscript.py foo` , the script's... |
sys.argv[1] meaning in script | 4,117,530 | 45 | 2010-11-07T11:41:50Z | 4,118,133 | 135 | 2010-11-07T14:26:20Z | [
"python"
] | I'm currently teaching myself Python and was just wondering (In reference to my example below) in simplified terms what the sys.argv[1] represents. Is it simply asking for an input?
```
#!/usr/bin/python3.1
# import modules used here -- sys is a very standard one
import sys
# Gather our code in a main() function
def... | *I would like to note that previous answers made many assumptions about the user's knowledge. This answer attempts to answer the question at a more tutorial level.*
For every invocation of Python, `sys.argv` is automatically a list of strings representing the arguments (as separated by spaces) on the command-line. The... |
sys.argv[1] meaning in script | 4,117,530 | 45 | 2010-11-07T11:41:50Z | 15,606,349 | 8 | 2013-03-25T01:34:51Z | [
"python"
] | I'm currently teaching myself Python and was just wondering (In reference to my example below) in simplified terms what the sys.argv[1] represents. Is it simply asking for an input?
```
#!/usr/bin/python3.1
# import modules used here -- sys is a very standard one
import sys
# Gather our code in a main() function
def... | `sys.argv` is a list.
This list is created by your command line, it's a list of your command line arguments.
For example:
in your command line you input something like this,
```
python3.2 file.py something
```
`sys.argv` will become a list ['file.py', 'something']
In this case `sys.argv[1] = 'something'` |
Non-recursive os.walk() | 4,117,588 | 12 | 2010-11-07T11:57:36Z | 4,117,594 | 21 | 2010-11-07T12:00:44Z | [
"python",
"os.walk",
"non-recursive"
] | I'm looking for a way to do a non-recursive `os.walk()` walk, just like `os.listdir()` works. But I need to return in the same way the `os.walk()` returns. Any idea?
Thank you in advance. | ```
next(os.walk(...))
``` |
Get second element text with XPath? | 4,117,953 | 15 | 2010-11-07T13:39:09Z | 4,118,401 | 27 | 2010-11-07T15:37:00Z | [
"python",
"xpath",
"lxml"
] | ```
<span class='python'>
<a>google</a>
<a>chrome</a>
</span>
```
I want to get `chrome` and have it working like this already.
```
q = item.findall('.//span[@class="python"]//a')
t = q[1].text # first element = 0
```
I'd like to combine it into a single XPath expression and just get one item instead of a list. ... | > I tried this but it doesn't work.
>
> ```
> t = item.findtext('.//span[@class="python"]//a[2]')
> ```
**This is a FAQ about the `//` abbreviation**.
`.//a[2]` means: Select all `a` descendents of the current node that are the second `a` child of their parent. So this may select more than one element or no element -... |
Is 'if q and r:' evaluated separately? | 4,118,433 | 4 | 2010-11-07T15:47:01Z | 4,118,444 | 12 | 2010-11-07T15:50:24Z | [
"python"
] | It's a very simple question. Is
```
if q and r:
```
always guaranteed to be equivalent to this?
```
if q:
if r:
``` | Python's `and` and `or` are **short-circuiting** operators, so yes: in your example, if "q" is false, then the interpreter will not evaluate "r".
*edit* — after a little thought it occurs to me that it's important to note that Python's `and` and `or` work kind-of like Javascript `&&` and `||`. They do not produce a bo... |
Find the closest hour | 4,118,526 | 7 | 2010-11-07T16:10:36Z | 4,118,571 | 7 | 2010-11-07T16:22:53Z | [
"python",
"arrays",
"time"
] | I have a list with these items:
```
hours = ['19:30', '20:10', '20:30', '21:00', '22:00']
```
Assuming that now it's 20:18, how can I get the '20:10' item from list? I want to use this to find the current running show in a TV Guide. | ```
>>> import datetime
>>> hours = ['19:30', '20:10', '20:30', '21:00', '22:00']
>>> now = datetime.datetime.strptime("20:18", "%H:%M")
>>> min(hours, key=lambda t: abs(now - datetime.datetime.strptime(t, "%H:%M")))
'20:10'
``` |
I want to nest loop ten times, Is there any better way than this? | 4,118,684 | 2 | 2010-11-07T16:58:01Z | 4,118,699 | 10 | 2010-11-07T17:00:46Z | [
"python",
"perl",
"programming-languages"
] | Something like this. I want to brute force all characters with word of 10 size
```
lookup = map(chr, range(32, 127))
for i in lookup:
for j in lookup:
for k in lookup:
for l in lookup:
for m in lookup:
for n in lookup:
for o in lookup:... | [`itertools`](http://docs.python.org/library/itertools.html#itertools.permutations) is your friend.
```
>>> lookup = map(chr, range(32, 127))
>>> import itertools
>>> itertools.permutations(lookup, 10)
<itertools.permutations object at 0x023C8AE0>
```
Notice that `permutations` will give you every word, whereas `comb... |
I want to nest loop ten times, Is there any better way than this? | 4,118,684 | 2 | 2010-11-07T16:58:01Z | 4,118,870 | 15 | 2010-11-07T17:42:18Z | [
"python",
"perl",
"programming-languages"
] | Something like this. I want to brute force all characters with word of 10 size
```
lookup = map(chr, range(32, 127))
for i in lookup:
for j in lookup:
for k in lookup:
for l in lookup:
for m in lookup:
for n in lookup:
for o in lookup:... | While using the existing `itertools` package is normally better than rolling your own code, for educational value it's good to know how to do this yourself.
Obviously, nesting ten loops is not the best approach. I say "obviously" because it should immediately raise a red flag in your mind when you have to copy and pas... |
how to divide a list into n equal parts, python | 4,119,070 | 6 | 2010-11-07T18:35:43Z | 4,119,142 | 19 | 2010-11-07T18:51:48Z | [
"python",
"list",
"divide"
] | > **Possible Duplicate:**
> [How do you split a list into evenly sized chunks in Python?](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python)
Given (**any**) list of words `lst` I should divide it into 10 equal parts.
```
x = len(lst)/10
```
how to give these parts... | One-liner returning a list of lists, given a list and the chunk size:
```
>>> lol = lambda lst, sz: [lst[i:i+sz] for i in range(0, len(lst), sz)]
```
Testing:
```
>>> x = range(20, 36)
>>> print x
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35]
>>> lol(x, 4)
[[20, 21, 22, 23],
[24, 25, 26, 27],
... |
Replace Backslashes with Forward Slashes in Python | 4,119,166 | 2 | 2010-11-07T18:59:13Z | 4,119,176 | 9 | 2010-11-07T19:01:33Z | [
"python"
] | I'm writing a cross platform file explorer in python. I am trying to convert any backslashes in a path into forward slashes in order to deal with all paths in one format.
I've tried not only using string.replace(str, '\\', '/'), but also creating a method manually to search through the string and replace the instances... | You should use [`os.path`](http://docs.python.org/library/os.path.html) for this kind of stuff. |
Multiple (asynchronous) connections with urllib2 or other http library? | 4,119,680 | 11 | 2010-11-07T21:04:07Z | 4,120,071 | 8 | 2010-11-07T22:33:38Z | [
"python",
"asynchronous",
"urllib2",
"python-2.5"
] | I have code like this.
```
for p in range(1,1000):
result = False
while result is False:
ret = urllib2.Request('http://server/?'+str(p))
try:
result = process(urllib2.urlopen(ret).read())
except (urllib2.HTTPError, urllib2.URLError):
pass
results.append(resul... | Take a look at [gevent](http://www.gevent.org/) â a coroutine-based Python networking library that uses greenlet to provide a high-level synchronous API on top of libevent event loop.
Example:
```
#!/usr/bin/python
# Copyright (c) 2009 Denis Bilenko. See LICENSE for details.
"""Spawn multiple workers and wait for ... |
Multiple (asynchronous) connections with urllib2 or other http library? | 4,119,680 | 11 | 2010-11-07T21:04:07Z | 12,637,309 | 8 | 2012-09-28T09:30:24Z | [
"python",
"asynchronous",
"urllib2",
"python-2.5"
] | I have code like this.
```
for p in range(1,1000):
result = False
while result is False:
ret = urllib2.Request('http://server/?'+str(p))
try:
result = process(urllib2.urlopen(ret).read())
except (urllib2.HTTPError, urllib2.URLError):
pass
results.append(resul... | You can use asynchronous IO to do this.
[requests](https://github.com/kennethreitz/requests) + [gevent](http://www.gevent.org/) = [grequests](https://github.com/kennethreitz/grequests)
GRequests allows you to use Requests with Gevent to make asynchronous HTTP Requests easily.
```
import grequests
urls = [
'http... |
Remove all elements from the dictionary whose key is an element of a list | 4,120,705 | 4 | 2010-11-08T01:35:11Z | 4,120,783 | 10 | 2010-11-08T01:58:11Z | [
"python",
"list",
"dictionary"
] | How do you remove all elements from the dictionary whose key is a element of a list? | [**Note**: This is not direct answer but given earlier speculation that the question looks like homework. I wanted to provide help that will help solving the problem while learning from it]
**Decompose your problem which is**:
1. How to get a element from a list
2. How to delete a key:value in dictionary
Further hel... |
Remove all elements from the dictionary whose key is an element of a list | 4,120,705 | 4 | 2010-11-08T01:35:11Z | 4,120,833 | 7 | 2010-11-08T02:18:37Z | [
"python",
"list",
"dictionary"
] | How do you remove all elements from the dictionary whose key is a element of a list? | ```
map(dictionary.__delitem__, lst)
``` |
Remove all elements from the dictionary whose key is an element of a list | 4,120,705 | 4 | 2010-11-08T01:35:11Z | 4,120,910 | 8 | 2010-11-08T02:44:26Z | [
"python",
"list",
"dictionary"
] | How do you remove all elements from the dictionary whose key is a element of a list? | ```
for key in list_:
if key in dict_:
del dict_[key]
``` |
python module layout | 4,120,759 | 14 | 2010-11-08T01:51:23Z | 4,120,784 | 8 | 2010-11-08T01:59:11Z | [
"python",
"python-module"
] | I'm just starting to get to the point in my python projects that I need to start using multiple packages and I'm a little confused on exactly how everything is supposed to work together. What exactly should go into the `__init__.py` of the package? Some projects I see just have blank inits and all of their code are in ... | `__init__.py` can be empty, but what it really does is make sure Python treats your directories correctly, provide any initialization you might need for when your package is imported (configuring the environment or something along those lines), or defining `__all__` so that Python knows what to do when someone uses `fr... |
Stack performance in programming languages | 4,121,790 | 8 | 2010-11-08T06:45:43Z | 4,121,847 | 11 | 2010-11-08T06:59:19Z | [
"java",
"python",
"c",
"performance",
"ocaml"
] | Just for fun, I tried to compare the stack performance of a couple of programming languages calculating the Fibonacci series using the naive recursive algorithm. The code is mainly the same in all languages, i'll post a java version:
```
public class Fib {
public static int fib(int n) {
if (n < 2) return 1;
retur... | You say very little about your configuration (in benchmarking, details are everything: commandlines, computer used, ...)
When I try to reproduce for OCaml I get:
```
let rec f n = if n < 2 then 1 else (f (n-1)) + (f (n-2))
let () = Format.printf "%d@." (f 40)
$ ocamlopt fib.ml
$ time ./a.out
165580141
real 0m... |
Stack performance in programming languages | 4,121,790 | 8 | 2010-11-08T06:45:43Z | 4,121,856 | 17 | 2010-11-08T07:00:59Z | [
"java",
"python",
"c",
"performance",
"ocaml"
] | Just for fun, I tried to compare the stack performance of a couple of programming languages calculating the Fibonacci series using the naive recursive algorithm. The code is mainly the same in all languages, i'll post a java version:
```
public class Fib {
public static int fib(int n) {
if (n < 2) return 1;
retur... | You might want to crank up the optimisation level of your C compiler. With `gcc -O3`, that makes a big difference, a drop from 2.015 seconds to 0.766 seconds, a reduction of about 62%.
Beyond that, you need to ensure you've tested correctly. You should run each program ten times, remove the outliers (fastest and slowe... |
how can i create a websocket on google app engine for html5 | 4,121,920 | 9 | 2010-11-08T07:15:15Z | 4,122,243 | 11 | 2010-11-08T08:27:24Z | [
"javascript",
"python",
"google-app-engine",
"html5",
"websocket"
] | this is the [demo](http://html5demos.com/web-socket) that a Simple chat client , you must open it on webkit Browser like: chrome and Safari,
the demo use a web socket server based on node.js: websocket-server-node.js,
but i think it cant Deploy on google app engine ,
so did you know how to make a websocket using pyt... | I think you should wait for **Channel API**.
> **Channel API** - The Channel API lets you build applications that can push
> content directly to your userâs
> browser (aka âCometâ). No more polling
> for updates!
this is already part of the SDK but does not work in production.
[Here](http://www.youtube.com/wat... |
How can I invoke a thread multiple times in Python? | 4,122,188 | 3 | 2010-11-08T08:13:37Z | 4,122,221 | 7 | 2010-11-08T08:21:33Z | [
"python",
"multithreading"
] | I'm sorry if it is a stupid question. I am trying to use a number of classes of multi-threading to finish different jobs, which involves invoking these multi-threadings at different times for many times. But I am not sure which method to use. The code looks like this:
```
class workers1(Thread):
def __init__(sel... | there are a lot of misconceptions here:
* you can only start a specific instance of a thread once. but in your case, the for loop is looping over different instances of a thread, each instance being assigned to the variable `thread` in the loop, so there is no problem at all in calling the `start()` method over each t... |
Getting the root (head) of a DiGraph in networkx (Python) | 4,122,390 | 10 | 2010-11-08T08:57:22Z | 4,123,177 | 24 | 2010-11-08T10:54:30Z | [
"python",
"networkx",
"directed-graph"
] | I'm trying to use `networkx` to do some graph representation in a project, and I'm not sure how to do a few things that should be simple. I created a directed graph with a bunch of nodes and edges, such that there is only one root element in this graph. Now, what I'd like to do is start at the root, and then iterate th... | If by having "one root element" you mean your directed graph is a rooted tree, (http://en.wikipedia.org/wiki/Tree\_%28graph\_theory) then the root will be the only node with zero in-degree.
You can find that node in linear time (in the number of nodes) with:
```
In [1]: import networkx as nx
In [2]: G=nx.balanced_tr... |
Displaying list in Java as elegant as in Python | 4,122,517 | 6 | 2010-11-08T09:19:14Z | 4,122,666 | 16 | 2010-11-08T09:42:18Z | [
"java",
"python",
"list",
"join",
"iterator"
] | In Python it is pretty easy to display an iterable as comma separated list:
```
>>> iterable = ["a", "b", "c"]
>>> ", ".join(iterable)
'a, b, c'
```
Is there a Java way that comes close to this conciseness? (Notice that there is no "," at the end.) | Here are the versions using [Guava](http://code.google.com/p/guava-libraries/) and [Commons / Lang](http://commons.apache.org/lang/) that [Michael referred to](http://stackoverflow.com/questions/4122517/displaying-list-in-java-as-elegant-as-in-python/4122555#4122555):
```
List<String> items = Arrays.asList("a","b","c"... |
why "return 100 if i < 10 else pass" is not valid in python? | 4,122,764 | 4 | 2010-11-08T09:54:47Z | 4,122,782 | 10 | 2010-11-08T09:58:17Z | [
"python",
"if-statement"
] | All;
```
def foo(i):
return 100 if i < 10 else pass
return 200 if i < 20 else pass
return 1
```
Why this not works in python? I suppose this code may works same as:
```
def foo(i):
if i < 10:
return 100
elif i < 20:
return 200
else:
return 1
```
Thanks! | > `return 100 if i < 10 else pass`
you should read it as `return (100 if i < 10 else pass)`
so `pass` isn't a value |
why "return 100 if i < 10 else pass" is not valid in python? | 4,122,764 | 4 | 2010-11-08T09:54:47Z | 4,122,790 | 19 | 2010-11-08T10:00:17Z | [
"python",
"if-statement"
] | All;
```
def foo(i):
return 100 if i < 10 else pass
return 200 if i < 20 else pass
return 1
```
Why this not works in python? I suppose this code may works same as:
```
def foo(i):
if i < 10:
return 100
elif i < 20:
return 200
else:
return 1
```
Thanks! | In the [documentation](http://docs.python.org/2/reference/expressions.html#conditional-expressions) you will see that the "ternary operator" should be like this:
```
conditional_expression ::= or_test ["if" or_test "else" expression]
expression ::= conditional_expression | lambda_expr
```
and `pass` is ... |
why "return 100 if i < 10 else pass" is not valid in python? | 4,122,764 | 4 | 2010-11-08T09:54:47Z | 4,122,811 | 9 | 2010-11-08T10:02:42Z | [
"python",
"if-statement"
] | All;
```
def foo(i):
return 100 if i < 10 else pass
return 200 if i < 20 else pass
return 1
```
Why this not works in python? I suppose this code may works same as:
```
def foo(i):
if i < 10:
return 100
elif i < 20:
return 200
else:
return 1
```
Thanks! | read your code like this:
```
return (100 if (i < 10) else pass)
```
pass is not a value you can return.
The following code would work:
```
def foo(i):
return 100 if i < 10 else (200 if i < 20 else 1)
``` |
Csv blank rows problem with Excel | 4,122,794 | 13 | 2010-11-08T10:00:43Z | 4,122,980 | 33 | 2010-11-08T10:22:38Z | [
"python",
"excel",
"csv"
] | I have a csv file which contains rows from a sqlite3 database. I wrote the rows to the csv file using python.
When I open the csv file with Ms Excel, a blank row appears below every row, but the file on notepad is fine(without any blanks).
Does anyone know why this is happenning and how I can fix it?
Edit: I used th... | You're using `open('file.csv', 'w')`--try `open('file.csv', 'wb')`.
The Python csv module requires output files be opened in binary mode. |
Apply a list of decorators to a callable? | 4,122,815 | 4 | 2010-11-08T10:03:04Z | 4,122,845 | 11 | 2010-11-08T10:05:48Z | [
"python",
"decorator"
] | Given a list of decorator methods, how would one apply those to a callable?
For example, since:
```
@foo
@bar
def baz():
pass
```
...is the same as:
```
def baz():
pass
baz = foo(bar(baz)))
```
...one would assume that with a list of decorators (`[foo, bar]`) they could be applied to `baz` dynamically. | With yet another decorator!
```
def yad(decorators):
def decorator(f):
for d in reversed(decorators):
f = d(f)
return f
return decorator
```
example usage
```
list_of_decorators = [foo, bar]
@yad(list_of_decorators)
def foo():
print 'foo'
```
Without the decorator syntax, i... |
How do I send empty response in Django without templates | 4,123,155 | 28 | 2010-11-08T10:51:27Z | 4,123,205 | 49 | 2010-11-08T10:59:17Z | [
"python",
"ajax",
"django",
"django-views"
] | I have written a view which responds to ajax requests from browser. It's written like so -
```
@login_required
def no_response(request):
params = request.has_key("params")
if params:
# do processing
var = RequestContext(request, {vars})
return render_to_response('some_template.html', va... | `render_to_response` is a shortcut specifically for rendering a template. If you don't want to do that, just return an empty `HttpResponse`:
```
from django.http import HttpResponse
return HttpResponse('')
```
However, in this circumstance I wouldn't do that - you're signalling to the AJAX that there was an error, ... |
Python unsubscriptable | 4,123,603 | 11 | 2010-11-08T12:00:11Z | 4,123,614 | 20 | 2010-11-08T12:01:32Z | [
"python",
"typeerror"
] | What does `unsubscriptable` mean in the context of a TypeError as in:
```
TypeError: 'int' object is unsubscriptable
```
EDIT:
Short code example that results in this phenomena.
```
a=[[1,2],[5,3],5,[5,6],[2,2]]
for b in a:
print b[0]
> 1
> 5
> TypeError: 'int' object is unsubscriptable
``` | It means you tried treating an integer as an array. For example:
```
a = 1337
b = [1,3,3,7]
print b[0] # prints 1
print a[0] # raises your exception
``` |
Python unsubscriptable | 4,123,603 | 11 | 2010-11-08T12:00:11Z | 4,124,615 | 10 | 2010-11-08T14:11:37Z | [
"python",
"typeerror"
] | What does `unsubscriptable` mean in the context of a TypeError as in:
```
TypeError: 'int' object is unsubscriptable
```
EDIT:
Short code example that results in this phenomena.
```
a=[[1,2],[5,3],5,[5,6],[2,2]]
for b in a:
print b[0]
> 1
> 5
> TypeError: 'int' object is unsubscriptable
``` | The problem in your sample code is that the array "a" contains two different types: it has 4 2-element lists and one integer. You are then trying to sub-script every element in "a", including the integer element.
In other words, your code is effectively doing:
```
print [1,2][0]
print [5,3][0]
print 5[0]
print [5,6][... |
Django: Adding CSS classes when rendering form fields in a template | 4,124,220 | 30 | 2010-11-08T13:26:01Z | 4,124,698 | 20 | 2010-11-08T14:23:42Z | [
"python",
"django",
"forms"
] | I'm outputting fields of a form in a template like this `{{ form.first_name }}` and I'd like to add a class (eg. blueprint's *span-x*-class) to it. So I'd like to know if there's a nice readymade solution (template filter) for that, which I could use in the fashion `{{ form.first_name|add_class:"span-4" }}`? (I just wa... | To solve this I made my own template filter, you can apply it on any tag, not just input elements!
```
class_re = re.compile(r'(?<=class=["\'])(.*)(?=["\'])')
@register.filter
def add_class(value, css_class):
string = unicode(value)
match = class_re.search(string)
if match:
m = re.search(r'^%s$|^%s... |
Django: Adding CSS classes when rendering form fields in a template | 4,124,220 | 30 | 2010-11-08T13:26:01Z | 4,377,584 | 11 | 2010-12-07T14:18:59Z | [
"python",
"django",
"forms"
] | I'm outputting fields of a form in a template like this `{{ form.first_name }}` and I'd like to add a class (eg. blueprint's *span-x*-class) to it. So I'd like to know if there's a nice readymade solution (template filter) for that, which I could use in the fashion `{{ form.first_name|add_class:"span-4" }}`? (I just wa... | A few extra notes on how to get going with Lazerscience's very handy solution. Here's how the file looks with dependency imports:
```
import re
from django.utils.safestring import mark_safe
from django import template
register = template.Library()
class_re = re.compile(r'(?<=class=["\'])(.*)(?=["\'])')
@register.filt... |
Django: Adding CSS classes when rendering form fields in a template | 4,124,220 | 30 | 2010-11-08T13:26:01Z | 7,323,105 | 45 | 2011-09-06T16:24:19Z | [
"python",
"django",
"forms"
] | I'm outputting fields of a form in a template like this `{{ form.first_name }}` and I'd like to add a class (eg. blueprint's *span-x*-class) to it. So I'd like to know if there's a nice readymade solution (template filter) for that, which I could use in the fashion `{{ form.first_name|add_class:"span-4" }}`? (I just wa... | You only need to install Django widget\_tweaks
```
pip install django-widget-tweaks
```
After you can to do something like that on your template:
```
{{ form.search_query|attr:"type:search" }}
```
--
Read all about it [here](http://pypi.python.org/pypi/django-widget-tweaks). |
Python: multiple possible values for function arguments | 4,124,787 | 5 | 2010-11-08T14:34:53Z | 4,124,799 | 13 | 2010-11-08T14:37:38Z | [
"python",
"boolean-expression"
] | I've inherited some Python code that looks like this:
```
name = 'London'
code = '0.1'
notes = 'Capital of England'
ev = model.City(key=key, code=code, name=name or code, notes=notes)
```
In the spirit of learning, I'd like to know what's going on with the `name or code` argument. Is this saying 'Use `name` if it's n... | Almost. It says *use name if it does not evaluate to false*. [Things that evaluate to false](http://docs.python.org/library/stdtypes.html#truth-value-testing) include, but are not limited to:
* `False`
* empty sequences (`(), [], ""`)
* empty mappings (`{}`)
* 0
* `None`
**Edit** Added the link provided by [SilentGho... |
Python: multiple possible values for function arguments | 4,124,787 | 5 | 2010-11-08T14:34:53Z | 4,124,808 | 7 | 2010-11-08T14:38:34Z | [
"python",
"boolean-expression"
] | I've inherited some Python code that looks like this:
```
name = 'London'
code = '0.1'
notes = 'Capital of England'
ev = model.City(key=key, code=code, name=name or code, notes=notes)
```
In the spirit of learning, I'd like to know what's going on with the `name or code` argument. Is this saying 'Use `name` if it's n... | In python, the `or` operator returns the first operand, unless it evaluates to false, in which case it returns the second operand. In effect this will use `name`, with a default fallback of `code` if `name` is not specified. |
Python and d-bus: How to set up main loop? | 4,125,393 | 10 | 2010-11-08T15:45:56Z | 4,129,416 | 7 | 2010-11-09T00:32:39Z | [
"python",
"dbus",
"pygobject"
] | I have a problem with python and dbus. I checked out the developer docs and specifications, but I don't understand how to set up a main loop. I want to listen for notification events.
See
<http://dbus.freedesktop.org/doc/dbus-python/doc/>
and
<http://www.galago-project.org/specs/notification/0.9/index.html>
My exam... | Put `import gobject` at the top of your code, and after instantiating your object, do `gobject.MainLoop().run()`. I think that the `MainLoop` has to be created after the `DBusGMainLoop` is created. |
Google Protocol Buffers, HDF5, NumPy comparison (transferring data) | 4,125,855 | 8 | 2010-11-08T16:34:35Z | 4,128,544 | 9 | 2010-11-08T22:06:42Z | [
"python",
"numpy",
"hdf5"
] | I need help to make decision. I have a need to transfer some data in my application and have to make a choice between these 3 technologies.
I've read about all technologies a little bit (tutorials, documentation) but still can't decide...
How do they compare?
I need support of metadata (capability to receive file and... | There does seem to be a slight contradiction in your question - you want to be able to store Python objects, but you also want C/C++ access. I think that regardless of which choice you go with, you will need to convert your fancy Python data structures into more static structures such as arrays.
If you need cross-lang... |
Using decorators on lambdas in Python? | 4,125,893 | 9 | 2010-11-08T16:38:15Z | 4,125,914 | 20 | 2010-11-08T16:40:23Z | [
"python",
"syntax",
"lambda",
"decorator"
] | Is there any syntax for using a decorator on a lambda function in Python? Example:
```
def simpledecorator(f):
def new_f():
print "Using a decorator: "
f()
return new_f
@simpledecorator
def hello():
print "Hello world!"
```
Results in this output:
```
>>> hello()
Using a simple deco... | ```
f = anotherdecorator(lambda x: x * 2)
``` |
How can this function be rewritten to implement OrderedDict? | 4,126,348 | 10 | 2010-11-08T17:32:23Z | 4,127,426 | 25 | 2010-11-08T19:49:13Z | [
"python",
"xml",
"collections",
"lxml"
] | I have the following function which does a crude job of parsing an XML file into a dictionary.
Unfortunately, since Python dictionaries are not ordered, I am unable to cycle through the nodes as I would like.
How do I change this so it outputs an ordered dictionary which reflects the original order of the nodes when ... | You could use the new [`OrderedDict`](http://docs.python.org/library/collections.html?highlight=ordereddict#collections.OrderedDict) `dict` subclass which was added to the standard library's `collections` module in version 2.7\*. Actually what you need is an `Ordered`+`defaultdict` combination which doesn't existâbut... |
python-pip yum package provides pip-python instead of pip | 4,126,745 | 18 | 2010-11-08T18:23:26Z | 4,126,785 | 11 | 2010-11-08T18:27:46Z | [
"python",
"fedora",
"distribute"
] | I installed `python-pip` package via `yum` (using Fedora's updates repo). It does not add the `pip` script to my `PATH` though.
```
$ which pip
/usr/bin/which: no pip in
(/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/bin:/bin:
/usr/bin:/usr/local/sbin:/usr/sbin:/sbin)
```
It does, h... | It is probably to avoid a conflict with another package that has an executable called `pip`. As long as you don't install that package, you should be safe.
Another annoying example of this is the chromium browser, which my distro's executable is `chromium-browser` to avoid a conflict with some game I had never heard o... |
python-pip yum package provides pip-python instead of pip | 4,126,745 | 18 | 2010-11-08T18:23:26Z | 5,943,675 | 34 | 2011-05-09T23:42:07Z | [
"python",
"fedora",
"distribute"
] | I installed `python-pip` package via `yum` (using Fedora's updates repo). It does not add the `pip` script to my `PATH` though.
```
$ which pip
/usr/bin/which: no pip in
(/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/bin:/bin:
/usr/bin:/usr/local/sbin:/usr/sbin:/sbin)
```
It does, h... | If you install the `python-pip` package and then run:
```
pip-python install -U pip
```
pip will fix itself. |
Transforming the string representation of a dictionary into a real dictionary | 4,127,344 | 5 | 2010-11-08T19:37:41Z | 4,127,355 | 11 | 2010-11-08T19:40:09Z | [
"python",
"string",
"dictionary",
"numpy"
] | I am working on an image processing script. I need to let the user specify how to remap some classes in an image via a text file. The syntax in this file should be simple and self-evident. What I thought of doing is to get the user to write the string version of a dictionary:
```
125:126, 126:126, 127:128, 128:128
```... | You can use [`ast.literal_eval`](http://docs.python.org/library/ast.html#ast.literal_eval):
```
>>> import ast
>>> ast.literal_eval('{' + s + '}')
{128: 128, 125: 126, 126: 126, 127: 128}
```
Note that this requires Python 2.6 or newer.
An alternative is to split the string on `','` and then split each piece on `':'... |
Genshi: if/else | 4,127,626 | 6 | 2010-11-08T20:12:17Z | 4,127,799 | 7 | 2010-11-08T20:32:54Z | [
"python",
"pylons",
"genshi"
] | How do I do a simple if/else in the Genshi templating language?
I've found [this ticket](http://genshi.edgewall.org/ticket/134), which seems to suggest that Genshi doesn't support if/else, but it doesn't really explain what it supports instead.
I basically just want something like this:
```
<py:if test="c.row.curr... | Currently, you can not if do else constructs in Genshi, and as far as I'm aware, there are no plans to add it. Instead, like you mentioned, use py:choose. The following is how you use py:choose as a type of if/else construct:
```
<py:choose ...>
<py:when test="...">
${c.row.currency.upper()}
</py:when>
<py:o... |
Override operator + to make date + time = datetime in Python | 4,127,805 | 7 | 2010-11-08T20:33:25Z | 4,127,832 | 12 | 2010-11-08T20:37:08Z | [
"python",
"operator-overloading"
] | I have a couple classes extending builtin datetime.\*
Is there any good reason to not overload + (`MyTime.__radd___`) so MyDate + MyTime returns a MyDateTime? | This would generally be frowned upon because you're really combining rather than adding; this is why the actual datetime library has a [combine](http://docs.python.org/library/datetime.html#datetime.datetime.combine) method rather than using addition in this way.
I'm not aware of any other cases in Python where `<inst... |
Override operator + to make date + time = datetime in Python | 4,127,805 | 7 | 2010-11-08T20:33:25Z | 4,127,866 | 16 | 2010-11-08T20:42:02Z | [
"python",
"operator-overloading"
] | I have a couple classes extending builtin datetime.\*
Is there any good reason to not overload + (`MyTime.__radd___`) so MyDate + MyTime returns a MyDateTime? | This is already implemented as a class method, [`datetime.datetime.combine`](http://docs.python.org/library/datetime#datetime.datetime.combine):
```
import datetime
d = datetime.date(2010, 12, 5)
t = datetime.time(10, 22, 15)
dt = datetime.datetime.combine(d, t)
print dt
```
prints
```
2010-12-05 10:22:15
``` |
Replace string within file contents | 4,128,144 | 30 | 2010-11-08T21:16:35Z | 4,128,192 | 90 | 2010-11-08T21:20:55Z | [
"python",
"string",
"file-io"
] | How can I open a file, Stud.txt, and then replace any occurences of "A" with "Orange"? | ```
with open("out.txt", "wt") as fout:
with open("Stud.txt", "rt") as fin:
for line in fin:
fout.write(line.replace('A', 'Orange'))
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.