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 |
|---|---|---|---|---|---|---|---|---|---|
Should I take a Python CS class using Windows or Mac? | 1,878,904 | 2 | 2009-12-10T05:59:57Z | 1,878,914 | 9 | 2009-12-10T06:03:17Z | [
"python",
"windows",
"osx",
"compatibility"
] | I'll be taking a Python-based computer science class next semester using my MacBook Pro. It will be centered around a custom-designed [package](http://myro.roboteducation.org/) for this class. The problem is that this package is being sponsored by Microsoft Research, so it was obviously designed with Windows in mind. S... | If the class expects the code to run on Windows then I would install a VM with Windows on it since it is possible that some things may not work quite the same way (especially if you are doing system-specific things like file-system access or executing OS commands).
Classwork/homework always goes smoother when you have... |
DJANGO : Update div with AJAX | 1,879,872 | 5 | 2009-12-10T09:42:32Z | 1,881,894 | 13 | 2009-12-10T15:48:54Z | [
"jquery",
"python",
"ajax",
"django",
"django-templates"
] | I am building a chat application. So far I am adding chat messages with jquery $.post() and this works fine.
Now I need to retrieve the latest chat message from the table and append the list on the chat page.
I am new to Django, so please go slow.
So how do I get data from the chat table back to the chat page?
Thank... | My favorite technique for this kind of thing is to use an [inclusion tag](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#inclusion-tags)
basically you make a separate template for rendering the individual objects in the page template
page template:
```
{% load message_tags %}
<h3>Messages</h3>... |
Using a file to store optparse arguments | 1,880,404 | 14 | 2009-12-10T11:35:10Z | 1,880,642 | 21 | 2009-12-10T12:23:42Z | [
"python",
"optparse"
] | I've been using optparse for a while now, and would like to add the ability to load the arguments from a config file.
So far the best I can think of is a wrapper batch script with the arguments hardcoded... seems clunky.
What is the most elegant way to do this? | I agree with S.Lott's idea of using a config file, but I'd recommend using the built-in [ConfigParser](http://docs.python.org/library/configparser.html) (configparser in 3.0) module to parse it, rather than a home-brewed solution.
Here's a brief script that illustrates ConfigParser and [optparse](http://docs.python.or... |
Using a file to store optparse arguments | 1,880,404 | 14 | 2009-12-10T11:35:10Z | 1,883,991 | 7 | 2009-12-10T21:00:38Z | [
"python",
"optparse"
] | I've been using optparse for a while now, and would like to add the ability to load the arguments from a config file.
So far the best I can think of is a wrapper batch script with the arguments hardcoded... seems clunky.
What is the most elegant way to do this? | You can use [`argparse`](http://argparse.googlecode.com/svn/trunk/doc/ArgumentParser.html#fromfile-prefix-chars) module for that:
```
>>> open('args.txt', 'w').write('-f\nbar')
>>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
>>> parser.add_argument('-f')
>>> parser.parse_args(['-f', 'foo', '@args.txt']... |
pythonic way to explode a list of tuples | 1,880,683 | 5 | 2009-12-10T12:31:24Z | 1,880,706 | 17 | 2009-12-10T12:35:39Z | [
"python",
"list"
] | I need to do the opposite of this
<http://stackoverflow.com/questions/756550/multiple-tuple-to-two-pair-tuple-in-python>
Namely, I have a list of tuples
```
[(1,2), (3,4), (5,6)]
```
and need to produce this
```
[1,2,3,4,5,6]
```
I would personally do this
```
>>> tot = []
>>> for i in [(1,2), (3,4), (5,6)]:
...... | The most efficient way to do it is this:
```
tuples = [(1,2), (3,4), (5,6)]
[item for t in tuples for item in t]
```
output
```
[1, 2, 3, 4, 5, 6]
```
Here is [the comparison](http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python/952993#952993) I did for various way to do it in... |
Does 'p' have a special meaning in Django? | 1,880,753 | 2 | 2009-12-10T12:44:16Z | 1,880,815 | 13 | 2009-12-10T12:57:04Z | [
"python",
"django"
] | Why are p and p8 different in the following code?
The beginning of a view function (in file views.py in a Django app named "proteinSearch" with a model named "Protein" that has a field named "description"):
```
def searchForProteins2(request, searchStr):
p8 = Protein.objects.filter( description__icontains=searchS... | When you are in Debugging mode (pdb or ipdb), at that momemt 'p' is meant for a specific functionality, i.e. evaluating an expression expr.
Like,
```
ipdb> x = 1
ipdb> p x
1
ipdb> p x==True
True
ipdb> p x==1
True
```
In Django, 'p' will simply means a variable.
If you want to print value of 'p' variable, try,
```
... |
How to get the absolute path of a file using tkFileDialog? | 1,881,202 | 5 | 2009-12-10T14:06:48Z | 1,881,313 | 12 | 2009-12-10T14:25:18Z | [
"python",
"file",
"tkinter",
"dialog"
] | I am using:
```
file = tkFileDialog.askopenfile(parent=root, mode='rb',
filetypes=[('Subrip Subtitle File','*.srt')], title='Choose a subtitle file')
```
to get a file object specified by the user.
Is there any way I can get the absolute path of this file from the file object? | ```
file = tkFileDialog.askopenfile(parent=root,mode='rb',filetypes=[('Subrip Subtitle File','*.srt')],title='Choose a subtitle file')
abs_path = os.path.abspath(file.name)
``` |
What is the best way to get a stacktrace when using multiprocessing? | 1,881,338 | 15 | 2009-12-10T14:28:34Z | 1,881,690 | 10 | 2009-12-10T15:21:13Z | [
"python",
"multiprocessing"
] | I'm wondering about the best way to get a stacktrace when there is an exception inside a function executed via the multiprocessing module. Here's an example:
```
import multiprocessing
def square(x):
raise Exception("Crash.")
return x**2
if __name__ == '__main__':
pool = multiprocessing.Pool(processes=4)... | It looks like you should avoid raising the exception from your main function. Instead, you can catch it, treat it as a value returned to the main program, then raise it there. [Re-throwing exceptions in Python](http://nedbatchelder.com/blog/200711/rethrowing%5Fexceptions%5Fin%5Fpython.html) has more details. |
Python: Httplib2 Module Not Found | 1,882,465 | 13 | 2009-12-10T17:09:25Z | 1,882,503 | 8 | 2009-12-10T17:13:35Z | [
"python",
"httplib2"
] | I tried to import the module but i am getting the error shown below:-
```
sh-3.2# python -V
Python 2.6.4
sh-3.2# python -c "import httplib2"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named httplib2
```
How to fix this Error? | I suppose you could start by installing [httplib2](http://code.google.com/p/httplib2/). |
Python: Httplib2 Module Not Found | 1,882,465 | 13 | 2009-12-10T17:09:25Z | 1,882,512 | 12 | 2009-12-10T17:14:26Z | [
"python",
"httplib2"
] | I tried to import the module but i am getting the error shown below:-
```
sh-3.2# python -V
Python 2.6.4
sh-3.2# python -c "import httplib2"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named httplib2
```
How to fix this Error? | You need to install the httplib2 package from your package manager.
On Ubuntu:
`sudo apt-get install python-httplib2` |
Python: Httplib2 Module Not Found | 1,882,465 | 13 | 2009-12-10T17:09:25Z | 6,468,823 | 25 | 2011-06-24T13:55:52Z | [
"python",
"httplib2"
] | I tried to import the module but i am getting the error shown below:-
```
sh-3.2# python -V
Python 2.6.4
sh-3.2# python -c "import httplib2"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named httplib2
```
How to fix this Error? | `httplib2` is not part of the Python standard library. It's an external package you must install yourself.
using [pip](http://www.pip-installer.org/):
```
pip install httplib2
``` |
Where should django manager code live? | 1,883,322 | 19 | 2009-12-10T19:21:00Z | 1,883,460 | 20 | 2009-12-10T19:43:06Z | [
"python",
"django",
"design-patterns",
"django-models",
"django-managers"
] | This is a pretty simple django patterns question. My manager code usually lives in models.py, but what happens when models.py is really huge? Is there any other alternative pattern to letting your manager code live in models.py for maintainability and to avoid circular imports?
A question may be asked as to why models... | I prefer to keep my models in models.py and managers in managers.py (forms in forms.py) all within the same app. For more generic managers, I prefer to keep them in core.managers if they can be re-used for other apps. In some of our larger apps with models/modelname.py that will contains a manager and the model code wh... |
Where should django manager code live? | 1,883,322 | 19 | 2009-12-10T19:21:00Z | 1,883,633 | 7 | 2009-12-10T20:07:18Z | [
"python",
"django",
"design-patterns",
"django-models",
"django-managers"
] | This is a pretty simple django patterns question. My manager code usually lives in models.py, but what happens when models.py is really huge? Is there any other alternative pattern to letting your manager code live in models.py for maintainability and to avoid circular imports?
A question may be asked as to why models... | Your best bet with a large set of models is to use django modules to your advantage, and simply create a folder named models. Move your old models.py into this models folder, and rename it `__init__.py`. This will allow you to then separate each model into more specific files inside of this model folder.
You would the... |
Using Python, how do I to read/write data in memory like I would with a file? | 1,883,326 | 9 | 2009-12-10T19:21:38Z | 1,883,352 | 16 | 2009-12-10T19:25:19Z | [
"python",
"file",
"stream"
] | I'm used to C++, and I build my data handling classes/functions to handle stream objects instead of files. I'd like to know how I might modify the following code, so that it can handle a stream of binary data in memory, rather than a file handle.
```
def get_count(self):
curr = self.file.tell()
self.file.seek(... | You can use an instance of [StringIO.StringIO](http://docs.python.org/library/stringio.html?highlight=stringio#StringIO.StringIO) (or [cStringIO.StringIO](http://docs.python.org/library/stringio.html?highlight=stringio#module-cStringIO), faster) to give a file-like interface to in-memory data. |
Reading utf-8 characters from a gzip file in python | 1,883,604 | 15 | 2009-12-10T20:02:26Z | 1,883,673 | 10 | 2009-12-10T20:11:27Z | [
"python",
"file-io",
"utf-8",
"gzip"
] | I am trying to read a gunzipped file (.gz) in python and am having some trouble.
I used the gzip module to read it but the file is encoded as a utf-8 text file so eventually it reads an invalid character and crashes.
Does anyone know how to read gzip files encoded as utf-8 files? I know that there's a codecs module t... | I don't see why this should be so hard.
What are you doing exactly? Please explain "eventually it reads an invalid character".
It should be as simple as:
```
import gzip
fp = gzip.open('foo.gz')
contents = fp.read() # contents now has the uncompressed bytes of foo.gz
fp.close()
u_str = contents.decode('utf-8') # u_s... |
Reading utf-8 characters from a gzip file in python | 1,883,604 | 15 | 2009-12-10T20:02:26Z | 1,883,734 | 14 | 2009-12-10T20:21:02Z | [
"python",
"file-io",
"utf-8",
"gzip"
] | I am trying to read a gunzipped file (.gz) in python and am having some trouble.
I used the gzip module to read it but the file is encoded as a utf-8 text file so eventually it reads an invalid character and crashes.
Does anyone know how to read gzip files encoded as utf-8 files? I know that there's a codecs module t... | Maybe
```
import codecs
zf = gzip.open(fname, 'rb')
reader = codecs.getreader("utf-8")
contents = reader( zf )
for line in contents:
pass
``` |
Reading utf-8 characters from a gzip file in python | 1,883,604 | 15 | 2009-12-10T20:02:26Z | 19,794,943 | 12 | 2013-11-05T17:20:37Z | [
"python",
"file-io",
"utf-8",
"gzip"
] | I am trying to read a gunzipped file (.gz) in python and am having some trouble.
I used the gzip module to read it but the file is encoded as a utf-8 text file so eventually it reads an invalid character and crashes.
Does anyone know how to read gzip files encoded as utf-8 files? I know that there's a codecs module t... | This is possible in Python 3.3:
```
import gzip
gzip.open('file.gz', 'rt', encoding='utf-8')
```
Notice that gzip.open() requires you to explicitly specify text mode ('t'). |
Find the nth occurrence of substring in a string | 1,883,980 | 55 | 2009-12-10T20:58:50Z | 1,884,151 | 35 | 2009-12-10T21:26:39Z | [
"python",
"string",
"substring"
] | This seems like it should be pretty trivial, but I am new at Python and want to do it the most Pythonic way.
I want to find the n'th occurrence of a substring in a string.
There's got to be something equivalent to what I WANT to do which is
`mystring.find("substring", 2nd)`
How can you achieve this in Python? | Mark's iterative approach would be the usual way, I think.
Here's an alternative with string-splitting, which can often be useful for finding-related processes:
```
def findnth(haystack, needle, n):
parts= haystack.split(needle, n+1)
if len(parts)<=n+1:
return -1
return len(haystack)-len(parts[-1]... |
Find the nth occurrence of substring in a string | 1,883,980 | 55 | 2009-12-10T20:58:50Z | 1,884,216 | 16 | 2009-12-10T21:36:42Z | [
"python",
"string",
"substring"
] | This seems like it should be pretty trivial, but I am new at Python and want to do it the most Pythonic way.
I want to find the n'th occurrence of a substring in a string.
There's got to be something equivalent to what I WANT to do which is
`mystring.find("substring", 2nd)`
How can you achieve this in Python? | Understanding that regex is not always the best solution, I'd probably use one here:
```
>>> import re
>>> s = "ababdfegtduab"
>>> [m.start() for m in re.finditer(r"ab",s)]
[0, 2, 11]
>>> [m.start() for m in re.finditer(r"ab",s)][2] #index 2 is third occurrence
11
``` |
Find the nth occurrence of substring in a string | 1,883,980 | 55 | 2009-12-10T20:58:50Z | 1,884,277 | 37 | 2009-12-10T21:45:22Z | [
"python",
"string",
"substring"
] | This seems like it should be pretty trivial, but I am new at Python and want to do it the most Pythonic way.
I want to find the n'th occurrence of a substring in a string.
There's got to be something equivalent to what I WANT to do which is
`mystring.find("substring", 2nd)`
How can you achieve this in Python? | Here's a more Pythonic version of the straightforward iterative solution:
```
def find_nth(haystack, needle, n):
start = haystack.find(needle)
while start >= 0 and n > 1:
start = haystack.find(needle, start+len(needle))
n -= 1
return start
```
*Example:*
```
>>> find_nth("foofoofoofoo", "... |
Find the nth occurrence of substring in a string | 1,883,980 | 55 | 2009-12-10T20:58:50Z | 13,094,326 | 11 | 2012-10-26T20:59:02Z | [
"python",
"string",
"substring"
] | This seems like it should be pretty trivial, but I am new at Python and want to do it the most Pythonic way.
I want to find the n'th occurrence of a substring in a string.
There's got to be something equivalent to what I WANT to do which is
`mystring.find("substring", 2nd)`
How can you achieve this in Python? | This will find the second occurrence of substring in string.
```
def find_2nd(string, substring):
return string.find(substring, string.find(substring) + 1)
``` |
Find the nth occurrence of substring in a string | 1,883,980 | 55 | 2009-12-10T20:58:50Z | 23,479,065 | 7 | 2014-05-05T18:16:34Z | [
"python",
"string",
"substring"
] | This seems like it should be pretty trivial, but I am new at Python and want to do it the most Pythonic way.
I want to find the n'th occurrence of a substring in a string.
There's got to be something equivalent to what I WANT to do which is
`mystring.find("substring", 2nd)`
How can you achieve this in Python? | I'm offering some benchmarking results comparing the most prominent approaches presented so far, namely @bobince's `findnth()` (based on `str.split()`) vs. @tgamblin's or @Mark Byers' `find_nth()` (based on `str.find()`). I will also compare with a C extension (`_find_nth.so`) to see how fast we can go. Here is `find_n... |
Converting a list of lists to a tuple in Python | 1,884,323 | 5 | 2009-12-10T21:53:38Z | 1,884,377 | 11 | 2009-12-10T22:00:10Z | [
"python",
"list-comprehension",
"itertools",
"tuple-packing"
] | I have a list of lists (generated with a simple list comprehension):
```
>>> base_lists = [[a, b] for a in range(1, 3) for b in range(1, 6)]
>>> base_lists
[[1,1],[1,2],[1,3],[1,4],[1,5],[2,1],[2,2],[2,3],[2,4],[2,5]]
```
I want to turn this entire list into a tuple containing all of the values in the lists, i.e.:
... | ```
tuple(x for sublist in base_lists for x in sublist)
```
**Edit**: note that, with `base_lists` so short, the genexp (with unlimited memory available) is slow. Consider the following file `tu.py`:
```
base_lists = [[a, b] for a in range(1, 3) for b in range(1, 6)]
def genexp():
return tuple(x for sublist in bas... |
Named parameters with Python C API? | 1,884,327 | 4 | 2009-12-10T21:54:21Z | 1,884,369 | 12 | 2009-12-10T21:59:11Z | [
"python",
"c",
"python-c-api",
"named-parameters"
] | How can I simulate the following Python function using the Python C API?
```
def foo(bar, baz="something or other"):
print bar, baz
```
(i.e., so that it is possible to call it via:
```
>>> foo("hello")
hello something or other
>>> foo("hello", baz="world!")
hello world!
>>> foo("hello", "world!")
hello, world!
... | See [the docs](http://docs.python.org/extending/extending.html#keyword-parameters-for-extension-functions): you want to use `PyArg_ParseTupleAndKeywords`, documented at the URL I gave.
So for example:
```
def foo(bar, baz="something or other"):
print bar, baz
```
becomes (roughly -- haven't tested it!):
```
#in... |
CSV to JSON script | 1,884,395 | 7 | 2009-12-10T22:02:23Z | 1,884,455 | 15 | 2009-12-10T22:10:57Z | [
"python",
"json",
"csv"
] | I took this script from [here](http://www.johntron.com/creations/csv-to-json/):
```
import csv
from itertools import izip
f = open( '/django/sw2/wkw2/csvtest1.csv', 'r' )
reader = csv.reader( f )
keys = ( "firm_url", "firm_name", "first", "last", "school", "year_graduated" )
out = []
for property in reader:
proper... | Change the nested `for` loop to:
```
out = [dict(zip(keys, property)) for property in reader]
```
and, no, `print out` will not emit valid JSON -- use `print json.dumps(out)` (you'll need to `import json` too of course -- that's a Python 2.6 standard library module but you can find versions working with 2.5 if that's... |
How important is it to check return values when using the Python C API? | 1,884,684 | 3 | 2009-12-10T22:55:33Z | 1,884,752 | 8 | 2009-12-10T23:08:44Z | [
"python",
"c",
"memory-management"
] | It seems that everytime I call a function that returns a PyObject\*, I have to add four lines of error checking. Example:
```
py_fullname = PyObject_CallMethod(os, "path.join", "ss", folder, filename);
if (!py_fullname) {
Py_DECREF(pygame);
Py_DECREF(os);
return NULL;
}
image = PyObject_CallMethodObjArgs(p... | That's why `goto` is alive (though not entirely well;-) in C coding (as opposed to C++ and other languages that support exceptions): it's the only decent way to NOT have such repeated blocks of termination all over the mainline of your code -- a conditional forward jump to `errorexit` at each return-value check, with a... |
Lost connection to MySQL server during query | 1,884,859 | 28 | 2009-12-10T23:29:47Z | 1,884,913 | 7 | 2009-12-10T23:40:50Z | [
"python",
"mysql"
] | I have a huge table and I need to process all rows in it. I'm always getting this Lost connection message and I'm not able to reconnect and restore the cursor to the last position it was. This is basically the code I have here:
```
#
import MySQLdb
class DB:
conn = None
def connect(self):
self.conn = MySQLdb... | You need to increase the timeout on your connection. If you can't or don't want to do that for some reason, you could try calling:
```
data = db.query(sql).store_result()
```
This will fetch all the results immediately, then your connection won't time out halfway through iterating over them. |
Lost connection to MySQL server during query | 1,884,859 | 28 | 2009-12-10T23:29:47Z | 1,884,918 | 27 | 2009-12-10T23:41:59Z | [
"python",
"mysql"
] | I have a huge table and I need to process all rows in it. I'm always getting this Lost connection message and I'm not able to reconnect and restore the cursor to the last position it was. This is basically the code I have here:
```
#
import MySQLdb
class DB:
conn = None
def connect(self):
self.conn = MySQLdb... | The mysql docs have a whole page dedicated to this error:
<http://dev.mysql.com/doc/refman/5.0/en/gone-away.html>
of note are
* You can also get these errors if you send a query to the server that is incorrect or too large. If mysqld receives a packet that is too large or out of order, it assumes that something has g... |
Lost connection to MySQL server during query | 1,884,859 | 28 | 2009-12-10T23:29:47Z | 9,603,681 | 7 | 2012-03-07T14:51:24Z | [
"python",
"mysql"
] | I have a huge table and I need to process all rows in it. I'm always getting this Lost connection message and I'm not able to reconnect and restore the cursor to the last position it was. This is basically the code I have here:
```
#
import MySQLdb
class DB:
conn = None
def connect(self):
self.conn = MySQLdb... | Make sure you close cursor before connection. I've resolved my problem with this:
```
if cur and con:
cur.close()
con.close()
``` |
Killing the children with the parent | 1,884,941 | 14 | 2009-12-10T23:46:56Z | 13,280,892 | 11 | 2012-11-08T00:58:05Z | [
"python",
"subprocess",
"sigkill"
] | I have a program spawning and communicating with CPU heavy, unstable processes, not created by me. If my app crashes or is killed by `SIGKILL`, I want the subprocesses to get killed as well, so the user don´t have to track them down and kill them manually.
I know this topic has been covered before, but I have tried a... | I know it's been years, but I found a simple (slightly hacky) solution to this problem. From your parent process, wrapping all your calls around a very simple C program that calls prctl() and then exec() solves this problem on Linux. I call it "yeshup":
```
#include <linux/prctl.h>
#include <signal.h>
#include <unistd... |
How can I get optparse's OptionParser to ignore invalid options? | 1,885,161 | 18 | 2009-12-11T00:53:21Z | 1,885,285 | 9 | 2009-12-11T01:28:29Z | [
"python",
"optparse"
] | In python's `OptionParser`, how can I instruct it to ignore undefined options supplied to method `parse_args`?
e.g.
I've only defined option `--foo` for my `OptionParser` instance, but I call `parse_args` with list
`[ '--foo', '--bar' ]`
EDIT:
I don't care if it filters them out of the original list. I just w... | By default there is no way to modify the behavior of the call to `error()` that is raised when an undefined option is passed. From the documentation at the bottom of the section on [how optparse handles errors](http://docs.python.org/library/optparse.html#how-optparse-handles-errors):
> If optparseâs default error-h... |
How can I get optparse's OptionParser to ignore invalid options? | 1,885,161 | 18 | 2009-12-11T00:53:21Z | 9,307,174 | 33 | 2012-02-16T07:28:18Z | [
"python",
"optparse"
] | In python's `OptionParser`, how can I instruct it to ignore undefined options supplied to method `parse_args`?
e.g.
I've only defined option `--foo` for my `OptionParser` instance, but I call `parse_args` with list
`[ '--foo', '--bar' ]`
EDIT:
I don't care if it filters them out of the original list. I just w... | Here's one way to have unknown arguments added to the result `args` of `OptionParser.parse_args`, with a simple subclass.
```
from optparse import (OptionParser,BadOptionError,AmbiguousOptionError)
class PassThroughOptionParser(OptionParser):
"""
An unknown option pass-through implementation of OptionParser.
... |
How do I un-escape a backslash-escaped string in python? | 1,885,181 | 39 | 2009-12-11T01:00:01Z | 1,885,197 | 73 | 2009-12-11T01:04:17Z | [
"python",
"string",
"escaping"
] | Suppose I have a string which is a backslash-escaped version of another string. Is there an easy way, in Python, to unescape the string? I could, for example, do:
```
>>> escaped_str = '"Hello,\\nworld!"'
>>> raw_str = eval(escaped_str)
>>> print raw_str
Hello,
world!
>>>
```
However that involves passing a (possibly... | ```
>>> print '"Hello,\\nworld!"'.decode('string_escape')
"Hello,
world!"
``` |
How do I un-escape a backslash-escaped string in python? | 1,885,181 | 39 | 2009-12-11T01:00:01Z | 1,885,211 | 12 | 2009-12-11T01:07:36Z | [
"python",
"string",
"escaping"
] | Suppose I have a string which is a backslash-escaped version of another string. Is there an easy way, in Python, to unescape the string? I could, for example, do:
```
>>> escaped_str = '"Hello,\\nworld!"'
>>> raw_str = eval(escaped_str)
>>> print raw_str
Hello,
world!
>>>
```
However that involves passing a (possibly... | You can use `ast.literal_eval` which is safe:
> Safely evaluate an expression node or a string containing a Python
> expression. The string or node provided may only consist of the
> following Python literal structures: strings, numbers, tuples, lists,
> dicts, booleans, and None. (END)
Like this:
```
>>> import ast... |
How do I tell PyLint "it's a variable, not a constant" to stop message C0103? | 1,885,251 | 31 | 2009-12-11T01:15:52Z | 1,885,262 | 38 | 2009-12-11T01:17:24Z | [
"python",
"pylint"
] | I have a module-level variable in my Python 2.6 program named "\_log", which PyLint complains about:
```
C0103: Invalid name "_log" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
```
Having read [this answer](http://stackoverflow.com/questions/709490/python-code-convention-using-pylint/709709#709709) I understand why ... | ```
# pylint: disable-msg=C0103
```
Put it in the scope where you want these warnings to be ignored. You can also make the above an end-of-line comment, to disable the message only for that line of code.
IIRC it is true that pylint interprets all module-level variables as being 'constants'.
newer versions of pylint ... |
How slow are Python/django exceptions? | 1,885,292 | 5 | 2009-12-11T01:31:49Z | 1,885,301 | 10 | 2009-12-11T01:34:09Z | [
"python",
"django",
"exception"
] | is python exception slow?
I'm kind using python exceptions to structure programm follow in my web application, and I'm wondering how throwing exceptions will affect performance of my application. what is your thoughts?
which one of the following statements is less expensive in terms of memory and cpu?
```
try:
ar... | To really understand the performance of your system, you'll have to profile it. But Python is a language that encourages using exceptions like this, so they don't have an unusual overhead as they do in some other languages.
For example, sometimes people debate this choice:
```
if hasattr(obj, "attr"):
use(obj.att... |
How slow are Python/django exceptions? | 1,885,292 | 5 | 2009-12-11T01:31:49Z | 1,885,316 | 8 | 2009-12-11T01:37:37Z | [
"python",
"django",
"exception"
] | is python exception slow?
I'm kind using python exceptions to structure programm follow in my web application, and I'm wondering how throwing exceptions will affect performance of my application. what is your thoughts?
which one of the following statements is less expensive in terms of memory and cpu?
```
try:
ar... | [This guy](http://paltman.com/2008/jan/18/try-except-performance-in-python-a-simple-test/) did a nice little writeup of testing try/except speed with dicts, I sure it would have some analogue in your case. Either way, doing a nice profile will give you the best info. |
How slow are Python/django exceptions? | 1,885,292 | 5 | 2009-12-11T01:31:49Z | 1,885,333 | 14 | 2009-12-11T01:44:55Z | [
"python",
"django",
"exception"
] | is python exception slow?
I'm kind using python exceptions to structure programm follow in my web application, and I'm wondering how throwing exceptions will affect performance of my application. what is your thoughts?
which one of the following statements is less expensive in terms of memory and cpu?
```
try:
ar... | Handling exceptions will be the least of your worries with regards to performance. I would suggest, however, that you use a shortcut provided by Django for you:
```
from django.shortcuts import get_object_or_404
artist = get_object_or_404(Artist, id=id)
```
Which either assigns the object to `artist` or returns a 404... |
How to join lists element-wise in Python? | 1,885,300 | 3 | 2009-12-11T01:34:06Z | 1,885,309 | 12 | 2009-12-11T01:35:32Z | [
"python",
"list"
] | ```
l1 = [4, 6, 8]
l2 = [a, b, c]
```
result = `[(4,a),(6,b),(8,c)]`
How do I do that? | The [`zip`](http://docs.python.org/library/functions.html#zip) standard function does this for you:
```
>>> l1 = [4, 6, 8]
>>> l2 = ["a", "b", "c"]
>>> zip(l1, l2)
[(4, 'a'), (6, 'b'), (8, 'c')]
```
If you're using Python 3.x, then `zip` returns a generator and you can convert it to a list using the `list()` construc... |
How to join lists element-wise in Python? | 1,885,300 | 3 | 2009-12-11T01:34:06Z | 1,885,310 | 10 | 2009-12-11T01:36:01Z | [
"python",
"list"
] | ```
l1 = [4, 6, 8]
l2 = [a, b, c]
```
result = `[(4,a),(6,b),(8,c)]`
How do I do that? | Use [`zip`](http://docs.python.org/library/functions.html#zip).
```
l1 = [1, 2, 3]
l2 = [4, 5, 6]
>>> zip(l1, l2)
[(1, 4), (2, 5), (3, 6)]
```
Note that if your lists are of different lengths, the result will be truncated to the length of the shortest input.
```
>>> print zip([1, 2, 3],[4, 5, 6, 7])
[(1, 4), (2, 5),... |
Is it possible to keep the column order using the Python csv DictReader | 1,885,324 | 24 | 2009-12-11T01:41:10Z | 1,885,353 | 32 | 2009-12-11T01:50:46Z | [
"python",
"csv"
] | For example, my csv has columns as below:
> ID, ID2, Date, Job No, Code
I need to write the columns back in the same order. The dict jumbles the order immediately, so I believe it's more of a problem with the reader. | Python's `dict`s do NOT maintain order.
However, the instance of `csv.DictReader` that you're using (after you've read the first row!-) **does** have a `.fieldnames` list of strings, which **IS** in order.
So,
```
for rowdict in myReader:
print ['%s:%s' % (f, rowdict[f]) for f in myReader.fieldnames]
```
will sho... |
Python 2.6: reading data from a Windows Console application. (os.system?) | 1,885,776 | 4 | 2009-12-11T04:24:56Z | 1,885,778 | 8 | 2009-12-11T04:26:35Z | [
"python",
"windows",
"console",
"exe"
] | I have a Windows console application that returns some text. I want to read that text in a Python script. I have tried reading it by using os.system, but it is not working properly.
```
import os
foo = os.system('test.exe')
```
Assuming that test.exe returns "bar", I want the variable foo to be set to "bar". But what... | Please use subprocess
```
import subprocess
foo = subprocess.Popen('test.exe',stdout=subprocess.PIPE,stderr=subprocess.PIPE)
```
<http://docs.python.org/library/subprocess.html#module-subprocess> |
Pythonic way to ignore for loop control variable | 1,885,868 | 10 | 2009-12-11T04:57:44Z | 1,885,884 | 10 | 2009-12-11T05:04:29Z | [
"python"
] | A Python program I'm writing is to read a set number of lines from the top of a file, and the program needs to preserve this header for future use. Currently, I'm doing something similar to the following:
```
header = ''
header_len = 4
for i in range(1, header_len):
header += file_handle.readline()... | I'm not sure what the Pylint rules are, but you could use the '\_' throwaway variable name.
```
header = ''
header_len = 4
for _ in range(1, header_len):
header += file_handle.readline()
``` |
Pythonic way to ignore for loop control variable | 1,885,868 | 10 | 2009-12-11T04:57:44Z | 1,885,909 | 10 | 2009-12-11T05:12:20Z | [
"python"
] | A Python program I'm writing is to read a set number of lines from the top of a file, and the program needs to preserve this header for future use. Currently, I'm doing something similar to the following:
```
header = ''
header_len = 4
for i in range(1, header_len):
header += file_handle.readline()... | ```
import itertools
header_lines = list(itertools.islice(file_handle, header_len))
# or
header = "".join(itertools.islice(file_handle, header_len))
```
Note that with the first, the newline chars will still be present, to strip them:
```
header_lines = list(n.rstrip("\n")
for n in itertools.isli... |
Pythonic way to ignore for loop control variable | 1,885,868 | 10 | 2009-12-11T04:57:44Z | 1,887,169 | 8 | 2009-12-11T10:25:53Z | [
"python"
] | A Python program I'm writing is to read a set number of lines from the top of a file, and the program needs to preserve this header for future use. Currently, I'm doing something similar to the following:
```
header = ''
header_len = 4
for i in range(1, header_len):
header += file_handle.readline()... | ```
f = open('fname')
header = [next(f) for _ in range(header_len)]
```
Since you're going to write header back to the new files, you don't need to do anything with it. To write it back to the new file:
```
open('new', 'w').writelines(header + list_of_lines)
```
if you know the number of lines in the old file, `list... |
Return value from thread | 1,886,090 | 47 | 2009-12-11T06:00:58Z | 1,886,176 | 54 | 2009-12-11T06:24:14Z | [
"python",
"multithreading",
"python-multithreading",
"exit-code"
] | How do I get a thread to return a tuple or any value of my choice back to the parent in Python? | I suggest you instantiate a [Queue.Queue](http://docs.python.org/library/queue.html?highlight=queue#Queue.Queue) before starting the thread, and pass it as one of the thread's args: before the thread finishes, it `.put`s the result on the queue it received as an argument. The parent can `.get` or `.get_nowait` it at wi... |
Return value from thread | 1,886,090 | 47 | 2009-12-11T06:00:58Z | 1,891,891 | 12 | 2009-12-12T01:27:10Z | [
"python",
"multithreading",
"python-multithreading",
"exit-code"
] | How do I get a thread to return a tuple or any value of my choice back to the parent in Python? | If you were calling join() to wait for the thread to complete, you could simply attach the result to the Thread instance itself and then retrieve it from the main thread after the join() returns.
On the other hand, you don't tell us how you intend to discover that the thread is done and that the result is available. I... |
Use pyExcelerator to generate dynamic Excel file with Django. Ensure unique temporary filename | 1,886,744 | 3 | 2009-12-11T09:03:32Z | 1,886,836 | 11 | 2009-12-11T09:24:59Z | [
"python",
"django",
"excel",
"temporary-files",
"pyexcelerator"
] | I'd like to generate a dynamic Excel file on request from Django. The library pyExcelerator does this, but I haven't found any way to use the contents of the Excel file without generating a server-side temporary Excel file, reading it, using its contents and deleting it.
The problem is that pyExcelerator only way to e... | pyExcelerator is unmaintained, but it has a fork, [xlwt](http://pypi.python.org/pypi/xlwt), which is maintained and has more features, including allowing you to save to any file-like object. This includes saving straight to a Django `HttpResponse`:
```
from django.http import HttpResponse
import xlwt
def my_view(requ... |
How to compare datetime in Django? | 1,887,354 | 4 | 2009-12-11T11:08:49Z | 1,887,367 | 18 | 2009-12-11T11:11:06Z | [
"python",
"django",
"datetime",
"django-views"
] | Suppose I have:
```
ds = datetime.datetime.now
dd = Entry.objects.get(pk=id).pub_date
```
How to compare 2 objects above? I want to get the time difference between them.
Please help me solve this problem. Thank you very much ! | I am assuming that `pub_date` is a `django.db.models.DateField`, which means you can treat it as a `datetime.date` object.
If you convert them to the same type (either `datetime.datetime` or `datetime.date`) and subtract one from the other, you will get an instance of `datetime.timedelta`.
As you are using `datetime.... |
How to convert string to hexadecimal integer in Python? | 1,887,392 | 3 | 2009-12-11T11:18:15Z | 1,887,418 | 7 | 2009-12-11T11:21:53Z | [
"python",
"integer",
"hex"
] | hi I get user argv from command line as follows: `'0x000aff00'`
and I want python to treat it as hex directly...
```
str = sys.argv[1]
```
how is it possible? thanks! | Try: `i = int(sys.argv[1], 16)` |
Convert Python byte to "unsigned 8 bit integer" | 1,887,506 | 12 | 2009-12-11T11:38:47Z | 1,887,569 | 7 | 2009-12-11T11:49:44Z | [
"python",
"python-3.x"
] | I am reading in a byte array/list from socket. I want Python to treat the first byte as an "unsigned 8 bit integer". How is it possible to get its integer value as an unsigned 8 bit integer? | bytes/bytearray is a sequence of integers. If you just access an element by its index you'll have an integer:
```
>>> b'abc'
b'abc'
>>> _[0]
97
```
By their very definition, bytes and bytearrays contain integers in the `range(0, 256)`. So they're "unsigned 8-bit integers". |
Convert Python byte to "unsigned 8 bit integer" | 1,887,506 | 12 | 2009-12-11T11:38:47Z | 1,887,570 | 17 | 2009-12-11T11:49:51Z | [
"python",
"python-3.x"
] | I am reading in a byte array/list from socket. I want Python to treat the first byte as an "unsigned 8 bit integer". How is it possible to get its integer value as an unsigned 8 bit integer? | Use the [struct](http://docs.python.org/3.1/library/struct.html#module-struct) module.
```
import struct
value = struct.unpack('B', data[0])[0]
```
Note that unpack always returns a tuple, even if you're only unpacking one item.
Also, have a look at [this SO question](http://stackoverflow.com/questions/1591920/pytho... |
how to redirect complete output of a script | 1,887,618 | 3 | 2009-12-11T12:01:10Z | 1,887,735 | 15 | 2009-12-11T12:21:40Z | [
"python",
"shell",
"cron"
] | I have a simple cronjob running every day at 18:35:
```
05 18 * * * ~/job.sh 2>&1 >> ~/job.log
```
So the output of ~/job.sh should be written into ~/job.log. In job.sh, there are some echo commands and a few python scripts are executed, e.g.:
```
echo 'doing xyz'
python doXYZ.py
```
Now, whatever output the python... | Arkaitz has the simplest solution. However, to see what's wrong with your snippet we need to go into the bash manual:
> Note that the order of redirections is significant. For example, the
> command
>
> ```
> ls > dirlist 2>&1
> ```
>
> directs both standard output and standard error to the file dirlist,
> while the... |
Python hexadecimal comparison | 1,888,114 | 3 | 2009-12-11T13:35:41Z | 1,888,133 | 9 | 2009-12-11T13:38:51Z | [
"python",
"hex"
] | Hey guys, I got a problem I was hoping someone could help me figure out!
I have a string with a hexadecimal number = `'0x00000000'` which means:
```
0x01000000 = apple
0x00010000 = orange
0x00000100 = banana
```
All combinations with those are possible. i.e., `0x01010000 = apple & orange`
How can I from my stri... | convert your string to an integer, by using the `int()` built-in function and specifying a base:
```
>>> int('0x01010000',16)
16842752
```
now you have a standard integer representing a bitset. use `&`, `|` and any other bitwise operator to test individual bits.
```
>>> value = int('0x01010000',16)
>>> apple = 0x0... |
numpy : How to convert an array type quickly | 1,888,870 | 13 | 2009-12-11T15:35:31Z | 1,889,627 | 23 | 2009-12-11T17:34:10Z | [
"python",
"numpy"
] | I find the astype() method of numpy arrays not very efficient. I have an array containing
3 million of Uint8 point. Multiplying it by a 3x3 matrix takes 2 second, but converting the result from uint16 to uint8 takes another second.
More precisely :
```
print time.clock()
imgarray = np.dot(imgarray, M)/255
... | When you use `imgarray = imgarray.astype('B')`, you get a copy of the array, cast to the specified type. This requires extra memory allocation, even though you immediately flip imgarray to point to the newly allocated array.
If you use `imgarray.view('uint8')`, then you get a view of the array. This uses the same data... |
SQLAlchemy Many-to-Many Relationship on a Single Table | 1,889,251 | 10 | 2009-12-11T16:39:51Z | 5,652,169 | 13 | 2011-04-13T16:01:51Z | [
"python",
"orm",
"sqlalchemy"
] | I have a SQLAlchemy model set up in my application that should mimic the functionality of "followers" on Twitter, ie. users have have a many-to-many relationship with eachother (both followers and following). The tables are structured as follows (sa is the sqlalchemy module):
```
t_users = sa.Table("users", meta.metad... | You can also do this declaratively.
Here is a similar example based on teh above code, I do use the backref.
```
VolumeRelationship = Table(
'VolumeRelationship', Base.metadata,
Column('ParentID', Integer, ForeignKey('Volumes.ID')),
Column('VolumeID', Integer, ForeignKey('Volumes.ID'))
)
class Volume... |
Deleting directory in Python | 1,889,597 | 25 | 2009-12-11T17:29:20Z | 1,889,686 | 32 | 2009-12-11T17:41:23Z | [
"python",
"directory",
"delete-file"
] | `shutil.rmtree` will not delete read-only files on Windows. Is there a python equivalent of "rm -rf" ? Why oh why is this such a pain? | `shutil.rmtree` can take an error-handling function that will be called when it has problem removing a file. You can use that to force the removal of the problematic file(s).
Inspired by <http://mail.python.org/pipermail/tutor/2006-June/047551.html> and <http://techarttiki.blogspot.com/2008/08/read-only-windows-files-... |
Code bacteria: evolving mathematical behavior | 1,889,810 | 9 | 2009-12-11T18:00:27Z | 1,889,855 | 10 | 2009-12-11T18:06:36Z | [
"python",
"genetic-programming",
"evolutionary-algorithm"
] | It would not be my intention to put a link on my blog, but I don't have any other method to clarify what I really mean. The article is quite long, and it's in three parts ([1](http://forthescience.org/blog/2009/05/15/pythonic-evolution-part-1/),[2](http://forthescience.org/blog/2009/05/23/pythonic-evolution-part-2/),[3... | If you are optimising the code, perhaps you are engaged in **[genetic programming](http://en.wikipedia.org/wiki/Genetic_programming)**? |
Inheritance and factory functions in Python and Django | 1,891,004 | 5 | 2009-12-11T21:32:35Z | 1,896,343 | 7 | 2009-12-13T12:23:54Z | [
"python",
"django",
"inheritance"
] | I'm creating a Django app that uses some inheritance in it's model, mainly because I need to assign everything a UUID and a reference so I know what class it was. Here's a simplified version of the base class:
```
class BaseElement(models.Model):
uuid = models.CharField(max_length=64, editable=False, blank=True, d... | If you make `create()` a `@classmethod` instead of `@staticmethod`, you'll have access to the class object, which you can use instead of referring to it by name:
```
@classmethod
def create(cls, *args, **kwargs):
obj = cls(*args, **kwargs)
obj.set_defaults()
return obj
```
This is now generic and can go o... |
Python Exception Propagation | 1,891,572 | 7 | 2009-12-11T23:37:42Z | 1,891,615 | 20 | 2009-12-11T23:49:39Z | [
"python",
"exception"
] | I'm building a tool where as exceptions propagate upwards, new data about the context of the exception gets added to the exception. The issue is, by the time the exception gets to the top level, all of the extra context data is there, but only the very latest stack trace is shown. Is there an easy way to have an except... | Python exceptions are a bit like java, there is a way to cause the exception to be rethrown without truncating the stack.
Just use `raise` without an argument. The result it:
```
Traceback (most recent call last):
File "./exc.py", line 11, in <module>
b()
File "./exc.py", line 7, in b
a()
File "./exc.py... |
How to send EOF to Python sys.stdin from commandline? CTRL-D doesn't work | 1,892,215 | 5 | 2009-12-12T03:54:43Z | 1,892,639 | 11 | 2009-12-12T07:12:27Z | [
"python",
"unix",
"command-line",
"buffer"
] | I am writing to my Python process from the commandline on unix. I want to send EOF (or somehow flush the stdin buffer, so Python can read my input.)
If I hit CTRL-C, I get a KeyboardError.
If I hit CTRL-D, the program just stops.
How do I flush the stdin buffer? | Control-D should NOT make your program "just stop" -- it should close standard input, and if your program deals with that properly, it may perfectly well continue if it needs to!
For example, given the following `st.py`:
```
import sys
def main():
inwas = []
for line in sys.stdin:
inwas.append(line)
print ... |
How do derived class constructors work in python? | 1,892,269 | 11 | 2009-12-12T04:16:26Z | 1,892,281 | 20 | 2009-12-12T04:22:28Z | [
"python"
] | I have the following base class:
```
class NeuralNetworkBase:
def __init__(self, numberOfInputs, numberOfHiddenNeurons, numberOfOutputs):
self.inputLayer = numpy.zeros(shape = (numberOfInputs))
self.hiddenLayer = numpy.zeros(shape = (numberOfHiddenNeurons))
self.outputLayer = numpy.zeros(sh... | > Does python call by default the base
> class constructor's when running the
> derived class' one? Do I have to
> implicitly do it inside the derived
> class constructor?
No and yes.
This is consistent with the way Python handles other overridden methods - you have to explicitly call any method from the base class t... |
Why program functionally in Python? | 1,892,324 | 34 | 2009-12-12T04:46:23Z | 1,892,345 | 19 | 2009-12-12T04:56:44Z | [
"python",
"functional-programming"
] | At work we used to program our Python in a pretty standard OO way. Lately, a couple guys got on the functional bandwagon. And their code now contains lots more lambdas, maps and reduces. I understand that functional languages are good for concurrency but does programming Python functionally really help with concurrency... | I program in Python everyday, and I have to say that too much 'bandwagoning' toward OO or functional could lead toward missing elegant solutions. I believe that both paradigms have their advantages to certain problems - and I think that's when you know what approach to use. Use a functional approach when it leaves you ... |
Why program functionally in Python? | 1,892,324 | 34 | 2009-12-12T04:46:23Z | 1,892,585 | 15 | 2009-12-12T06:41:06Z | [
"python",
"functional-programming"
] | At work we used to program our Python in a pretty standard OO way. Lately, a couple guys got on the functional bandwagon. And their code now contains lots more lambdas, maps and reduces. I understand that functional languages are good for concurrency but does programming Python functionally really help with concurrency... | This answer is completely re-worked. It incorporates a lot of observations from the other answers.
As you can see, there is a lot of strong feelings surrounding the use of functional programming constructs in Python. There are three major groups of ideas here.
First, almost everybody but the people who are most wedde... |
Why program functionally in Python? | 1,892,324 | 34 | 2009-12-12T04:46:23Z | 1,892,614 | 66 | 2009-12-12T07:02:30Z | [
"python",
"functional-programming"
] | At work we used to program our Python in a pretty standard OO way. Lately, a couple guys got on the functional bandwagon. And their code now contains lots more lambdas, maps and reduces. I understand that functional languages are good for concurrency but does programming Python functionally really help with concurrency... | **Edit**: I've been taken to task in the comments (in part, it seems, by fanatics of FP in Python, but not exclusively) for not providing more explanations/examples, so, expanding the answer to supply some.
`lambda`, even more so `map` (and `filter`), **and** most especially `reduce`, are hardly ever the right tool fo... |
Why program functionally in Python? | 1,892,324 | 34 | 2009-12-12T04:46:23Z | 1,894,941 | 23 | 2009-12-12T22:40:08Z | [
"python",
"functional-programming"
] | At work we used to program our Python in a pretty standard OO way. Lately, a couple guys got on the functional bandwagon. And their code now contains lots more lambdas, maps and reduces. I understand that functional languages are good for concurrency but does programming Python functionally really help with concurrency... | FP is important not only for concurrency; in fact, there's virtually no concurrency in the canonical Python implementation (maybe 3.x changes that?). in any case, FP lends itself well to concurrency because it leads to programs with no or fewer (explicit) states. states are troublesome for a few reasons. one is that th... |
Why program functionally in Python? | 1,892,324 | 34 | 2009-12-12T04:46:23Z | 1,895,283 | 7 | 2009-12-13T01:25:29Z | [
"python",
"functional-programming"
] | At work we used to program our Python in a pretty standard OO way. Lately, a couple guys got on the functional bandwagon. And their code now contains lots more lambdas, maps and reduces. I understand that functional languages are good for concurrency but does programming Python functionally really help with concurrency... | Here's a short summary of positive answers when/why to program functionally.
* List comprehensions were imported from Haskell, a FP language. They are Pythonic. I'd prefer to write
> ```
> y = [i*2 for i in k if i % 3 == 0]
> ```
than to use an imperative construct (loop).
* I'd use `lambda` when giving a complicat... |
Why program functionally in Python? | 1,892,324 | 34 | 2009-12-12T04:46:23Z | 1,899,731 | 9 | 2009-12-14T08:50:05Z | [
"python",
"functional-programming"
] | At work we used to program our Python in a pretty standard OO way. Lately, a couple guys got on the functional bandwagon. And their code now contains lots more lambdas, maps and reduces. I understand that functional languages are good for concurrency but does programming Python functionally really help with concurrency... | The question, which seems to be mostly ignored here:
> does programming Python functionally really help with concurrency?
No. The value FP brings to concurrency is in eliminating state in computation, which is ultimately responsible for the hard-to-grasp nastiness of unintended errors in concurrent computation. But i... |
How to make a window jump to the front? | 1,892,339 | 21 | 2009-12-12T04:52:34Z | 6,795,115 | 32 | 2011-07-22T19:32:46Z | [
"python",
"tkinter"
] | How do I get a Tkinter application to jump to the front. Currently the window appears behind all my other windows and doesn't get focus.
Is there some method I should be calling? | Assuming you mean your application windows when you say "my other windows", you can use the `lift()` method on a Toplevel or Tk:
```
root.lift()
```
If you want the window to stay above all other windows, use:
```
root.attributes("-topmost", True)
```
Where `root` is your Toplevel or Tk. Don't forget the `-` infron... |
How to make a window jump to the front? | 1,892,339 | 21 | 2009-12-12T04:52:34Z | 8,775,078 | 20 | 2012-01-08T03:07:47Z | [
"python",
"tkinter"
] | How do I get a Tkinter application to jump to the front. Currently the window appears behind all my other windows and doesn't get focus.
Is there some method I should be calling? | If you're doing this on a Mac, use AppleEvents to give focus to Python. Eg:
```
import os
os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''')
``` |
Why import urlfetch from Google App Engines? | 1,893,012 | 6 | 2009-12-12T10:38:04Z | 1,893,680 | 15 | 2009-12-12T14:59:32Z | [
"python",
"google-app-engine",
"import",
"urlfetch"
] | [Here in Google App Engines](http://code.google.com/appengine/docs/python/urlfetch/overview.html) I got this code that would help fetch an HTML code of any web page by its URL:
```
from google.appengine.api import urlfetch
url = "http://www.google.com/"
result = urlfetch.fetch(url)
if result.status_code == 200:
doSome... | Python has libraries such as urllib and httplib for fetching URLs, but on App Engine, all requests must go through the custom urlfetch library. App Engine includes stubs for urllib and httplib that cause them to use urlfetch internally, but if you have a choice, using urlfetch directly is more efficient and flexible. |
PYTHONPATH vs. sys.path | 1,893,598 | 40 | 2009-12-12T14:33:36Z | 1,893,622 | 24 | 2009-12-12T14:39:06Z | [
"python",
"pythonpath",
"sys.path"
] | Another developer and I disagree about whether PYTHONPATH or sys.path should be used to allow Python to find a Python package in a user (e.g., development) directory.
We have a Python project with a typical directory structure:
```
Project
setup.py
package
__init__.py
lib.py
script.py
... | If the only reason to modify the path is for developers working from their working tree, then you should use an installation tool to set up your environment for you. virtualenv is very popular, and if you are using setuptools, you can simply run `setup.py develop` to semi-install the working tree in your current Python... |
PYTHONPATH vs. sys.path | 1,893,598 | 40 | 2009-12-12T14:33:36Z | 1,893,663 | 27 | 2009-12-12T14:54:30Z | [
"python",
"pythonpath",
"sys.path"
] | Another developer and I disagree about whether PYTHONPATH or sys.path should be used to allow Python to find a Python package in a user (e.g., development) directory.
We have a Python project with a typical directory structure:
```
Project
setup.py
package
__init__.py
lib.py
script.py
... | I hate PYTHONPATH. I find it brittle and annoying to set on a per-user basis (especially for daemon users) and keep track of as project folders move around. I would much rather set `sys.path` in the invoke scripts for standalone projects.
However `sys.path.append` isn't the way to do it. You can easily get duplicates,... |
Convert string representation of list to list in Python | 1,894,269 | 129 | 2009-12-12T18:19:03Z | 1,894,292 | 7 | 2009-12-12T18:29:02Z | [
"python",
"string"
] | I was wondering what the simplest way is to convert a `string` list like the following to a `list`:
```
x = u'[ "A","B","C" , " D"]'
```
Even in case user puts spaces in between the commas, and spaces inside of the quotes. I need to handle that as well to:
```
x = ["A", "B", "C", "D"]
```
in Python.
I know I can s... | ```
import ast
l = ast.literal_eval('[ "A","B","C" , " D"]')
l = [i.strip() for i in l]
``` |
Convert string representation of list to list in Python | 1,894,269 | 129 | 2009-12-12T18:19:03Z | 1,894,293 | 29 | 2009-12-12T18:29:08Z | [
"python",
"string"
] | I was wondering what the simplest way is to convert a `string` list like the following to a `list`:
```
x = u'[ "A","B","C" , " D"]'
```
Even in case user puts spaces in between the commas, and spaces inside of the quotes. I need to handle that as well to:
```
x = ["A", "B", "C", "D"]
```
in Python.
I know I can s... | The `eval` is dangerous - you shouldn't execute user input.
If you have 2.6 or newer, use ast instead of eval:
```
>>> import ast
>>> ast.literal_eval('["A","B" ,"C" ," D"]')
["A", "B", "C", " D"]
```
Once you have that, `strip` the strings.
If you're on an older version of Python, you can get very close to what yo... |
Convert string representation of list to list in Python | 1,894,269 | 129 | 2009-12-12T18:19:03Z | 1,894,296 | 214 | 2009-12-12T18:30:49Z | [
"python",
"string"
] | I was wondering what the simplest way is to convert a `string` list like the following to a `list`:
```
x = u'[ "A","B","C" , " D"]'
```
Even in case user puts spaces in between the commas, and spaces inside of the quotes. I need to handle that as well to:
```
x = ["A", "B", "C", "D"]
```
in Python.
I know I can s... | ```
>>> import ast
>>> x = u'[ "A","B","C" , " D"]'
>>> x = ast.literal_eval(x)
>>> x
['A', 'B', 'C', ' D']
>>> x = [n.strip() for n in x]
>>> x
['A', 'B', 'C', 'D']
```
[ast.literal\_eval](http://docs.python.org/library/ast.html#ast.literal%5Feval):
> Safely evaluate an expression node or a string containing a Pytho... |
variable name introspection in Python | 1,894,591 | 3 | 2009-12-12T20:23:10Z | 1,894,643 | 10 | 2009-12-12T20:44:24Z | [
"python",
"metaprogramming"
] | Is it possible to dynamically determine the name of a variable in Python?
For example, I sometimes have the following situation:
```
name = foo if bar else baz
type = alpha or bravo
D = {
"name": name,
"type": type
}
```
It would be nice if duplication there could be reduced with something like `D = makedic... | In the general case, you cannot deduce the name from a value (there might be no name, there might be multiple ones, etc); when you call your hypothetical `makedict(name)`, the **value** of `name` is what `makedict` receives, so (again, in the general case) it cannot discern what name (if any) the value came from. You c... |
python lxml on app engine? | 1,894,696 | 11 | 2009-12-12T21:04:14Z | 1,894,756 | 23 | 2009-12-12T21:28:19Z | [
"python",
"google-app-engine",
"beautifulsoup",
"lxml"
] | Can I use python lxml on google app engine? ( or do i have to use Beautiful Soup? )
I have started using Beautiful Soup but it seems slow. I am just starting to play with the idea of "screen scraping" data from other websites to create some sort of "mash-up". | **EDIT**: If you [use python2.7](http://code.google.com/appengine/docs/python/python27/using27.html) on AppEngine, the `lxml` library [is supported](http://code.google.com/appengine/docs/python/python27/newin27.html#Supported_Third-Party_Libraries).
---
Short answer: [you can't](http://code.google.com/p/googleappengi... |
python lxml on app engine? | 1,894,696 | 11 | 2009-12-12T21:04:14Z | 15,529,850 | 11 | 2013-03-20T16:54:09Z | [
"python",
"google-app-engine",
"beautifulsoup",
"lxml"
] | Can I use python lxml on google app engine? ( or do i have to use Beautiful Soup? )
I have started using Beautiful Soup but it seems slow. I am just starting to play with the idea of "screen scraping" data from other websites to create some sort of "mash-up". | To add to Caio's revised answer, you can use `lxml` and this is how to do it:
In your `app.yaml` file, add the following:
```
libraries:
- name: lxml
version: "2.3" # or "latest"
```
Now `import lxml` will work in your Python script.
[Here is the link to the official documentation.](https://developers.google.co... |
Printing BFS (Binary Tree) in Level Order with _specific formatting_ | 1,894,846 | 21 | 2009-12-12T22:04:00Z | 1,894,860 | 7 | 2009-12-12T22:11:22Z | [
"python",
"algorithm",
"binary-tree",
"breadth-first-search"
] | To begin with, this question is not a dup of [this one](http://stackoverflow.com/questions/1104644/how-would-you-print-out-the-data-in-a-binary-tree-level-by-level-starting-at-th), but builds on it.
Taking the tree in that question as an example,
```
1
/ \
2 3
/ / \
4 5 6
```
How would you modify ... | Sounds like [breadth-first traversal](http://www.cs.bu.edu/teaching/cs112/spring-2000/breadth-first/) to me.
Breadth-first traversal is implemented with a [queue](http://en.wikipedia.org/wiki/Queue%5F%28data%5Fstructure%29). Here, simply insert in the queue a special token that indicate that a newline must be printed.... |
Printing BFS (Binary Tree) in Level Order with _specific formatting_ | 1,894,846 | 21 | 2009-12-12T22:04:00Z | 1,894,914 | 32 | 2009-12-12T22:33:01Z | [
"python",
"algorithm",
"binary-tree",
"breadth-first-search"
] | To begin with, this question is not a dup of [this one](http://stackoverflow.com/questions/1104644/how-would-you-print-out-the-data-in-a-binary-tree-level-by-level-starting-at-th), but builds on it.
Taking the tree in that question as an example,
```
1
/ \
2 3
/ / \
4 5 6
```
How would you modify ... | Just build one level at a time, e.g.:
```
class Node(object):
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def traverse(rootnode):
thislevel = [rootnode]
while thislevel:
nextlevel = list()
for n in thislevel:
print n.value,
... |
Pythonic way to write a for loop that doesn't use the loop index | 1,895,615 | 8 | 2009-12-13T05:11:46Z | 1,895,710 | 18 | 2009-12-13T06:06:44Z | [
"eclipse",
"for-loop",
"python"
] | This is to do with the following code, which uses a for loop to generate a series of random offsets for use elsewhere in the program.
The index of this for loop is unused, and this is resulting in the 'offending' code being highlighted as a warning by Eclipse / PyDev
```
def RandomSample(count):
pattern = []
... | Just for reference for ignoring variables in PyDev
By default pydev will ignore following variables
```
['_', 'empty', 'unused', 'dummy']
```
You can add more by passing supression parameters
```
-E, --unusednames ignore unused locals/arguments if name is one of these values
```
Ref:
<http://eclipse-pydev.sourcea... |
Using cProfile results with KCacheGrind | 1,896,032 | 42 | 2009-12-13T09:43:00Z | 1,896,129 | 7 | 2009-12-13T10:40:34Z | [
"python",
"profiling",
"kcachegrind",
"cprofile"
] | I'm using cProfile to profile my Python program. Based upon [this talk](http://blip.tv/file/1957086/) I was under the impression that KCacheGrind could parse and display the output from cProfile.
However, when I go to import the file, KCacheGrind just displays an 'Unknown File Format' error in the status bar and sits ... | It can be done using an external module called [lscallproftree](http://www.gnome.org/~johan/lsprofcalltree.py)
This article explains how: [CherryPy - CacheGrind](http://tools.cherrypy.org/wiki/Cachegrind)
With my resulting code looking like so:
```
...
if profile:
import cProfile
import lsprofcalltree
p... |
Using cProfile results with KCacheGrind | 1,896,032 | 42 | 2009-12-13T09:43:00Z | 2,534,743 | 16 | 2010-03-28T22:01:10Z | [
"python",
"profiling",
"kcachegrind",
"cprofile"
] | I'm using cProfile to profile my Python program. Based upon [this talk](http://blip.tv/file/1957086/) I was under the impression that KCacheGrind could parse and display the output from cProfile.
However, when I go to import the file, KCacheGrind just displays an 'Unknown File Format' error in the status bar and sits ... | You could use [`profilestats.profile`](http://pypi.python.org/pypi/profilestats/) decorator (`$ pip install profilestats`) -- a simple wrapper for [pyprof2calltree](http://pypi.python.org/pypi/pyprof2calltree) module (rebranding of `lsprofcalltree.py`):
```
from profilestats import profile
@profile
def func():
# ... |
Using cProfile results with KCacheGrind | 1,896,032 | 42 | 2009-12-13T09:43:00Z | 3,561,512 | 73 | 2010-08-24T22:26:25Z | [
"python",
"profiling",
"kcachegrind",
"cprofile"
] | I'm using cProfile to profile my Python program. Based upon [this talk](http://blip.tv/file/1957086/) I was under the impression that KCacheGrind could parse and display the output from cProfile.
However, when I go to import the file, KCacheGrind just displays an 'Unknown File Format' error in the status bar and sits ... | With cProfile you can also profile existing programs, without making any separate profiling script. Just run program with profiler
```
python -m cProfile -o profile_data.pyprof script_to_profile.py
```
and open profile data in kcachegrind with pyprof2calltree, whose -k switch automatically opens data in kcachegrind
... |
How to determine the datatype in Python? | 1,896,261 | 2 | 2009-12-13T11:41:30Z | 1,896,268 | 8 | 2009-12-13T11:45:38Z | [
"python"
] | astring
('a','tuple')
How do I determine if "x" is a tuple or string? | ```
if isinstance(x, basestring):
# a string
else:
try: it = iter(x)
except TypeError:
# not an iterable
else:
# iterable (tuple, list, etc)
```
[@Alex Martelli's answer](http://stackoverflow.com/questions/1549801/differences-between-isinstance-and-type-in-python/1549854#1549854) describes in... |
Python: How to read huge text file into memory | 1,896,674 | 19 | 2009-12-13T14:34:04Z | 1,896,687 | 17 | 2009-12-13T14:38:05Z | [
"python",
"memory",
"sorting",
"large-files"
] | I'm using Python 2.6 on a Mac Mini with 1GB RAM. I want to read in a huge text file
```
$ ls -l links.csv; file links.csv; tail links.csv
-rw-r--r-- 1 user user 469904280 30 Nov 22:42 links.csv
links.csv: ASCII text, with CRLF line terminators
4757187,59883
4757187,99822
4757187,66546
4757187,638452
4757187,462795... | There is a recipe for sorting files larger than RAM [on this page](http://code.activestate.com/recipes/466302/), though you'd have to adapt it for your case involving CSV-format data. There are also links to additional resources there.
**Edit:** True, the file on disk is not "larger than RAM", but the in-memory repres... |
Running unittest with typical test directory structure | 1,896,918 | 286 | 2009-12-13T16:10:23Z | 1,896,959 | 14 | 2009-12-13T16:25:43Z | [
"python",
"unit-testing"
] | The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own `test` directory:
```
new_project/
antigravity/
antigravity.py
test/
test_antigravity.py
setup.py
etc.
```
for example see this [Python project howto](http://infini... | From the article you linked to:
> Create a test\_modulename.py file and
> put your unittest tests in it. Since
> the test modules are in a separate
> directory from your code, you may need
> to add your moduleâs parent directory
> to your PYTHONPATH in order to run
> them:
>
> ```
> $ cd /path/to/googlemaps
>
> $ ex... |
Running unittest with typical test directory structure | 1,896,918 | 286 | 2009-12-13T16:10:23Z | 1,897,665 | 36 | 2009-12-13T20:40:58Z | [
"python",
"unit-testing"
] | The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own `test` directory:
```
new_project/
antigravity/
antigravity.py
test/
test_antigravity.py
setup.py
etc.
```
for example see this [Python project howto](http://infini... | The simplest solution for your users is to provide an executable script (`runtests.py` or some such) which bootstraps the necessary test environment, including, if needed, adding your root project directory to sys.path temporarily. This doesn't require users to set environment variables, something like this works fine ... |
Running unittest with typical test directory structure | 1,896,918 | 286 | 2009-12-13T16:10:23Z | 2,992,477 | 13 | 2010-06-07T19:30:11Z | [
"python",
"unit-testing"
] | The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own `test` directory:
```
new_project/
antigravity/
antigravity.py
test/
test_antigravity.py
setup.py
etc.
```
for example see this [Python project howto](http://infini... | I generally create a "run tests" script in the project directory (the one that is common to both the source directory and `test`) that loads my "All Tests" suite. This is usually boilerplate code, so I can reuse it from project to project.
run\_tests.py:
```
import unittest
import test.all_tests
testSuite = test.all_... |
Running unittest with typical test directory structure | 1,896,918 | 286 | 2009-12-13T16:10:23Z | 24,266,885 | 225 | 2014-06-17T14:49:19Z | [
"python",
"unit-testing"
] | The very common directory structure for even a simple Python module seems to be to separate the unit tests into their own `test` directory:
```
new_project/
antigravity/
antigravity.py
test/
test_antigravity.py
setup.py
etc.
```
for example see this [Python project howto](http://infini... | The best solution in my opinion is to use the `unittest` [command line interface](https://docs.python.org/2/library/unittest.html#command-line-interface) which will add the directory to the `sys.path` so you don't have to (done in the `TestLoader` class).
For example for a directory structure like this:
```
new_proje... |
"unpacking" a passed dictionary into the function's name space in Python? | 1,897,623 | 19 | 2009-12-13T20:24:33Z | 1,897,657 | 7 | 2009-12-13T20:35:32Z | [
"python",
"function",
"dictionary",
"parameters"
] | In the work I do, I often have parameters that I need to group into subsets for convenience:
```
d1 = {'x':1,'y':2}
d2 = {'a':3,'b':4}
```
I do this by passing in multiple dictionaries. Most of the time I use the passed dictionary directly, i.e.:
```
def f(d1,d2):
for k in d1:
blah( d1[k] )
```
In some ... | If you like `d.variable` syntax better than `d['variable']`, you can wrap the dictionary in [an almost trivial "bunch" object](http://code.activestate.com/recipes/52308/) such as this:
```
class Bunch:
def __init__(self, **kw):
self.__dict__.update(kw)
```
It doesn't exactly bring dictionary contents into... |
"unpacking" a passed dictionary into the function's name space in Python? | 1,897,623 | 19 | 2009-12-13T20:24:33Z | 1,897,822 | 14 | 2009-12-13T21:28:36Z | [
"python",
"function",
"dictionary",
"parameters"
] | In the work I do, I often have parameters that I need to group into subsets for convenience:
```
d1 = {'x':1,'y':2}
d2 = {'a':3,'b':4}
```
I do this by passing in multiple dictionaries. Most of the time I use the passed dictionary directly, i.e.:
```
def f(d1,d2):
for k in d1:
blah( d1[k] )
```
In some ... | You can always pass a dictionary as an argument to a function. For instance,
```
dict = {'a':1, 'b':2}
def myFunc( a=0,b=0,c=0 ):
print a,b,c
myFunc(**dict)
``` |
"unpacking" a passed dictionary into the function's name space in Python? | 1,897,623 | 19 | 2009-12-13T20:24:33Z | 4,014,043 | 7 | 2010-10-25T11:20:16Z | [
"python",
"function",
"dictionary",
"parameters"
] | In the work I do, I often have parameters that I need to group into subsets for convenience:
```
d1 = {'x':1,'y':2}
d2 = {'a':3,'b':4}
```
I do this by passing in multiple dictionaries. Most of the time I use the passed dictionary directly, i.e.:
```
def f(d1,d2):
for k in d1:
blah( d1[k] )
```
In some ... | Assuming all keys in your dictionary qualify to be identifiers,
You can simply do this:
```
adict = { 'x' : 'I am x', 'y' : ' I am y' }
for key in adict.keys():
exec(key + " = adict['" + key + "']")
blah(x)
blah(y)
``` |
Test if point is in some rectangle | 1,897,779 | 10 | 2009-12-13T21:17:30Z | 1,897,789 | 8 | 2009-12-13T21:20:42Z | [
"python",
"algorithm",
"point"
] | I have a large collection of rectangles, all of the same size. I am generating random points that should not fall in these rectangles, so what I wish to do is test if the generated point lies in one of the rectangles, and if it does, generate a new point.
Using R-trees seem to work, but they are really meant for recta... | This Reddit thread addresses your problem:
[I have a set of rectangles, and need to determine whether a point is contained within any of them. What are some good data structures to do this, with fast lookup being important?](http://www.reddit.com/r/programming/comments/80dlc/i_have_a_set_of_rectangles_and_need_to_dete... |
Does anyone know of a asynchronous mysql lib for python? | 1,897,799 | 11 | 2009-12-13T21:23:32Z | 1,898,320 | 13 | 2009-12-14T00:15:05Z | [
"python",
"mysql",
"twisted",
"asynchronous",
"tornado"
] | I've been looking into non-blocking servers for python (tornado, twisted etc) but a lot of the benefits seems to be lost if there's no non-blocking connection to the database. Does anyone know if there are any projects that take care of this? (by non-blocking a la node.js)
Edit: Clarified my question | You can use Twisted's [ADBAPI](http://twistedmatrix.com/documents/8.2.0/api/twisted.enterprise.adbapi.html) to wrap a synchronous DBAPI implementation.
E.g.:
```
from twisted.internet import reactor
from twisted.enterprise import adbapi
def result(rows):
for row in rows:
print row
reactor.stop()
de... |
How do you you run a Twisted application via Python (instead of via Twisted)? | 1,897,939 | 19 | 2009-12-13T22:03:32Z | 1,898,102 | 15 | 2009-12-13T22:56:12Z | [
"python",
"networking",
"sockets",
"twisted"
] | I am working my way through learning Twisted, and have stumbled across something I'm not sure I'm terribly fond of - the "Twisted Command Prompt". I am fiddling around with Twisted on my Windows machine, and tried running the "Chat" example:
```
from twisted.protocols import basic
class MyChat(basic.LineReceiver):
... | Don't confuse "Twisted" with "`twistd`". When you use "`twistd`", you *are* running the program with Python. "`twistd`" is a Python program that, among other things, can load an application from a `.tac` file (as you're doing here).
The "Twisted Command Prompt" is a Twisted installer-provided convenience to help out p... |
How do you you run a Twisted application via Python (instead of via Twisted)? | 1,897,939 | 19 | 2009-12-13T22:03:32Z | 1,898,188 | 20 | 2009-12-13T23:25:31Z | [
"python",
"networking",
"sockets",
"twisted"
] | I am working my way through learning Twisted, and have stumbled across something I'm not sure I'm terribly fond of - the "Twisted Command Prompt". I am fiddling around with Twisted on my Windows machine, and tried running the "Chat" example:
```
from twisted.protocols import basic
class MyChat(basic.LineReceiver):
... | I don't know if it's the best way to do this but what I do is instead of:
```
application = service.Application("chatserver")
internet.TCPServer(1025, factory).setServiceParent(application)
```
you can do:
```
from twisted.internet import reactor
reactor.listenTCP(1025, factory)
reactor.run()
```
Sumarized if you w... |
How do I check the methods that an object has, in Python? | 1,897,960 | 5 | 2009-12-13T22:08:46Z | 1,897,967 | 20 | 2009-12-13T22:11:08Z | [
"python",
"object",
"methods"
] | For example, a list.
l1 = [1, 5 , 7]
How do I check the methods that it has?
(l1.append, for example)
Or a string...
string.lower( | You can use `dir` to get a list the methods of any object. This is very useful in the interactive prompt:
```
>>> dir(l1)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__',
'__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iad... |
python csv into dictionary | 1,898,305 | 9 | 2009-12-14T00:08:45Z | 1,898,324 | 12 | 2009-12-14T00:15:36Z | [
"python",
"csv"
] | I am pretty new to python. I need to create a class that loads csv data into a dictionary.
I want to be able to control the keys and value
So let say the following code, I can pull out worker1.name or worker1.age anytime i want.
```
class ageName(object):
'''class to represent a person'''
def __init__(self, name, age... | ```
import csv
reader = csv.reader(open('workers.csv', newline=''), delimiter=',', quotechar='"')
workers = [ageName(row[0], row[1]) for row in reader]
```
workers now has a list of all the workers
```
>>> workers[0].name
'jon'
```
**added edit after question was altered**
Is there any reason you're using old styl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.