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 |
|---|---|---|---|---|---|---|---|---|---|
Reverse loop inside a loop with same list | 2,095,068 | 2 | 2010-01-19T16:34:05Z | 2,095,111 | 7 | 2010-01-19T16:39:16Z | [
"python",
"loops",
"for-loop",
"reverse"
] | ```
num = list(str(1234567))
for n1 in num:
print n1
for n2 in reversed(num):
print '\t', n2
```
On each iteration, it prints the first digit from the first loop and all 7 from the reverse loop. How can I print not all digits but only the last (i.e first) digit from reverse loop?
Thanks | Simplest way is to just zip the forward and reverse lists together:
```
for n1, n2 in izip(num, reversed(num)):
print n1, '\t', n2
``` |
First Python Program - Multiple Errors | 2,095,298 | 2 | 2010-01-19T17:03:39Z | 2,095,334 | 10 | 2010-01-19T17:08:20Z | [
"python"
] | I am trying to write a python program that will eventually take a command line argument of a file, determine if its a tar or zip etc file and then exctract it accordingly. I am just trying to get the tar part working now and I am getting multiple errors. The file I am checking for resides in my ~/ directory. Any ideas ... | You can clearly see in your error it states
```
NameError: global name 'ReadError' is not defined
```
ReadError is not a global python name. If you look at the [tarfile](http://docs.python.org/library/tarfile.html#tarfile.ReadError) documentation you will see ReadError is part of that modules exceptions. So in this c... |
Check even/odd for Palindrome? | 2,095,404 | 3 | 2010-01-19T17:16:10Z | 2,095,416 | 8 | 2010-01-19T17:17:41Z | [
"python",
"testing",
"palindrome"
] | Is it a good idea to check for odd/even length of a palindrome number/string? Most snippets I came across don't do this basic test. If length is even, it can't be a palindrome, no?
```
if len(var) % 2 != 0:
# could be a palindrome, continue...
else:
break
```
Or is it just better (i.e faster) to start comparing t... | baab = palindrome and has length of 4 which is even |
Check even/odd for Palindrome? | 2,095,404 | 3 | 2010-01-19T17:16:10Z | 2,095,444 | 20 | 2010-01-19T17:20:30Z | [
"python",
"testing",
"palindrome"
] | Is it a good idea to check for odd/even length of a palindrome number/string? Most snippets I came across don't do this basic test. If length is even, it can't be a palindrome, no?
```
if len(var) % 2 != 0:
# could be a palindrome, continue...
else:
break
```
Or is it just better (i.e faster) to start comparing t... | [ABBA](http://www.abbasite.com/) - an example of [palindrome](https://en.wikipedia.org/wiki/Palindrome) of four letters meaning even length.
> A **palindrome** is a word, phrase, [number](https://en.wikipedia.org/wiki/Palindromic_number), or other sequence of [characters](https://en.wikipedia.org/wiki/Character_(symbo... |
Check even/odd for Palindrome? | 2,095,404 | 3 | 2010-01-19T17:16:10Z | 2,095,577 | 10 | 2010-01-19T17:36:45Z | [
"python",
"testing",
"palindrome"
] | Is it a good idea to check for odd/even length of a palindrome number/string? Most snippets I came across don't do this basic test. If length is even, it can't be a palindrome, no?
```
if len(var) % 2 != 0:
# could be a palindrome, continue...
else:
break
```
Or is it just better (i.e faster) to start comparing t... | The easiest way to check for a palindrome is to simply compare the string against it's reverse:
```
def ispalindrome(s):
return s == s[::-1]
```
This uses extended slices with a negative step to walk backwards through `s` and get the reverse. |
Python: arguments for using itertools to split a list into groups | 2,095,637 | 5 | 2010-01-19T17:47:23Z | 2,095,838 | 15 | 2010-01-19T18:11:37Z | [
"python"
] | This is a question about the relative merits of fast code that uses the standard library but is obscure (at least to me) versus a hand-rolled alternative. In this [thread](http://stackoverflow.com/questions/1825907/python-how-do-i-split-a-list-into-groups-closed) (and others that it duplicates), it seems the "Pythonic"... | When you reuse tools from the standard library, rather than "reinventing the wheel" by coding them yourself from scratch, you're not only getting well-optimized and tuned software (sometimes amazingly so, as often in the case of `itertools` components): more importantly, you're getting large amounts of functionality th... |
Closest language to Python's syntax that is more low level language! | 2,096,015 | 5 | 2010-01-19T18:32:36Z | 2,096,045 | 12 | 2010-01-19T18:37:29Z | [
"python",
"programming-languages",
"syntax",
"low-level"
] | I guess topic says it all! But, I really wan't a syntax similar to Python's! And low-level... like C++ for example. I guess Java and C# is OK too, but I really have a huge problem with the { }, and always ; <-- and each line. I hate it so much... | [Cython](http://www.cython.org/) is a lower-level language with a syntax similar to Python's. |
Closest language to Python's syntax that is more low level language! | 2,096,015 | 5 | 2010-01-19T18:32:36Z | 2,096,048 | 15 | 2010-01-19T18:37:45Z | [
"python",
"programming-languages",
"syntax",
"low-level"
] | I guess topic says it all! But, I really wan't a syntax similar to Python's! And low-level... like C++ for example. I guess Java and C# is OK too, but I really have a huge problem with the { }, and always ; <-- and each line. I hate it so much... | [cython](http://www.cython.org/) may be pretty close to what you want: syntax just about identical to Python, and you can basically write C-level code in it. It's tuned to generate Python-usable extensions, but you could then "freeze" them into a stand-alone executable.
[boo](http://boo.codehaus.org/) is another langu... |
When Does It Make Sense To Rewrite A Python Module in C? | 2,096,334 | 3 | 2010-01-19T19:19:28Z | 2,096,344 | 14 | 2010-01-19T19:20:56Z | [
"python",
"c",
"optimization"
] | In a game that I am writing, I use a 2D vector class which I have written to handle the speeds of the objects. This is called a large number of times every frame as there are a lot of objects on the screen, so any increase I can make in its speed will be useful.
It is pretty simple, consisting mostly of wrappers to th... | If you're vector-munging, give [numpy](http://numpy.scipy.org/) a try first. Chances are you will get speeds not far from C if you utilize numpy's vector manipulation functions wisely.
Other than that, your question is very heuristic. If your code is too slow:
1. Profile it - chances are you'll be able to improve it ... |
When Does It Make Sense To Rewrite A Python Module in C? | 2,096,334 | 3 | 2010-01-19T19:19:28Z | 2,096,358 | 9 | 2010-01-19T19:22:19Z | [
"python",
"c",
"optimization"
] | In a game that I am writing, I use a 2D vector class which I have written to handle the speeds of the objects. This is called a large number of times every frame as there are a lot of objects on the screen, so any increase I can make in its speed will be useful.
It is pretty simple, consisting mostly of wrappers to th... | First measure then optimize |
Sphinx - generate automatic references to Trac tickets and changesets | 2,096,401 | 5 | 2010-01-19T19:27:05Z | 2,111,327 | 9 | 2010-01-21T17:23:54Z | [
"python",
"trac",
"python-sphinx",
"restructuredtext"
] | Is [Sphinx](http://sphinx.pocoo.org/), is there way to automatically link text like `#112` or `r1023` to the corresponding tickets/changesets in [Trac](http://trac.edgewall.org/)?
For eg:
```
#112 -> http://mytracsite/tickets/112
r1023 -> http://mytracsite/changeset/1023
```
See [TracLinks](http://trac.edgewall.org... | If you put this in your config.py
```
trac_url = 'http://mytratsite/'
from docutils import nodes, utils
from docutils.parsers.rst import roles
import urllib
def trac_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
ref = trac_url + '/intertrac/' + urllib.quote(text, safe='')
node = nodes.refer... |
counting combinations and permutations efficiently | 2,096,573 | 22 | 2010-01-19T19:52:03Z | 2,096,714 | 20 | 2010-01-19T20:11:44Z | [
"python",
"algorithm",
"math",
"combinations",
"permutation"
] | I have some code to count permutations and combinations, and I'm trying to make it work better for large numbers.
I've found a better algorithm for permutations that avoids large intermediate results, but I still think I can do better for combinations.
So far, I've put in a special case to reflect the symmetry of nCr... | if n is not far from r then using the recursive definition of combination is probably better, since xC0 == 1 you will only have a few iterations:
The relevant recursive definition here is:
nCr = (n-1)C(r-1) \* n/r
This can be nicely computed using tail recursion with the following list:
[(n - r, 0), (n - r + 1, 1),... |
counting combinations and permutations efficiently | 2,096,573 | 22 | 2010-01-19T19:52:03Z | 2,096,894 | 16 | 2010-01-19T20:40:55Z | [
"python",
"algorithm",
"math",
"combinations",
"permutation"
] | I have some code to count permutations and combinations, and I'm trying to make it work better for large numbers.
I've found a better algorithm for permutations that avoids large intermediate results, but I still think I can do better for combinations.
So far, I've put in a special case to reflect the symmetry of nCr... | Two fairly simple suggestions:
1. To avoid overflow, do everything in log space. Use the fact that log(a \* b) = log(a) + log(b), and log(a / b) = log(a) - log(b). This makes it easy to work with very large factorials: log(n! / m!) = log(n!) - log(m!), etc.
2. Use the gamma function instead of factorial. You can find ... |
how to safely generate a SQL LIKE statement using python db-api | 2,097,475 | 12 | 2010-01-19T22:02:03Z | 2,097,551 | 14 | 2010-01-19T22:12:17Z | [
"python",
"sql",
"sql-like",
"python-db-api"
] | I am trying to assemble the following SQL statement using python's db-api:
```
SELECT x FROM myTable WHERE x LIKE 'BEGINNING_OF_STRING%';
```
where BEGINNING\_OF\_STRING should be a python var to be safely filled in through the DB-API. I tried
```
beginningOfString = 'abc'
cursor.execute('SELECT x FROM myTable WHER... | It's best to separate the parameters from the sql if you can.
Then you can let the db module take care of proper quoting of the parameters.
```
sql='SELECT x FROM myTable WHERE x LIKE %s'
args=[beginningOfString+'%']
cursor.execute(sql,args)
``` |
Should I create each class in its own .py file? | 2,098,088 | 23 | 2010-01-19T23:49:00Z | 2,098,096 | 21 | 2010-01-19T23:51:30Z | [
"python"
] | I'm quite new to Python in general.
I'm aware that I can create multiple classes in the same .py file, but I'm wondering if I should create each class in its own .py file.
In C# for instance, I would have a class that handles all Database interactions. Then another class that had the business rules.
Is this the case... | No. Typical Python style is to put related classes in the same module. It may be that a class ends up in a module of its own (especially if it's a large class), but it should not be a goal in its own right. And when you do, please do not name the module after the class -- you'll just end up confusing yourself and other... |
setting referral url in python urllib.urlretrieve | 2,098,623 | 5 | 2010-01-20T02:12:21Z | 2,098,655 | 9 | 2010-01-20T02:19:11Z | [
"python",
"html"
] | I am using `urllib.urlretrieve` in Python to download websites. Though some websites seem to not want me to download them, unless they have a proper referrer from their own site. Does anybody know of a way I can set a referrer in one of Python's libraries or a external one to. | ```
import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
r = urllib2.urlopen(req)
```
adopted from <http://docs.python.org/library/urllib2.html> |
Python List indexed by tuples | 2,098,695 | 3 | 2010-01-20T02:32:25Z | 2,098,702 | 8 | 2010-01-20T02:34:32Z | [
"python",
"list",
"matlab",
"list-comprehension"
] | I'm a Matlab user needing to use Python for some things, I would really appreciate it if someone can help me out with Python syntax:
(1) Is it true that lists can be indexed by tuples in Python? If so, how do I do this? For example, I would like to use that to represent a matrix of data.
(2) Assuming I can use a list... | You should look into [numpy](http://numpy.scipy.org/), it's made for just this sort of thing. |
using django and twisted together | 2,099,189 | 5 | 2010-01-20T05:12:28Z | 2,099,238 | 10 | 2010-01-20T05:30:51Z | [
"python",
"django",
"chat",
"twisted",
"forums"
] | 1)I want to devlop a website that has forums and chat.**The chat and forums are linked in some way**.Meaning for each thread the users can chat in the chat room for that thread or can post a reply to the forum.
I was thinking of using django for forums and twisted for chat thing.Can i combine the two?
The chat applicat... | I would not combine the two per se; calls into Django would happen synchronously which means that Twisted's event loop would be blocked. Better to treat the Twisted process as a [standalone app using Django](http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/) and to have a classic web server handle the... |
using django and twisted together | 2,099,189 | 5 | 2010-01-20T05:12:28Z | 2,106,609 | 10 | 2010-01-21T02:58:12Z | [
"python",
"django",
"chat",
"twisted",
"forums"
] | 1)I want to devlop a website that has forums and chat.**The chat and forums are linked in some way**.Meaning for each thread the users can chat in the chat room for that thread or can post a reply to the forum.
I was thinking of using django for forums and twisted for chat thing.Can i combine the two?
The chat applicat... | I have a project going that might be just what you are looking for (at least to get started). It is called Hotdot: <http://github.com/clemesha/hotdot> .
Also, I wrote up more details about this topic here: <http://clemesha.org/blog/2009/dec/17/realtime-web-apps-python-django-orbited-twisted/> |
Does IronPython and Jython have the same GIL issues as CPython? | 2,099,405 | 2 | 2010-01-20T06:17:30Z | 2,099,421 | 8 | 2010-01-20T06:21:32Z | [
"python",
"ironpython",
"jython"
] | I read about the problems with CPython and CPU bound threads and the GIL and some changes in Python 3.2.
Do IronPython and Jython have this same problem?
Thanks | No, neither have a GIL at all.
See [previous answer about Jython](http://stackoverflow.com/questions/1120354/does-jython-have-the-gil) and I[ronPython wiki page](http://wiki.python.org/moin/IronPython). |
tips on creating RSS/XML easily in python | 2,099,666 | 4 | 2010-01-20T07:23:46Z | 2,101,186 | 10 | 2010-01-20T12:12:00Z | [
"python",
"xml",
"rss"
] | I have a list if these 3 items: title and link and a html based description and I am looking for a library or external tool which can be fed these 3 items and create a rss xml page. Does such a thing exist? | I suggest you use a template and feed the list of items to the template.
Example [Jinja2](http://jinja.pocoo.org/2/) template (Atom, not RSS, but you get the idea), assuming that the items are 3-tuples (title, link, html):
```
<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<auth... |
python wraps.who can give a example | 2,099,788 | 2 | 2010-01-20T07:53:04Z | 2,099,793 | 7 | 2010-01-20T07:55:52Z | [
"python"
] | ```
from functools import wraps
def a():
a='aa'
def b():
b="bbb"
c=wraps(a)(b)
print c#what happen?
```
What is the wraps mean, example is the best. | Quoted from [the documentation](http://docs.python.org/library/functools.html#functools.wraps):
```
functools.wraps(wrapped[, assigned][, updated])
```
This is a convenience function for invoking `partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)` as a function decorator when defining a wra... |
sort csv by column | 2,100,353 | 14 | 2010-01-20T09:47:32Z | 2,100,384 | 32 | 2010-01-20T09:51:50Z | [
"python",
"csv",
"sorting",
"parsing"
] | I want to sort a CSV table by date. Started out being a simple task:
```
import sys
import csv
reader = csv.reader(open("files.csv"), delimiter=";")
for id, path, title, date, author, platform, type, port in reader:
print date
```
I used Python's CSV module to read in a file with that structure:
```
id;file;de... | ```
import operator
sortedlist = sorted(reader, key=operator.itemgetter(3), reverse=True)
```
or use lambda
```
sortedlist = sorted(reader, key=lambda row: row[3], reverse=True)
``` |
sort csv by column | 2,100,353 | 14 | 2010-01-20T09:47:32Z | 2,100,963 | 7 | 2010-01-20T11:28:24Z | [
"python",
"csv",
"sorting",
"parsing"
] | I want to sort a CSV table by date. Started out being a simple task:
```
import sys
import csv
reader = csv.reader(open("files.csv"), delimiter=";")
for id, path, title, date, author, platform, type, port in reader:
print date
```
I used Python's CSV module to read in a file with that structure:
```
id;file;de... | The reader acts like a generator. On a file with some fake data:
```
>>> import sys, csv
>>> data = csv.reader(open('data.csv'),delimiter=';')
>>> data
<_csv.reader object at 0x1004a11a0>
>>> data.next()
['a', ' b', ' c']
>>> data.next()
['x', ' y', ' z']
>>> data.next()
Traceback (most recent call last):
File "<std... |
Is there a javascript equivalent to unpack sequences like in python? | 2,100,731 | 11 | 2010-01-20T10:48:23Z | 2,100,754 | 10 | 2010-01-20T10:53:06Z | [
"javascript",
"python",
"iterable-unpacking"
] | Is there a javascript equivalent to unpack sequences like in python?
```
a, b = (1, 2)
``` | There isn't. JavaScript doesn't have such syntax sugar. |
Making a web interface to a script that takes 30 minutes to execute | 2,101,052 | 7 | 2010-01-20T11:47:10Z | 2,101,113 | 12 | 2010-01-20T12:00:21Z | [
"python",
"http-headers",
"timeout",
"http-status-code-504"
] | I wrote a python script to process some data from CSV files. The script takes between 3 to 30 minutes to complete, depending on the size of the CSV.
Now I want to put in a web interface to this, so I can upload the CSV data files from anywhere. I wrote a basic HTTP POST upload page and used Python's CGI module - but t... | I would separate the work like this:
1. A web app URL that accept the POSTed CSV file. The web app puts the CSV content into an off line queue, for instance a database table. The web app's response should be an unique ID for the queued item (use an auto-incremented ID column, for instance). The client must store this ... |
Parsing a stdout in Python | 2,101,426 | 7 | 2010-01-20T12:54:41Z | 2,101,448 | 27 | 2010-01-20T12:58:23Z | [
"python"
] | In Python I need to get the version of an external binary I need to call in my script.
Let's say that I want to use [Wget](http://en.wikipedia.org/wiki/Wget) in Python and I want to know its version.
I will call
```
os.system( "wget --version | grep Wget" )
```
and then I will parse the outputted string.
How to re... | One "old" way is:
```
fin,fout=os.popen4("wget --version | grep Wget")
print fout.read()
```
The other modern way is to use a `subprocess` module:
```
import subprocess
cmd = subprocess.Popen('wget --version', shell=True, stdout=subprocess.PIPE)
for line in cmd.stdout:
if "Wget" in line:
print line
``` |
Parsing a stdout in Python | 2,101,426 | 7 | 2010-01-20T12:54:41Z | 2,101,458 | 8 | 2010-01-20T13:00:34Z | [
"python"
] | In Python I need to get the version of an external binary I need to call in my script.
Let's say that I want to use [Wget](http://en.wikipedia.org/wiki/Wget) in Python and I want to know its version.
I will call
```
os.system( "wget --version | grep Wget" )
```
and then I will parse the outputted string.
How to re... | Use the `subprocess` module:
```
from subprocess import Popen, PIPE
p1 = Popen(["wget", "--version"], stdout=PIPE)
p2 = Popen(["grep", "Wget"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
``` |
Python state-machine design | 2,101,961 | 34 | 2010-01-20T14:22:22Z | 2,102,001 | 30 | 2010-01-20T14:27:44Z | [
"python",
"state-machines",
"fsm"
] | Related to this **[SO question (C state-machine design)](http://stackoverflow.com/questions/1647631/c-state-machine-design)**, could you SO folks share with me (and the community!) your Python state-machine design techniques?
**Update3**: At the moment, I am going for an engine based on the following:
```
class Track... | I don't really get the question. The **State** Design pattern is pretty clear. See the [Design Patterns book](http://rads.stackoverflow.com/amzn/click/0201633612).
```
class SuperState( object ):
def someStatefulMethod( self ):
raise NotImplementedError()
def transitionRule( self, input ):
rais... |
Python state-machine design | 2,101,961 | 34 | 2010-01-20T14:22:22Z | 2,102,191 | 8 | 2010-01-20T14:51:51Z | [
"python",
"state-machines",
"fsm"
] | Related to this **[SO question (C state-machine design)](http://stackoverflow.com/questions/1647631/c-state-machine-design)**, could you SO folks share with me (and the community!) your Python state-machine design techniques?
**Update3**: At the moment, I am going for an engine based on the following:
```
class Track... | There is [this design pattern](http://wiki.python.org/moin/State%20Machine%20via%20Decorators) for using decorators to implement state machines. From the description on the page:
> Decorators are used to specify which methods are the event handlers for the class.
There is example code on the page as well (it is quite... |
Python state-machine design | 2,101,961 | 34 | 2010-01-20T14:22:22Z | 2,103,398 | 11 | 2010-01-20T17:19:18Z | [
"python",
"state-machines",
"fsm"
] | Related to this **[SO question (C state-machine design)](http://stackoverflow.com/questions/1647631/c-state-machine-design)**, could you SO folks share with me (and the community!) your Python state-machine design techniques?
**Update3**: At the moment, I am going for an engine based on the following:
```
class Track... | In the April, 2009 issue of Python Magazine, I wrote an article on embedding a State DSL within Python, using pyparsing and imputil. This code would allow you to write the module trafficLight.pystate:
```
# trafficLight.pystate
# define state machine
statemachine TrafficLight:
Red -> Green
Green -> Yellow
... |
Is it possible to make user input invisible as a 'sudo' password input? | 2,101,975 | 8 | 2010-01-20T14:24:24Z | 2,101,992 | 13 | 2010-01-20T14:26:51Z | [
"python",
"input",
"console",
"user",
"interaction"
] | I'm using **raw\_input()** to receive password from user in interactive mode, but I want to make input symbols invisible for security reasons, as it is when you're typing your password using *sudo* or connecting to a database. How I should do it? | You need the [`getpass`](http://docs.python.org/library/getpass.html) module.
```
from getpass import getpass
password = getpass()
``` |
trapping a MySql warning | 2,102,251 | 24 | 2010-01-20T14:59:39Z | 2,102,315 | 34 | 2010-01-20T15:06:59Z | [
"python",
"mysql"
] | In my python script I would like to trap a "Data truncated for column 'xxx'" warning durnig my query using MySql.
I saw some posts suggesting the code below, but it doesn' work.
Do you know if some specific module must be imported or if some option/flag should be called before using this code?
Thanks all
Afeg
```
... | Warnings are just that: warnings. They get reported to (usually) stderr, but nothing else is done. You can't catch them like exceptions because they aren't being raised.
You can, however, configure what to *do* with warnings, and turn them off or turn them into exceptions, using the `warnings` module. For instance, `w... |
Why do I need the DJANGO_SETTINGS_MODULE set? | 2,102,330 | 13 | 2010-01-20T15:08:08Z | 2,102,365 | 11 | 2010-01-20T15:12:22Z | [
"python",
"django"
] | Every time I log on to my server through SSH I need to type the following:
```
export DJANGO_SETTINGS_MODULE=settings
```
if I do not any usage of the manage.py module fails
My manage.py has the following added code:
```
if "notification" in settings.INSTALLED_APPS:
from notification import models as notificati... | Your`manage.py` is referencing an application (`notifications`). This forces Django to complain about DJANGO\_SETTINGS\_MODULE being set because the Django environment hasn't been set up yet.
Incidentally, you can force the enviroment setup manually, but honestly I wouldn't do this in manage.py. That's not really a go... |
why this dos command does not work inside python? | 2,102,452 | 3 | 2010-01-20T15:24:14Z | 2,102,476 | 12 | 2010-01-20T15:26:32Z | [
"python",
"subprocess"
] | I try to move some dos command from my batch file into python but get this error, The filename, directory name, or volume label syntax is incorrect, for the following statement.
```
subprocess.Popen('rd /s /q .\ProcessControlSimulator\bin', shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOU... | `\` (backslash) is an escape character within string constants, so your string ends up changed. Use double `\`s (like so `\\`) within string constants:
```
subprocess.Popen('rd /s /q .\\ProcessControlSimulator\\bin', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
``` |
why this dos command does not work inside python? | 2,102,452 | 3 | 2010-01-20T15:24:14Z | 2,102,506 | 7 | 2010-01-20T15:29:25Z | [
"python",
"subprocess"
] | I try to move some dos command from my batch file into python but get this error, The filename, directory name, or volume label syntax is incorrect, for the following statement.
```
subprocess.Popen('rd /s /q .\ProcessControlSimulator\bin', shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOU... | You've got unescaped backslashes. You can use a python raw string to avoid having to escape your slashes, or double them up:
```
subprocess.Popen(r'rd /s /q .\ProcessControlSimulator\bin', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
```
or
```
subprocess.Popen('rd /s /q .\\ProcessControlSimulator\\... |
why this dos command does not work inside python? | 2,102,452 | 3 | 2010-01-20T15:24:14Z | 2,102,519 | 8 | 2010-01-20T15:30:50Z | [
"python",
"subprocess"
] | I try to move some dos command from my batch file into python but get this error, The filename, directory name, or volume label syntax is incorrect, for the following statement.
```
subprocess.Popen('rd /s /q .\ProcessControlSimulator\bin', shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOU... | My advice is try not to use system commands unnecessarily. You are using Python, so use the available modules that come with it. From what i see, you are trying to remove directories right? Then you can use modules like shutil. Example:
```
import shutil
import os
path = os.path.join("c:\\","ProcessControlSimulator","... |
determine the type of a value which is represented as string in python | 2,103,071 | 5 | 2010-01-20T16:35:58Z | 2,103,183 | 9 | 2010-01-20T16:48:52Z | [
"python",
"csv",
"types",
"casting"
] | When I read a comma seperated file or string with the csv parser in python all items are represented as a string. see example below.
```
import csv
a = "1,2,3,4,5"
r = csv.reader([a])
for row in r:
d = row
```
d
['1', '2', '3', '4', '5']
type(d[0])
<type 'str'>
I want to determine for each value if it is a strin... | You could do something like this:
```
from datetime import datetime
tests = [
# (Type, Test)
(int, int),
(float, float),
(datetime, lambda value: datetime.strptime(value, "%Y/%m/%d"))
]
def getType(value):
for typ, test in tests:
try:
test(value)
return typ
... |
SqlAlchemy add new Field to class and create corresponding column in table | 2,103,274 | 9 | 2010-01-20T17:01:53Z | 7,610,243 | 7 | 2011-09-30T12:18:35Z | [
"python",
"sqlalchemy"
] | I want to add a field to an existing mapped class, how would I update the sql table automatically. Does sqlalchemy provide a method to update the database with a new column, if a field is added to the class. | Sometimes Migrate is too much work - you just want to column automatically added when you run your changed code. So here is a function that does that.
Caveats: it pokes around in the SQLAlchemy internals and tends to require small changes every time SQLAlchemy undergoes a major revision. (There's probably a much bette... |
Python newbie class design question | 2,103,532 | 6 | 2010-01-20T17:38:38Z | 2,103,567 | 11 | 2010-01-20T17:43:31Z | [
"python",
"oop",
"iterator"
] | I'm trying to figure out the best way to design a couple of classes. I'm pretty new to Python (and OOP in general) and just want to make sure that I'm doing this right. I have two classes: "Users" and "User".
```
class User(object):
def __init__(self):
pass
class Users(object):
def __init__(self):
... | Put this in your `Users`:
```
def __iter__(self):
return iter(self.users)
```
Now you can:
```
for u in users:
print u.email
```
[Docs](http://docs.python.org/library/stdtypes.html#iterator-types) |
Python newbie class design question | 2,103,532 | 6 | 2010-01-20T17:38:38Z | 2,103,580 | 17 | 2010-01-20T17:45:08Z | [
"python",
"oop",
"iterator"
] | I'm trying to figure out the best way to design a couple of classes. I'm pretty new to Python (and OOP in general) and just want to make sure that I'm doing this right. I have two classes: "Users" and "User".
```
class User(object):
def __init__(self):
pass
class Users(object):
def __init__(self):
... | I would say not really. Your `Users` class appears to just be a list of users, so I would just make it a list rather than a whole class. Here's what I would do:
```
class User(object):
def __init__(self, user_id=None, email=None):
self.user_id, self.email = user_id, email
users = []
users.append(User(user... |
Selecting An Embedded Language | 2,103,728 | 7 | 2010-01-20T18:04:49Z | 2,103,850 | 10 | 2010-01-20T18:23:06Z | [
"c++",
"python",
"perl",
"performance",
"lua"
] | I'm making an application that analyses one or more series of data using several different algorithms (agents). I came to the idea that each of these agents could be implemented as separate Python scripts which I run using either the Python C API or Boost.Python in my app.
I'm a little worried about runtime overhead T... | Yes, tons. Lua and Python seems to be the most popular:
**Embedding Lua**
* <http://www.lua.org/pil/24.html>
* [Why is Lua considered a game language?](http://stackoverflow.com/questions/38338/why-is-lua-considered-a-game-language)
* [Lua as a general-purpose scripting language?](http://stackoverflow.com/questions/25... |
Selecting An Embedded Language | 2,103,728 | 7 | 2010-01-20T18:04:49Z | 4,950,642 | 9 | 2011-02-09T21:24:57Z | [
"c++",
"python",
"perl",
"performance",
"lua"
] | I'm making an application that analyses one or more series of data using several different algorithms (agents). I came to the idea that each of these agents could be implemented as separate Python scripts which I run using either the Python C API or Boost.Python in my app.
I'm a little worried about runtime overhead T... | Lua is quite fast as it is. If you need more speed, try [LuaJIT](http://luajit.org/), which is excellent. |
How to check file size in python? | 2,104,080 | 357 | 2010-01-20T18:58:29Z | 2,104,083 | 586 | 2010-01-20T18:59:16Z | [
"python"
] | I am writing a Python script in Windows. I want to do something based on the file size. For example, if the size is greater than 0, I will send an email to somebody, otherwise continue to other things.
How do I check the file size? | Like this (credit <http://www.daniweb.com/forums/thread78629.html>):
```
>>> import os
>>> b = os.path.getsize("/path/isa_005.mp3")
>>> b
2071611L
``` |
How to check file size in python? | 2,104,080 | 357 | 2010-01-20T18:58:29Z | 2,104,107 | 327 | 2010-01-20T19:01:53Z | [
"python"
] | I am writing a Python script in Windows. I want to do something based on the file size. For example, if the size is greater than 0, I will send an email to somebody, otherwise continue to other things.
How do I check the file size? | Use [`os.stat`](https://docs.python.org/2/library/os.html#os.stat), and use the `st_size` member of the resulting object:
```
>>> import os
>>> statinfo = os.stat('somefile.txt')
>>> statinfo
(33188, 422511L, 769L, 1, 1032, 100, 926L, 1105022698,1105022732, 1105022732)
>>> statinfo.st_size
926L
```
Output is in bytes... |
How to check file size in python? | 2,104,080 | 357 | 2010-01-20T18:58:29Z | 19,079,887 | 65 | 2013-09-29T15:41:10Z | [
"python"
] | I am writing a Python script in Windows. I want to do something based on the file size. For example, if the size is greater than 0, I will send an email to somebody, otherwise continue to other things.
How do I check the file size? | The other answers work for real files, but if you need something that works for "file-like objects", try this:
```
# f is a file-like object.
f.seek(0, os.SEEK_END)
size = f.tell()
```
It works for real files and StringIO's, in my limited testing. (Python 2.7.3.) The "file-like object" API isn't really a rigorous in... |
Efficiently search two-tuple | 2,104,095 | 2 | 2010-01-20T19:00:37Z | 2,104,111 | 14 | 2010-01-20T19:02:52Z | [
"python",
"tuples"
] | What's the best one-liner replacement for the code below? I'm sure there's a smarter way.
```
choices = ((1, 'ONE'), (2, 'TWO'), (3, 'THREE'))
some_int = 2
for choice in choices:
if choice[0] == some_int:
label = choice[1]
break;
# label == 'TWO'
``` | ```
labels = dict(choices)
label = labels[some_int]
```
you could, of course, join this into an one-liner, if you don't need `labels` anywhere else. |
Finding elements not in a list | 2,104,305 | 25 | 2010-01-20T19:35:13Z | 2,104,322 | 8 | 2010-01-20T19:37:49Z | [
"python",
"list"
] | So heres my code:
```
item = [0,1,2,3,4,5,6,7,8,9]
for item in z:
if item not in z:
print item
```
Z contains a list of integers. I want to compare item to Z and print out the numbers that are not in Z when compared to item. I can print the elemtens that are in Z when compared not items, but when i try a... | ```
list1 = [1,2,3,4]; list2 = [0,3,3,6]
print set(list2) - set(list1)
``` |
Finding elements not in a list | 2,104,305 | 25 | 2010-01-20T19:35:13Z | 2,104,336 | 30 | 2010-01-20T19:39:40Z | [
"python",
"list"
] | So heres my code:
```
item = [0,1,2,3,4,5,6,7,8,9]
for item in z:
if item not in z:
print item
```
Z contains a list of integers. I want to compare item to Z and print out the numbers that are not in Z when compared to item. I can print the elemtens that are in Z when compared not items, but when i try a... | ```
>> items = [1,2,3,4]
>> Z = [3,4,5,6]
>> print list(set(items)-set(Z))
[1, 2]
``` |
Finding elements not in a list | 2,104,305 | 25 | 2010-01-20T19:35:13Z | 2,104,348 | 63 | 2010-01-20T19:40:49Z | [
"python",
"list"
] | So heres my code:
```
item = [0,1,2,3,4,5,6,7,8,9]
for item in z:
if item not in z:
print item
```
Z contains a list of integers. I want to compare item to Z and print out the numbers that are not in Z when compared to item. I can print the elemtens that are in Z when compared not items, but when i try a... | Your code is not doing what I think you think it is doing. The line `for item in z:` will iterate through `z`, each time making `item` equal to one single element of `z`. The original `item` list is therefore overwritten before you've done anything with it.
I think you want something like this:
```
item = [0,1,2,3,4,... |
Adding arrays with different number of dimensions | 2,104,643 | 7 | 2010-01-20T20:19:54Z | 2,104,699 | 8 | 2010-01-20T20:28:23Z | [
"python",
"numpy"
] | Let's say I have a 2D Numpy array:
```
>>> a = np.random.random((4,6))
```
and I want to add a 1D array to each row:
```
>>> c = np.random.random((6,))
>>> a + c
```
This works. Now if I try adding a 1D array to each column, I get an error:
```
>>> b = np.random.random((4,))
>>> a + b
Traceback (most recent call l... | This is a distinctive feature of numpy called [broadcasting](http://docs.scipy.org/doc/numpy/reference/ufuncs.html#broadcasting).
It is done using four rules which are a bit complicated in formulation but are rather intuitive once understood:
> 1. All input arrays with `ndim` smaller than the input array of largest `n... |
Returning the product of a list | 2,104,782 | 85 | 2010-01-20T20:40:10Z | 2,104,800 | 32 | 2010-01-20T20:42:25Z | [
"python"
] | Is there a more concise, efficient or simply pythonic way to do the following?
```
def product(list):
p = 1
for i in list:
p *= i
return p
```
EDIT:
I actually find that this is marginally faster than using operator.mul:
```
from operator import mul
# from functools import reduce # python3 compa... | ```
reduce(lambda x, y: x * y, list, 1)
``` |
Returning the product of a list | 2,104,782 | 85 | 2010-01-20T20:40:10Z | 2,105,155 | 89 | 2010-01-20T21:33:16Z | [
"python"
] | Is there a more concise, efficient or simply pythonic way to do the following?
```
def product(list):
p = 1
for i in list:
p *= i
return p
```
EDIT:
I actually find that this is marginally faster than using operator.mul:
```
from operator import mul
# from functools import reduce # python3 compa... | Without using lambda:
```
from operator import mul
reduce(mul, list, 1)
```
it is better and faster. With python 2.7.5
```
from operator import mul
import numpy as np
import numexpr as ne
# from functools import reduce # python3 compatibility
a = range(1, 101)
%timeit reduce(lambda x, y: x * y, a) # (1)
%timeit r... |
Returning the product of a list | 2,104,782 | 85 | 2010-01-20T20:40:10Z | 2,105,189 | 14 | 2010-01-20T21:38:20Z | [
"python"
] | Is there a more concise, efficient or simply pythonic way to do the following?
```
def product(list):
p = 1
for i in list:
p *= i
return p
```
EDIT:
I actually find that this is marginally faster than using operator.mul:
```
from operator import mul
# from functools import reduce # python3 compa... | ```
import operator
reduce(operator.mul, list, 1)
``` |
Returning the product of a list | 2,104,782 | 85 | 2010-01-20T20:40:10Z | 13,792,206 | 20 | 2012-12-09T21:47:59Z | [
"python"
] | Is there a more concise, efficient or simply pythonic way to do the following?
```
def product(list):
p = 1
for i in list:
p *= i
return p
```
EDIT:
I actually find that this is marginally faster than using operator.mul:
```
from operator import mul
# from functools import reduce # python3 compa... | if you just have numbers in your list:
```
from numpy import prod
prod(list)
``` |
How does Python manage int and long? | 2,104,884 | 55 | 2010-01-20T20:54:09Z | 2,104,947 | 51 | 2010-01-20T21:01:54Z | [
"python",
"integer"
] | Does anybody know how Python manage internally int and long types?
* Does it choose the right type dynamically?
* What is the limit for an int?
* I am using Python 2.6, Is is different with previous versions?
How should I understand the code below?
```
>>> print type(65535)
<type 'int'>
>>> print type(65536*65536)
<... | `int` and `long` were "unified" [a few versions back](http://www.python.org/dev/peps/pep-0237/). Before that it was possible to overflow an int through math ops.
3.x has further advanced this by eliminating int altogether and only having long.
Python 2: `sys.maxint` contains the maximum value a Python int can hold.
... |
How does Python manage int and long? | 2,104,884 | 55 | 2010-01-20T20:54:09Z | 2,104,953 | 7 | 2010-01-20T21:02:57Z | [
"python",
"integer"
] | Does anybody know how Python manage internally int and long types?
* Does it choose the right type dynamically?
* What is the limit for an int?
* I am using Python 2.6, Is is different with previous versions?
How should I understand the code below?
```
>>> print type(65535)
<type 'int'>
>>> print type(65536*65536)
<... | This [PEP](http://www.python.org/dev/peps/pep-0237/) should help.
Bottom line is that you really shouldn't have to worry about it in python versions > 2.4 |
In Jinja2, how can I use macros in combination with block tags? | 2,104,957 | 10 | 2010-01-20T21:03:49Z | 2,105,535 | 18 | 2010-01-20T22:32:24Z | [
"python",
"django",
"templates",
"django-templates",
"jinja2"
] | I'm a front end developer, and I've been trying to get a hang on using Jinja2 effectively. I want to tweak a current site so it has multiple base templates using inheritance, it fully uses block tags to substitute content and override it, and uses macros to support passing of arguments.
My base template contains this ... | Blocks are only definable at a template's top level. If you extend a template, any values set in the child template using a `set` tag will be accessible from the template it is extending. For example, if you have a template named `layout.html`:
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/T... |
Wrap C++ lib with Cython | 2,105,508 | 13 | 2010-01-20T22:27:05Z | 2,106,051 | 20 | 2010-01-21T00:15:55Z | [
"python",
"cython"
] | I'm new to Cython and I'm tring to use Cython to wrap a C/C++ static library. I made a simply example as following.
Test.h:
```
#ifndef TEST_H
#define TEST_H
int add(int a, int b);
int multipy(int a, int b);
#endif
```
Test.cpp
```
#include "test.h"
int add(int a, int b)
{
return a+b;
}
int multipy(int a, i... | If your C++ code is only used by the wrapper, another option is to let the setup compile your .cpp file, like this:
```
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
ext_modules = [Extension("test",
["test.pyx", "test.cpp"],
... |
Graceful exiting of a program in Python? | 2,105,509 | 6 | 2010-01-20T22:28:04Z | 2,105,600 | 7 | 2010-01-20T22:42:24Z | [
"python"
] | Hey all, I have a script that runs as a
```
while True:
doStuff()
```
What is the best way to communicate with this script if I need to stop it but I don't want to kill it if it is in the middle of an operation?
Thanks! | And I'm assuming you mean killing from outside the python script.
The way I've found easiest is
```
@atexit.register
def cleanup()
sys.unlink("myfile.%d" % os.getpid() )
f = open("myfile.%d" % os.getpid(), "w" )
f.write("Nothing")
f.close()
while os.path.exists("myfile.%d" % os.getpid() ):
doSomething()
```
The... |
name 'times' is used prior to global declaration - But IT IS declared! | 2,105,611 | 13 | 2010-01-20T22:43:56Z | 2,105,637 | 14 | 2010-01-20T22:48:05Z | [
"python",
"python-3.x",
"global-variables"
] | I'm coding a small program to time and show, in a ordered fashion, my Rubik's cube solvings. But Python (3) keeps bothering me about times being used prior to global declaration. But what's strange is that IT IS declared, right on the beggining, as `times = []` (yes, it's a list) and then again, on the function (that's... | The global declaration is when you declare that `times` is `global`
```
def timeit():
global times # <- global declaration
# ...
```
If a variable is declared `global`, it can't be used before the declaration.
In this case, I don't think you need the declaration at all, because you're not assigning to `times... |
name 'times' is used prior to global declaration - But IT IS declared! | 2,105,611 | 13 | 2010-01-20T22:43:56Z | 2,105,647 | 12 | 2010-01-20T22:49:23Z | [
"python",
"python-3.x",
"global-variables"
] | I'm coding a small program to time and show, in a ordered fashion, my Rubik's cube solvings. But Python (3) keeps bothering me about times being used prior to global declaration. But what's strange is that IT IS declared, right on the beggining, as `times = []` (yes, it's a list) and then again, on the function (that's... | From the Python documentation:
```
Names listed in a global statement must not be used in the same code block
textually preceding that global statement.
```
<http://docs.python.org/reference/simple_stmts.html#global>
So, moving `global times` to the top of the function should be fine.
But, you should try not to use... |
Search_fields in django python | 2,106,084 | 6 | 2010-01-21T00:21:12Z | 2,106,162 | 14 | 2010-01-21T00:44:30Z | [
"python",
"django-admin"
] | I was wondering how I am able to use a foreign key to preform a search for example
```
class Product(models.Model):
name = models.CharField(max_length = 127)
description = models.TextField()
code = models.CharField(max_length = 127)
def __unicode__(self):
return self.name + " - " + self.code
... | You can specify related field searches in the admin `search_fields` the same way you do on Django querysets. Check on the [documentation](https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields). For the `LotComments` object, the `search_fields` would look something like:
... |
Escape SQL "LIKE" value for Postgres with psycopg2 | 2,106,207 | 22 | 2010-01-21T00:58:54Z | 2,106,443 | 19 | 2010-01-21T02:04:04Z | [
"python",
"postgresql",
"psycopg2",
"python-db-api"
] | Does psycopg2 have a function for escaping the value of a **LIKE** operand for Postgres?
For example I may want to match strings that start with the string "20% of all", so I want to write something like this:
```
sql = '... WHERE ... LIKE %(myvalue)s'
cursor.fetchall(sql, { 'myvalue': escape_sql_like('20% of all') +... | Yeah, this is a real mess. Both MySQL and PostgreSQL use backslash-escapes for this by default. This is a terrible pain if you're also escaping the string again with backslashes instead of using parameterisation, and it's also incorrect according to ANSI SQL:1992, which says there are by default no extra escape charact... |
Pythonic way to create a numpy array from a list of numpy arrays | 2,106,287 | 17 | 2010-01-21T01:21:05Z | 2,106,651 | 12 | 2010-01-21T03:09:39Z | [
"python",
"performance",
"arrays",
"numpy",
"scipy"
] | I generate a list of one dimensional numpy arrays in a loop and later convert this list to a 2d numpy array. I would've preallocated a 2d numpy array if i knew the number of items ahead of time, but I don't, therefore I put everything in a list.
The mock up is below:
```
>>> list_of_arrays = map(lambda x: x*ones(2), ... | Suppose you know that the final array `arr` will never be larger than 5000x10.
Then you could pre-allocate an array of maximum size, populate it with data as
you go through the loop, and then use `arr.resize` to cut it down to the
discovered size after exiting the loop.
The tests below suggest doing so will be slightl... |
Handling a Python exception that occurs within an except clause | 2,106,475 | 9 | 2010-01-21T02:14:32Z | 2,106,490 | 10 | 2010-01-21T02:18:43Z | [
"python",
"exception"
] | I have some code in a Python `except` clause that is intended to do some logging, but the logging code might itself cause an exception. In my case, I'd like to just ignore any second exception that might occur, and raise the original exception. Here is a very simplified example:
```
try:
a = this_variable_doesnt_e... | With abstraction:
```
def log_it():
try:
1 / 0
except:
pass
try:
this = that
except:
log_it()
raise
```
Does what you want in Python 2.5
Another way to do it is to store the exception in a variable, then re-raise it explicitly:
```
try:
this = that
except NameError, e: # or ... |
Handling a Python exception that occurs within an except clause | 2,106,475 | 9 | 2010-01-21T02:14:32Z | 2,106,518 | 13 | 2010-01-21T02:29:38Z | [
"python",
"exception"
] | I have some code in a Python `except` clause that is intended to do some logging, but the logging code might itself cause an exception. In my case, I'd like to just ignore any second exception that might occur, and raise the original exception. Here is a very simplified example:
```
try:
a = this_variable_doesnt_e... | I believe what you're seeing is the result of [exception chaining](http://www.python.org/dev/peps/pep-3134/), which is a [change in Python 3](http://docs.python.org/3.1/whatsnew/3.0.html#changes-to-exceptions).
From the *Motivation* section of the PEP:
> During the handling of one exception (exception `A`), it is pos... |
Dynamically create image thumbnails (using django) | 2,106,507 | 7 | 2010-01-21T02:26:14Z | 2,106,612 | 8 | 2010-01-21T02:58:22Z | [
"python",
"django",
"thumbnails"
] | I would like to dynamically create thumbnails based on parameters in the URL. For example, `http://mysite.com/images/1234/120x45.jpg` would create a `120x45` thumbnail for image id `1234`.
The obvious solution to this is to have a django view which does the following:
1. Look for a previously cached version of the im... | You don't have to use Django to serve the static content directly. Simply have your server route 404 requests for your images folder to a Django view, where it splits apart the filename and generates the appropriate thumbnail, before redirecting back to the original URL (which hopefully will no longer be a 404).
As fo... |
Re-open files in Python? | 2,106,820 | 24 | 2010-01-21T03:57:53Z | 2,106,825 | 57 | 2010-01-21T03:59:02Z | [
"python",
"file"
] | Say I have this simple python script:
```
file = open('C:\\some_text.txt')
print file.readlines()
print file.readlines()
```
When it is run, the first print prints a list containing the text of the file, while the second print prints a blank list. Not completely unexpected I guess. But is there a way to 'wind back' t... | You can reset the file pointer by calling [`seek()`](http://docs.python.org/library/stdtypes.html#file.seek):
```
file.seek(0)
```
will do it. You need that line after your first `readlines()`. Note that `file` has to support random access for the above to work. |
Restart a Python Program | 2,107,317 | 8 | 2010-01-21T06:28:55Z | 2,107,357 | 8 | 2010-01-21T06:39:46Z | [
"python",
"restart"
] | I'm writing a Python program that, if the user changes settings while running it, needs to be restarted to apply the changed settings. Is there a way of doing this? I'm thinking something along the lines of:
```
import sys
command_line = ' '.join(sys.argv)
# Now do something with command_line
# Now call my custom exit... | I would bypass all the angst you're likely to get from trying to re-run yourself and leave it in the hands of the environment.
By that, I mean:
1. Have a controlling program which does nothing more than run your program (with the same parameters it was given) in a loop while your program exits with a specific "restar... |
How to run two functions simultaneously | 2,108,126 | 14 | 2010-01-21T09:32:58Z | 2,108,146 | 12 | 2010-01-21T09:37:18Z | [
"python",
"testing",
"multithreading",
"function",
"synchronization"
] | I am running test but I want to run 2 functions at the same time. I have a camera and I am telling it to move via suds, I am then logging into the camera via SSH to check the speed the camera is set to. When I check the speed the camera has stopped so no speed is available. Is there a way I can get these functions to r... | Import the `threading` module and run `SudsMove()` like so:
```
threading.Thread(target = SudsMove).start()
```
That will create and start a background thread which does the movement.
**ANSWER TO EDITED QUESTION:**
As far as I understand this, `TestAbsoluteMove.Ssh(self)` polls the speed once and stores the result ... |
Saving huge bigram dictionary to file using pickle | 2,108,293 | 2 | 2010-01-21T10:08:40Z | 2,108,319 | 7 | 2010-01-21T10:11:50Z | [
"python",
"file",
"dictionary",
"pickle"
] | a friend of mine wrote this little progam.
the `textFile` is 1.2GB in size (7 years worth of newspapers).
He successfully manages to create the dictionary but he cannot write it to a file using pickle(program hangs).
```
import sys
import string
import cPickle as pickle
biGramDict = {}
textFile = open(str(sys.argv[1... | Pickle is only meant to write complete (small) objects. Your dictionary is a bit large to even hold in memory, you'd better use a database instead so you can store and retrieve entries one by one instead of all at once.
Some good and easily integratable singe-file database formats you can use from Python are [SQLite](... |
MySQL "incorrect string value" error when save unicode string in Django | 2,108,824 | 104 | 2010-01-21T11:34:22Z | 4,793,471 | 79 | 2011-01-25T12:28:09Z | [
"python",
"mysql",
"django",
"unicode",
"utf-8"
] | I got strange error message when tried to save first\_name, last\_name to Django's auth\_user model.
**Failed examples**
```
user = User.object.create_user(username, email, password)
user.first_name = u'Rytis'
user.last_name = u'SlatkeviÄius'
user.save()
>>> Incorrect string value: '\xC4\x8Dius' for column 'last_nam... | I had the same problem and resolved it by changing the character set of the column. Even though your database has a default character set of `utf-8` I think it's possible for database columns to have a different character set in MySQL. Here's the SQL QUERY I used:
```
ALTER TABLE database.table MODIFY COLUMN col V... |
MySQL "incorrect string value" error when save unicode string in Django | 2,108,824 | 104 | 2010-01-21T11:34:22Z | 11,597,447 | 54 | 2012-07-22T02:46:53Z | [
"python",
"mysql",
"django",
"unicode",
"utf-8"
] | I got strange error message when tried to save first\_name, last\_name to Django's auth\_user model.
**Failed examples**
```
user = User.object.create_user(username, email, password)
user.first_name = u'Rytis'
user.last_name = u'SlatkeviÄius'
user.save()
>>> Incorrect string value: '\xC4\x8Dius' for column 'last_nam... | If you have this problem here's a python script to change all the columns of your mysql database automatically.
```
#! /usr/bin/env python
import MySQLdb
host = "localhost"
passwd = "passwd"
user = "youruser"
dbname = "yourdbname"
db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=dbname)
cursor = db.curso... |
MySQL "incorrect string value" error when save unicode string in Django | 2,108,824 | 104 | 2010-01-21T11:34:22Z | 20,349,552 | 56 | 2013-12-03T11:11:42Z | [
"python",
"mysql",
"django",
"unicode",
"utf-8"
] | I got strange error message when tried to save first\_name, last\_name to Django's auth\_user model.
**Failed examples**
```
user = User.object.create_user(username, email, password)
user.first_name = u'Rytis'
user.last_name = u'SlatkeviÄius'
user.save()
>>> Incorrect string value: '\xC4\x8Dius' for column 'last_nam... | None of these answers solved the problem for me. The root cause being:
**You cannot store 4-byte characters in MySQL with the utf-8 character set.**
MySQL has a [3 byte limit on utf-8 characters](http://dev.mysql.com/doc/refman/5.6/en/charset-unicode-utf8.html) (yes, it's wack, [nicely summed up by a Django developer... |
MySQL "incorrect string value" error when save unicode string in Django | 2,108,824 | 104 | 2010-01-21T11:34:22Z | 23,792,645 | 8 | 2014-05-21T19:57:05Z | [
"python",
"mysql",
"django",
"unicode",
"utf-8"
] | I got strange error message when tried to save first\_name, last\_name to Django's auth\_user model.
**Failed examples**
```
user = User.object.create_user(username, email, password)
user.first_name = u'Rytis'
user.last_name = u'SlatkeviÄius'
user.save()
>>> Incorrect string value: '\xC4\x8Dius' for column 'last_nam... | If it's a new project, I'd just drop the database, and create a new one with a proper charset:
```
CREATE DATABASE <dbname> CHARACTER SET utf8;
``` |
IPython doesn't work in Django shell | 2,109,075 | 17 | 2010-01-21T12:17:39Z | 7,712,122 | 28 | 2011-10-10T11:30:01Z | [
"python",
"django",
"osx-snow-leopard"
] | I've just recently switched over to using 64-bit Python 2.6.1 on Mac OS X 10.6 (Snow Leopard). IPython won't work with Django anymore, but IPython works from the command-line.
The error says:
```
shell = IPython.Shell.IPShell(argv=[])
AttributeError: 'module' object has no attribute 'Shell'
```
I could use the `... | IPython 0.11 has a different API, for which a fix exists in the last Django versions.
For older Django versions, you can use IPython 0.10, which does work:
```
pip install ipython==0.10
``` |
A good django search app? â How to perform fuzzy search with Haystack? | 2,110,411 | 4 | 2010-01-21T15:31:17Z | 2,110,763 | 9 | 2010-01-21T16:13:46Z | [
"python",
"django",
"solr",
"django-haystack",
"fuzzy-search"
] | I'm using django-haystack at the moment
with apache-solr as the backend.
Problem is I cannot get the app to perform the search functionality I'm looking for
1. Searching for sub-parts in a word
> eg. Searching for "buntu" does not give me "ubuntu"
2. Searching for similar words
> eg. Searching for "ubantu" wo... | This is really about how you pass the query back to Haystack (and therefore to Solr). You can do a 'fuzzy' search in Solr/Lucene by using a `~` after the word:
```
ubuntu~
```
would return both `buntu` and `ubantu`. See the [Lucene documentation](http://lucene.apache.org/java/2_4_0/queryparsersyntax.html#Fuzzy#20Sear... |
why is __init__ module in django project loaded twice | 2,110,545 | 8 | 2010-01-21T15:45:32Z | 2,110,584 | 19 | 2010-01-21T15:51:26Z | [
"python",
"django"
] | I put
```
print 'Hello world!'
```
into `__init__.py` in my django project. When I run `./manage.py runserver` now, I get
```
gruszczy@gruszczy-laptop:~/Programy/project$ ./manage.py runserver
Hello world!
Hello world!
Validating models...
0 errors found
```
Why is `__init__.py` run twice? It should be loaded only ... | It should be loaded only once... *per process*. I'm guessing that `manage.py` forks, and that two separate processes are launched. Could you print the result of `os.getpid()`? |
Python zipfile hangs when writing | 2,110,739 | 3 | 2010-01-21T16:11:17Z | 2,110,777 | 9 | 2010-01-21T16:15:02Z | [
"python",
"zipfile"
] | I am trying to use the [zipfile](http://docs.python.org/library/zipfile.html) module in Python to create simple zip files:
```
import zipfile
files = ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h')
zip_file_name = 'zipfile_test.zip'
zfh = zipfile.ZipFile(zip_file_name, 'w')
for file in files:
print 'Archiving file %s' % ... | You're putting *the zip file* into the zip file:
```
zfh.write(zip_file_name)
```
Should be:
```
zfh.write(file)
``` |
How to build 64-bit Python on OS X 10.6 -- ONLY 64 bit, no Universal nonsense | 2,111,283 | 6 | 2010-01-21T17:19:36Z | 2,111,435 | 11 | 2010-01-21T17:36:52Z | [
"python",
"osx",
"64bit",
"osx-snow-leopard",
"x86-64"
] | I just want to build this on my development machine -- the binary install from Python.org is still 32 bits and installing extensions (MySQLdb, for example) is driving me nuts with trying to figure out the proper flags for each and every extension.
Clarification: I did NOT replace the system Python, I just installed th... | If you happen to be using [MacPorts](http://www.macports.org/), it's as simple as specifying the variant that tells it not to compile Universal, like so:
```
sudo port install python26 -universal
```
You can view available variants using the `variants` command:
```
% port variants python26 ... |
What's the best practice for handling single-value tuples in Python? | 2,111,759 | 6 | 2010-01-21T18:22:22Z | 2,111,864 | 11 | 2010-01-21T18:37:04Z | [
"python",
"tuples"
] | I am using a 3rd party library function which reads a set of keywords from a file, and is supposed to return a tuple of values. It does this correctly as long as there are at least two keywords. However, in the case where there is only one keyword, it returns a raw string, not a tuple of size one. This is particularly ... | You need to somehow test for the type, if it's a string or a tuple. I'd do it like this:
```
keywords = library.get_keywords()
if not isinstance(keywords, tuple):
keywords = (keywords,) # Note the comma
for keyword in keywords:
do_your_thang(keyword)
``` |
How to encrypt a string in Python and decrypt that same string in PHP? | 2,112,274 | 4 | 2010-01-21T19:38:58Z | 2,112,319 | 7 | 2010-01-21T19:46:39Z | [
"php",
"python"
] | I have a string that I would like to encrypt in Python, store it as a cookie, then in a PHP file I'd like to retrieve that cookie, and decrypt it in PHP. How would I go about doing this?
---
I appreciate the fast responses.
All cookie talk aside, lets just say I want to encrypt a string in Python and then decrypt a ... | Use a standard encryption scheme. The implementation is going to be equivalent in either language.
[RSA](http://en.wikipedia.org/wiki/RSA) is available (via third party libraries) in both languages, if you need asymmetric key crypto. So is [AES](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard), if you need s... |
Python 2.x vs 3.x Speed | 2,112,298 | 35 | 2010-01-21T19:43:17Z | 2,112,375 | 22 | 2010-01-21T19:54:43Z | [
"python",
"performance"
] | I'm a PhD student and use Python to write the code I use for my research. My workflow often consists of making a small change to the code, running the program, seeing whether the results improved, and repeating the process. Because of this, I find myself spending more time waiting for my program to run than I do actual... | [This article (archive.org)](https://web.archive.org/web/20131028122438/http://mikewatkins.ca/2008/12/06/python-3-performance-a-red-herring/) said that there were a few points where Python 3.0 was actually slower than Python 2.6, though I think many of these issues were resolved. That being said, Numpy hasn't been brou... |
generating promotion code using python | 2,112,436 | 3 | 2010-01-21T20:04:12Z | 2,112,661 | 7 | 2010-01-21T20:34:55Z | [
"python",
"security",
"promotions"
] | Hello
By using python language, what would be a clever / efficient way of generating promotion codes.
Like to be used for generating special numbers for discount coupons.
like: 1027828-1
Thanks | The following isn't particularly pythonic or particularly efficient, but it might suffice:
```
import random
def get_promo_code(num_chars):
code_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
code = ''
for i in range(0, num_chars):
slice_start = random.randint(0, len(code_chars) - 1)
... |
Running Python & Django on IIS | 2,112,525 | 6 | 2010-01-21T20:15:40Z | 2,112,557 | 7 | 2010-01-21T20:21:22Z | [
"asp.net",
"python",
"asp.net-mvc",
"apache",
"iis"
] | Is it possible to run Python & Django on IIS?
I am going to be a Lead Developer in some web design company and right now they are using classic ASP and ASP.NET.
As far as I can see ASP.NET MVC is not mature. Should I recommend Python & Django stack?
If it's not possible to run Python on IIS what do you think I sh... | There's two issue here, technological and psycological.
Technologically, yes, it's definitely possible. In fact, Django has a [wiki article](http://code.djangoproject.com/wiki/DjangoOnWindowsWithIISAndSQLServer) about this. Google also shows a lot of similar tutorials. Apache and IIS can also run on the same machine (... |
How do I fix PyDev "Undefined variable from import" errors? | 2,112,715 | 117 | 2010-01-21T20:40:49Z | 2,248,987 | 140 | 2010-02-12T01:07:36Z | [
"python",
"code-analysis",
"pydev"
] | I've got a Python project using PyDev in Eclipse, and PyDev keeps generating false errors for my code. I have a module `settings` that defines a `settings` object. I import that in module `b` and assign an attribute with:
```
from settings import settings
settings.main = object()
```
In some of my code--but not all o... | For code in your project, the only way is adding a comment saying that you expected that (the static code-analysis only sees what you see, not runtime info -- if you opened that module yourself, you'd have no indication that main was expected).
You can use ctrl+1 (Cmd+1 for Mac) in a line with an error and pydev will ... |
How do I fix PyDev "Undefined variable from import" errors? | 2,112,715 | 117 | 2010-01-21T20:40:49Z | 7,954,059 | 41 | 2011-10-31T13:01:27Z | [
"python",
"code-analysis",
"pydev"
] | I've got a Python project using PyDev in Eclipse, and PyDev keeps generating false errors for my code. I have a module `settings` that defines a `settings` object. I import that in module `b` and assign an attribute with:
```
from settings import settings
settings.main = object()
```
In some of my code--but not all o... | I'm using opencv which relies on binaries etc so I have scripts where every other line has this silly error. Python is a dynamic language so such occasions shouldn't be considered errors.
I removed these errors altogether by going to:
Window -> Preferences -> PyDev -> Editor -> Code Analysis -> Undefined -> Undefined... |
How do I fix PyDev "Method should have self as first parameter" errors | 2,112,770 | 7 | 2010-01-21T20:47:43Z | 2,112,820 | 18 | 2010-01-21T20:53:15Z | [
"python",
"code-analysis",
"pydev"
] | I'm developing in Python using PyDev in Eclipse, and some of my code generates errors in the code analysis tool. Specifically:
```
class Group(object):
def key(self, k):
class Subkey(object):
def __enter__(s):
self._settings.beginGroup(k)
return self
... | You could disable that error in the preferences...
```
Window > Preferences > Pydev > Editor > Code Analysis > Others
```
Or refactor the code...
```
class Group(object):
def key(self, k):
outer_self = self
class Subkey(object):
def __enter__(self):
outer_self._setting... |
How do I fix PyDev "Method should have self as first parameter" errors | 2,112,770 | 7 | 2010-01-21T20:47:43Z | 2,248,963 | 14 | 2010-02-12T01:00:57Z | [
"python",
"code-analysis",
"pydev"
] | I'm developing in Python using PyDev in Eclipse, and some of my code generates errors in the code analysis tool. Specifically:
```
class Group(object):
def key(self, k):
class Subkey(object):
def __enter__(s):
self._settings.beginGroup(k)
return self
... | Using `Ctrl+1` in a line with an error from PyDev will always bring you a fix which will allow you to ignore the PyDev error in the line. In this specific case, it'll allow you to ignore the error by adding `#@NoSelf` to the end of the line. `Ctrl+1` is also useful when some unused import is needed and under other situ... |
Determining Whether a Directory is Writeable | 2,113,427 | 55 | 2010-01-21T22:24:39Z | 2,113,457 | 44 | 2010-01-21T22:30:40Z | [
"python",
"file",
"permissions",
"directory",
"operating-system"
] | What would be the best way in Python to determine whether a directory is writeable for the user executing the script? Since this will likely involve using the os module I should mention I'm running it under a \*nix environment. | It may seem strange to suggest this, but a common Python idiom is
> It's easier to ask for forgiveness
> than for permission
Following that idiom, one might say:
Try writing to the directory in question, and catch the error if you don't have the permission to do so. |
Determining Whether a Directory is Writeable | 2,113,427 | 55 | 2010-01-21T22:24:39Z | 2,113,511 | 95 | 2010-01-21T22:39:22Z | [
"python",
"file",
"permissions",
"directory",
"operating-system"
] | What would be the best way in Python to determine whether a directory is writeable for the user executing the script? Since this will likely involve using the os module I should mention I'm running it under a \*nix environment. | Although what Christophe suggested is a more Pythonic solution, the os module does have a function to check access:
`os.access('/path/to/folder', os.W_OK)` # W\_OK is for writing, R\_OK for reading, etc. |
Determining Whether a Directory is Writeable | 2,113,427 | 55 | 2010-01-21T22:24:39Z | 2,113,750 | 9 | 2010-01-21T23:17:40Z | [
"python",
"file",
"permissions",
"directory",
"operating-system"
] | What would be the best way in Python to determine whether a directory is writeable for the user executing the script? Since this will likely involve using the os module I should mention I'm running it under a \*nix environment. | If you only care about the file perms, `os.access(path, os.W_OK)` should do what you ask for. If you instead want to know whether you **can** write to the directory, `open()` a test file for writing (it shouldn't exist beforehand), catch and examine any `IOError`, and clean up the test file afterwards.
More generally,... |
Determining Whether a Directory is Writeable | 2,113,427 | 55 | 2010-01-21T22:24:39Z | 25,868,839 | 11 | 2014-09-16T12:30:39Z | [
"python",
"file",
"permissions",
"directory",
"operating-system"
] | What would be the best way in Python to determine whether a directory is writeable for the user executing the script? Since this will likely involve using the os module I should mention I'm running it under a \*nix environment. | My solution using the `tempfile` module:
```
import tempfile
import errno
def isWritable(path):
try:
testfile = tempfile.TemporaryFile(dir = path)
testfile.close()
except OSError as e:
if e.errno == errno.EACCES: # 13
return False
e.filename = path
raise
... |
Group by hour in SQLAlchemy? | 2,113,448 | 5 | 2010-01-21T22:29:06Z | 2,113,473 | 9 | 2010-01-21T22:33:37Z | [
"python",
"sqlite",
"sqlalchemy"
] | How do I group query results by the hour part of a datetime column in SQLAlchemy? | This works for PostgreSQL:
```
.group_by(func.date_trunc('hour', date_col))
``` |
Python: getting filename case as stored in Windows? | 2,113,822 | 12 | 2010-01-21T23:30:54Z | 2,114,975 | 7 | 2010-01-22T04:33:51Z | [
"python",
"windows",
"case",
"filenames"
] | Though Windows is case insensitive, it does preserve case in filenames. In Python, is there any way to get a filename with case as it is stored on the file system?
E.g., in a Python program I have filename = "texas.txt", but want to know that it's actually stored "TEXAS.txt" on the file system, even if this is inconse... | Here's the simplest way to do it:
```
>>> import win32api
>>> win32api.GetLongPathName(win32api.GetShortPathName('texas.txt')))
'TEXAS.txt'
``` |
Cannot solve mod_wsgi exception in Django setup | 2,113,905 | 10 | 2010-01-21T23:47:32Z | 2,116,481 | 13 | 2010-01-22T10:12:25Z | [
"python",
"django",
"apache",
"wsgi"
] | I'm working with my hosting provider to get a Django application up and running, but neither of us are very experienced and we've basically hit a complete dead end.
I don't have direct access to the conf file but here's how its contents have been described to me:
```
<IfModule mod_wsgi.c>
WSGIScriptAlias /fredapp/ /h... | If the quoted configuration about is what you are using, the error is rather obvious actually. You have:
```
WSGIDaemonProcess fred threads=15 display-name=%{GROUP} python-path=/home/fred/public_html/cgi-bin/fredapp/apache/
WSGIProcessGroup scratchf
```
It should be:
```
WSGIDaemonProcess fred threads=15 display-nam... |
which style is preferred? | 2,114,540 | 9 | 2010-01-22T02:21:36Z | 2,114,556 | 9 | 2010-01-22T02:26:48Z | [
"python",
"exception",
"coding-style"
] | Option 1:
```
def f1(c):
d = {
"USA": "N.Y.",
"China": "Shanghai"
}
if c in d:
return d[c]
return "N/A"
```
Option 2:
```
def f2(c):
d = {
"USA": "N.Y.",
"China": "Shanghai"
}
try:
return d[c]
except:
return "N/A"
```
So that I can then call:
```
for c in ("China", "J... | Typically, exceptions carry some overhead, and are meant for truly 'exceptional' cases. In this case, this sounds like a normal part of the execution, not an 'exceptional' or 'error' state.
In general, I think your code will benefit by using the "if/else" convention, and saving exceptions for only when they are truly ... |
which style is preferred? | 2,114,540 | 9 | 2010-01-22T02:21:36Z | 2,114,557 | 21 | 2010-01-22T02:27:11Z | [
"python",
"exception",
"coding-style"
] | Option 1:
```
def f1(c):
d = {
"USA": "N.Y.",
"China": "Shanghai"
}
if c in d:
return d[c]
return "N/A"
```
Option 2:
```
def f2(c):
d = {
"USA": "N.Y.",
"China": "Shanghai"
}
try:
return d[c]
except:
return "N/A"
```
So that I can then call:
```
for c in ("China", "J... | Neither, I would go for
```
def f2(c):
d = {
"USA": "N.Y.",
"China": "Shanghai"
}
return d.get(c, "N/A")
```
This way is shorter and "get" is designed for the job.
Also an except without an explicit exception is bad pratice, so use `except KeyError:` not just except.
Exceptions do not have much overh... |
which style is preferred? | 2,114,540 | 9 | 2010-01-22T02:21:36Z | 2,114,563 | 7 | 2010-01-22T02:27:56Z | [
"python",
"exception",
"coding-style"
] | Option 1:
```
def f1(c):
d = {
"USA": "N.Y.",
"China": "Shanghai"
}
if c in d:
return d[c]
return "N/A"
```
Option 2:
```
def f2(c):
d = {
"USA": "N.Y.",
"China": "Shanghai"
}
try:
return d[c]
except:
return "N/A"
```
So that I can then call:
```
for c in ("China", "J... | Neither.
```
return d.get(c, 'N/A')
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.