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
How do you check if a widget has focus in Tkinter?
1,385,921
7
2009-09-06T15:25:17Z
1,385,933
11
2009-09-06T15:32:23Z
[ "python", "focus", "tkinter", "entry" ]
``` from Tkinter import * app = Tk() text_field = Entry(app) text_field.pack() app.mainloop() ``` I want to be able to check if `text_field` is currently selected or focused, so that I know whether or not to do something with its contents when the user presses enter.
If you want to do something when the user presses enter only if the focus is on the entry widget, simply add a binding to the entry widget. It will only fire if that widget has focus. For example: ``` >>> from Tkinter import * >>> root=Tk() >>> e1=Entry(root) >>> e1.pack() >>> e2=Entry(root) >>> e2.pack() >>> def hand...
maximum number combinations
1,385,929
3
2009-09-06T15:30:45Z
1,385,935
12
2009-09-06T15:34:42Z
[ "python", "combinations" ]
I am trying to generate a list of all possible number combinations within a set of four numbers using all numbers from 0 through 9. I'm getting close but the output doesn't show every possible combination starting from 0000 all the way to 9999. Any clues as to why the following code is dropping certain combinations? ...
If you have python 2.6, why not use [itertools.combinations](http://docs.python.org/library/itertools.html#itertools.combinations)? ``` from itertools import combinations combinations(range(10), 4) ```
PIL: Thumbnail and end up with a square image
1,386,352
41
2009-09-06T18:33:59Z
1,386,382
56
2009-09-06T18:45:01Z
[ "python", "png", "thumbnails", "python-imaging-library", "alpha" ]
Calling ``` image = Image.open(data) image.thumbnail((36,36), Image.NEAREST) ``` will maintain the aspect ratio. But I need to end up displaying the image like this: ``` <img src="/media/image.png" style="height:36px; width:36px" /> ``` Can I have a letterbox style with either transparent or white around the image?
Paste the image into a transparent image with the right size as a background ``` from PIL import Image size = (36, 36) image = Image.open(data) image.thumbnail(size, Image.ANTIALIAS) background = Image.new('RGBA', size, (255, 255, 255, 0)) background.paste( image, ((size[0] - image.size[0]) / 2, (size[1] - ima...
PIL: Thumbnail and end up with a square image
1,386,352
41
2009-09-06T18:33:59Z
8,469,920
96
2011-12-12T04:25:06Z
[ "python", "png", "thumbnails", "python-imaging-library", "alpha" ]
Calling ``` image = Image.open(data) image.thumbnail((36,36), Image.NEAREST) ``` will maintain the aspect ratio. But I need to end up displaying the image like this: ``` <img src="/media/image.png" style="height:36px; width:36px" /> ``` Can I have a letterbox style with either transparent or white around the image?
PIL already already has a function to do exactly that ``` from PIL import Image, ImageOps thumb = ImageOps.fit(image, size, Image.ANTIALIAS) ```
PIL: Image resizing : Algorithm similar to firefox's
1,386,400
8
2009-09-06T18:58:37Z
1,386,756
8
2009-09-06T21:21:59Z
[ "python", "image", "thumbnails", "python-imaging-library" ]
I'm getting about the same *bad looking* resizing from all the 4 algorithms of PIL ``` >>> data = utils.fetch("http://wavestock.com/images/beta-icon.gif") >>> image = Image.open(StringIO.StringIO(data)); image.save("/home/ptarjan/www/tmp/metaward/original.png") >>> >>> image = Image.open(StringIO.StringIO(data)); imag...
I resized the "original" with Python and found the same results as you did. I also resized the "original" with GIMP and I got the same (if not inferior) quality. This made me suspect that Firefox cheats. Possibly it converts to RGB ("original" mode is indexed color). Thus the following code: ``` import Image im=Image....
Handling big numbers in code
1,386,604
7
2009-09-06T20:13:19Z
1,386,629
7
2009-09-06T20:22:55Z
[ "python", "algorithm" ]
I'm working on a programming problem where I need to handle a number involving 100000 digits. Can python handle numbers like this?
Yes; Python 2.x has two types of integers, **int** of limited size and **long** of **unlimited size**. However all calculations will automatically convert to long if needed. Handling big numbers works fine, but one of the slower things will be if you try to print the 100000 digits to output, or even try to create a str...
Handling big numbers in code
1,386,604
7
2009-09-06T20:13:19Z
1,386,735
22
2009-09-06T21:12:35Z
[ "python", "algorithm" ]
I'm working on a programming problem where I need to handle a number involving 100000 digits. Can python handle numbers like this?
As other answers indicated, Python does support integer numbers bounded only by the amount of memory available. If you want even faster support for them, try [gmpy](http://code.google.com/p/gmpy/) (as gmpy's author and current co-maintainer I'm of course a little biased here;-): ``` $ python -mtimeit -s'import gmpy; x...
Convert binary string to list of integers using Python
1,386,811
5
2009-09-06T21:46:52Z
1,386,828
11
2009-09-06T21:51:21Z
[ "python" ]
I am new to Python. Here's what I am trying to do: 1. Slice a long binary string into 3 digit-long chunks. 2. Store each "chunk" into a list called row. 3. Convert each binary chunk into a number (0-7). 4. Store the converted list of numbers into a new list called numbers. Here is what I have so far: ``` def travers...
Something like this should do it: ``` s = "110101001" numbers = [int(s[i:i+3], 2) for i in range(0, len(s), 3)] print numbers ``` The output is: ``` [6, 5, 1] ``` Breaking this down step by step, first: ``` >>> range(0, len(s), 3) [0, 3, 6] ``` The [`range()`](http://docs.python.org/library/functions.html#range) ...
Convert binary string to list of integers using Python
1,386,811
5
2009-09-06T21:46:52Z
1,386,836
7
2009-09-06T21:55:15Z
[ "python" ]
I am new to Python. Here's what I am trying to do: 1. Slice a long binary string into 3 digit-long chunks. 2. Store each "chunk" into a list called row. 3. Convert each binary chunk into a number (0-7). 4. Store the converted list of numbers into a new list called numbers. Here is what I have so far: ``` def travers...
I'll assume that by "binary string" you actually mean a normal string (i.e. text) whose items are all '0' or '1'. So for points 1 and 2, ``` row = [thestring[i:i+3] for i in xrange(0, len(thestring), 3)] ``` of course the last item will be only 1 or 2 characters long if `len(thestring)` is not an exact multiple of 3...
Django : select_related with ManyToManyField
1,387,044
13
2009-09-06T23:52:55Z
9,431,210
18
2012-02-24T13:00:05Z
[ "python", "django", "django-models", "django-select-related" ]
I have : ``` class Award(models.Model) : name = models.CharField(max_length=100, db_index=True) class Alias(models.Model) : awards = models.ManyToManyField('Award', through='Achiever') class Achiever(models.Model): award = models.ForeignKey(Award) alias = models.ForeignKey(Alias) count = models.I...
Django versions 1.4 and above have [`prefetch_related`](https://docs.djangoproject.com/en/1.4/ref/models/querysets/#prefetch-related) for this purpose. The [`prefetch_related`](https://docs.djangoproject.com/en/1.4/ref/models/querysets/#prefetch-related) method is similar to [`select_related`](https://docs.djangoproje...
Reliably detect Windows in Python
1,387,222
30
2009-09-07T01:29:16Z
1,387,224
8
2009-09-07T01:31:03Z
[ "python", "windows", "platform-detection" ]
I'm working on a couple of Linux tools and need to prevent installation on Windows, since it depends on FHS and is thus rendered useless on that platform. The `platform.platform` function comes close but only returns a string. Unfortunately I don't know what to search for in that string for it to yield a reliable resu...
Try this: ``` import platform if platform.system() == "Darwin": # Don't have Windows handy, but I'd expect "Win32" or "Windows" for it ``` **Edit:** Just saw that you tried `platform.platform()`...`platform.system()` will work better for this case. Trust me, use it. Dark corners lie in platform detection. `dist...
Reliably detect Windows in Python
1,387,222
30
2009-09-07T01:29:16Z
1,387,226
17
2009-09-07T01:32:49Z
[ "python", "windows", "platform-detection" ]
I'm working on a couple of Linux tools and need to prevent installation on Windows, since it depends on FHS and is thus rendered useless on that platform. The `platform.platform` function comes close but only returns a string. Unfortunately I don't know what to search for in that string for it to yield a reliable resu...
On my Windows box, `platform.system()` returns `'Windows'`. However, I'm not sure why you'd bother. If you want to limit the platform it runs on technologically, I'd use a white-list rather than a black-list. In fact, I wouldn't do it technologically at all since perhaps the next release of Python may have `Win32/Win...
Reliably detect Windows in Python
1,387,222
30
2009-09-07T01:29:16Z
1,387,228
47
2009-09-07T01:33:31Z
[ "python", "windows", "platform-detection" ]
I'm working on a couple of Linux tools and need to prevent installation on Windows, since it depends on FHS and is thus rendered useless on that platform. The `platform.platform` function comes close but only returns a string. Unfortunately I don't know what to search for in that string for it to yield a reliable resu...
``` >>> import platform >>> platform.system() 'Windows' ```
Reliably detect Windows in Python
1,387,222
30
2009-09-07T01:29:16Z
7,637,706
36
2011-10-03T16:18:44Z
[ "python", "windows", "platform-detection" ]
I'm working on a couple of Linux tools and need to prevent installation on Windows, since it depends on FHS and is thus rendered useless on that platform. The `platform.platform` function comes close but only returns a string. Unfortunately I don't know what to search for in that string for it to yield a reliable resu...
For those that came here looking for a way to detect Cygwin from Python (as opposed to just detecting Windows), here are some example return values from `os.name` and `platform.system` on different platforms ``` OS/build | os.name | platform.system() -------------+---------+----------------------- Win32 native | ...
MySQL INSERT data does not get stored in proper db, only temporary?
1,387,573
2
2009-09-07T04:37:21Z
1,387,579
8
2009-09-07T04:40:32Z
[ "python", "mysql" ]
I'm having trouble with MySQL or Python and can't seem to isolate the problem. `INSERT`s only seem to last the run of the script and are not stored in the database. I have this script: ``` import MySQLdb db = MySQLdb.connect(host="localhost", user="user", passwd="password", db="example") dbcursor = db.cursor() dbcur...
You are not committing the transaction. ``` conn = MySQLdb.connect (host = "localhost", user = "testuser", passwd = "testpass", db = "test") cursor = conn.cursor() cursor.execute(...) conn.commit() ``` [Reference](http://www.kitebird.com/article...
C++ with Python embedding: crash if Python not installed
1,387,906
14
2009-09-07T06:56:51Z
1,387,977
18
2009-09-07T07:16:51Z
[ "c++", "python", "dll", "embed", "distribution" ]
I'm developing on Windows, and I've searched everywhere without finding anyone talking about this kind of thing. I made a C++ app on my desktop that embedded Python 3.1 using MSVC. I linked python31.lib and included python31.dll in the app's run folder alongside the executable. It works great. My extension and embeddi...
In addition to pythonxy.dll, you also need the entire Python library, i.e. the contents of the lib folder, plus the extension modules, i.e. the contents of the DLLs folder. Without the standard library, Python won't even start, since it tries to find os.py (in 3.x; string.py in 2.x). On startup, it imports a number of ...
C++ with Python embedding: crash if Python not installed
1,387,906
14
2009-09-07T06:56:51Z
2,970,407
10
2010-06-03T23:02:34Z
[ "c++", "python", "dll", "embed", "distribution" ]
I'm developing on Windows, and I've searched everywhere without finding anyone talking about this kind of thing. I made a C++ app on my desktop that embedded Python 3.1 using MSVC. I linked python31.lib and included python31.dll in the app's run folder alongside the executable. It works great. My extension and embeddi...
Nice. And if you do not want to zip, copy Python26\DLLs & Python26\lib to your exe directory as: ``` .\myexe.exe .\python26.dll .\Python26\DLLs .\Python26\lib ``` And then set PYTHONHOME with Py\_SetPythonHome() API. Apparently, this API is not in the list of "allowed" calls **before** Py\_Initialize(); Below...
How to get output from subprocess.Popen()
1,388,753
26
2009-09-07T10:50:52Z
1,388,807
29
2009-09-07T11:04:18Z
[ "python", "linux", "subprocess", "popen" ]
I want output from execute Test\_Pipe.py, I tried following code on Linux but it did not work. **Test\_Pipe.py** ``` import time while True : print "Someting ..." time.sleep(.1) ``` **Caller.py** ``` import subprocess as subp import time proc = subp.Popen(["python", "Test_Pipe.py"], stdout=subp.PIPE, stdin...
You obviously can use subprocess.communicate but I think you are looking for real time input and output. readline was blocked because the process is probably waiting on your input. You can read character by character to overcome this like the following: ``` import subprocess import sys process = subprocess.Popen( ...
How to get output from subprocess.Popen()
1,388,753
26
2009-09-07T10:50:52Z
1,390,035
11
2009-09-07T16:10:41Z
[ "python", "linux", "subprocess", "popen" ]
I want output from execute Test\_Pipe.py, I tried following code on Linux but it did not work. **Test\_Pipe.py** ``` import time while True : print "Someting ..." time.sleep(.1) ``` **Caller.py** ``` import subprocess as subp import time proc = subp.Popen(["python", "Test_Pipe.py"], stdout=subp.PIPE, stdin...
To avoid the many problems that can always arise with buffering for tasks such as "getting the subprocess's output to the main process in real time", I always recommend using [pexpect](http://sourceforge.net/projects/pexpect/) for all non-Windows platform, [wexpect](http://sage.math.washington.edu/home/goreckc/sage/wex...
How to get output from subprocess.Popen()
1,388,753
26
2009-09-07T10:50:52Z
3,536,709
17
2010-08-21T07:03:19Z
[ "python", "linux", "subprocess", "popen" ]
I want output from execute Test\_Pipe.py, I tried following code on Linux but it did not work. **Test\_Pipe.py** ``` import time while True : print "Someting ..." time.sleep(.1) ``` **Caller.py** ``` import subprocess as subp import time proc = subp.Popen(["python", "Test_Pipe.py"], stdout=subp.PIPE, stdin...
Nadia's snippet does work but calling read with a 1 byte buffer is highly unrecommended. The better way to do this would be to set the stdout file descriptor to nonblocking using fcntl ``` fcntl.fcntl( proc.stdout.fileno(), fcntl.F_SETFL, fcntl.fcntl(proc.stdout.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK, ) ...
How can I compare two lists in python and return matches
1,388,818
168
2009-09-07T11:07:27Z
1,388,836
210
2009-09-07T11:10:46Z
[ "python", "list" ]
I want to take two lists and find the values that appear in both. ``` a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] returnMatches(a, b) ``` would return `[5]`, for instance.
Not the most efficient one, but by far the most obvious way to do it is: ``` >>> a = [1, 2, 3, 4, 5] >>> b = [9, 8, 7, 6, 5] >>> set(a) & set(b) {5} ``` if order is significant you can do it with list comprehensions like this: ``` >>> [i for i, j in zip(a, b) if i == j] [5] ``` (only works for equal-sized lists, wh...
How can I compare two lists in python and return matches
1,388,818
168
2009-09-07T11:07:27Z
1,388,837
9
2009-09-07T11:10:53Z
[ "python", "list" ]
I want to take two lists and find the values that appear in both. ``` a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] returnMatches(a, b) ``` would return `[5]`, for instance.
The easiest way to do that is to use [sets](http://docs.python.org/library/stdtypes.html#set-types-set-frozenset): ``` >>> a = [1, 2, 3, 4, 5] >>> b = [9, 8, 7, 6, 5] >>> set(a) & set(b) set([5]) ```
How can I compare two lists in python and return matches
1,388,818
168
2009-09-07T11:07:27Z
1,388,842
190
2009-09-07T11:11:36Z
[ "python", "list" ]
I want to take two lists and find the values that appear in both. ``` a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] returnMatches(a, b) ``` would return `[5]`, for instance.
Use [set.intersection()](http://docs.python.org/library/stdtypes.html#set.intersection), it's fast and readable. ``` >>> set(a).intersection(b) set([5]) ```
How can I compare two lists in python and return matches
1,388,818
168
2009-09-07T11:07:27Z
1,388,848
8
2009-09-07T11:12:28Z
[ "python", "list" ]
I want to take two lists and find the values that appear in both. ``` a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] returnMatches(a, b) ``` would return `[5]`, for instance.
Quick way: ``` list(set(a).intersection(set(b))) ```
How can I compare two lists in python and return matches
1,388,818
168
2009-09-07T11:07:27Z
3,056,197
7
2010-06-16T18:41:45Z
[ "python", "list" ]
I want to take two lists and find the values that appear in both. ``` a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] returnMatches(a, b) ``` would return `[5]`, for instance.
``` >>> s = ['a','b','c'] >>> f = ['a','b','d','c'] >>> ss= set(s) >>> fs =set(f) >>> print ss.intersection(fs) **set(['a', 'c', 'b'])** >>> print ss.union(fs) **set(['a', 'c', 'b', 'd'])** >>> print ss.union(fs) - ss.intersection(fs) **set(['d'])** ```
How can I compare two lists in python and return matches
1,388,818
168
2009-09-07T11:07:27Z
3,834,580
30
2010-09-30T20:28:23Z
[ "python", "list" ]
I want to take two lists and find the values that appear in both. ``` a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] returnMatches(a, b) ``` would return `[5]`, for instance.
I prefer the set based answers, but here's one that works anyway ``` [x for x in a if x in b] ```
How can I compare two lists in python and return matches
1,388,818
168
2009-09-07T11:07:27Z
10,872,313
51
2012-06-03T17:12:23Z
[ "python", "list" ]
I want to take two lists and find the values that appear in both. ``` a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] returnMatches(a, b) ``` would return `[5]`, for instance.
A quick performance test showing Lutz's solution is the best: ``` import time def speed_test(func): def wrapper(*args, **kwargs): t1 = time.time() for x in xrange(5000): results = func(*args, **kwargs) t2 = time.time() print '%s took %0.3f ms' % (func.func_name, (t2-t1)...
how do I determine whether a python script is imported as module or run as script?
1,389,044
13
2009-09-07T11:58:18Z
1,389,048
24
2009-09-07T11:59:19Z
[ "python", "module" ]
The question is rather straightforward but not answered by searching. How do I determine in a python script whether this script is imported as a module or run as a script? Is there a difference at all in python? The problem is, that I want to evaluate the command line parameters only if run as a script, but not if the...
from python [docs](http://docs.python.org/dev/tutorial/modules.html#executing-modules-as-scripts): > When you run a Python module with > > python fibo.py > > the code in the module will be > executed, just as if you imported it, > but with the `__name__` set to > `"__main__"`. That means that by adding > this code at ...
how to add json library
1,389,141
9
2009-09-07T12:19:02Z
1,389,269
12
2009-09-07T12:47:24Z
[ "python", "json", "osx", "python-2.5" ]
i am new to python, on my Mac, when i issue command ``` User:ihasfriendz user$ python main.py Traceback (most recent call last): File "main.py", line 2, in <module> import json ImportError: No module named json ``` I get error on json. how to add this library? i'm using 2.5 (the default came with leopard)
You can also install simplejson. If you have pip (see <https://pypi.python.org/pypi/pip>) as your Python package manager you can install simplejson with: ``` pip install simplejson ``` This is similar to the comment of installing with easy\_install, but I prefer pip to easy\_install as you can easily uninstall in p...
Python: Automatically initialize instance variables?
1,389,180
35
2009-09-07T12:28:28Z
1,389,202
11
2009-09-07T12:34:37Z
[ "python", "class", "initialization-list" ]
I have a python class that looks like this: ``` class Process: def __init__(self, PID, PPID, cmd, FDs, reachable, user): ``` followed by: ``` self.PID=PID self.PPID=PPID self.cmd=cmd ... ``` Is there any way to autoinitialize these instance variables, like C++'s initialization li...
You could do it easily with the keyword arguments, e.g. like this: ``` >>> class D: def __init__(self, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) >>> D(test='d').test 'd' ``` similar implementation for the positional arguments would be: ``` >> class C: def __init__(self, *args): ...
Python: Automatically initialize instance variables?
1,389,180
35
2009-09-07T12:28:28Z
1,389,216
56
2009-09-07T12:37:39Z
[ "python", "class", "initialization-list" ]
I have a python class that looks like this: ``` class Process: def __init__(self, PID, PPID, cmd, FDs, reachable, user): ``` followed by: ``` self.PID=PID self.PPID=PPID self.cmd=cmd ... ``` Is there any way to autoinitialize these instance variables, like C++'s initialization li...
**Edit: extended the solution to honor default arguments also** Here is the complete solution: ``` from functools import wraps import inspect def initializer(func): """ Automatically assigns the parameters. >>> class process: ... @initializer ... def __init__(self, cmd, reachable=False,...
Python: Automatically initialize instance variables?
1,389,180
35
2009-09-07T12:28:28Z
1,389,224
21
2009-09-07T12:38:59Z
[ "python", "class", "initialization-list" ]
I have a python class that looks like this: ``` class Process: def __init__(self, PID, PPID, cmd, FDs, reachable, user): ``` followed by: ``` self.PID=PID self.PPID=PPID self.cmd=cmd ... ``` Is there any way to autoinitialize these instance variables, like C++'s initialization li...
Quoting the [Zen of Python](http://www.python.org/dev/peps/pep-0020/), > Explicit is better than implicit.
Python: Automatically initialize instance variables?
1,389,180
35
2009-09-07T12:28:28Z
1,389,232
25
2009-09-07T12:40:02Z
[ "python", "class", "initialization-list" ]
I have a python class that looks like this: ``` class Process: def __init__(self, PID, PPID, cmd, FDs, reachable, user): ``` followed by: ``` self.PID=PID self.PPID=PPID self.cmd=cmd ... ``` Is there any way to autoinitialize these instance variables, like C++'s initialization li...
If you're using Python 2.6 or higher, you can use [collections.namedtuple](http://docs.python.org/library/collections.html#collections.namedtuple): ``` >>> from collections import namedtuple >>> Process = namedtuple('Process', 'PID PPID cmd') >>> proc = Process(1, 2, 3) >>> proc.PID 1 >>> proc.PPID 2 ``` This is appr...
Python: Automatically initialize instance variables?
1,389,180
35
2009-09-07T12:28:28Z
1,389,304
12
2009-09-07T12:54:44Z
[ "python", "class", "initialization-list" ]
I have a python class that looks like this: ``` class Process: def __init__(self, PID, PPID, cmd, FDs, reachable, user): ``` followed by: ``` self.PID=PID self.PPID=PPID self.cmd=cmd ... ``` Is there any way to autoinitialize these instance variables, like C++'s initialization li...
Another thing you can do: ``` class X(object): def __init__(self, a,b,c,d): vars = locals() # dict of local names self.__dict__.update(vars) # __dict__ holds and object's attributes del self.__dict__["self"] # don't need `self` ``` But the only solution I would recommend, besides just spel...
How to save data with Python?
1,389,738
12
2009-09-07T14:49:22Z
1,389,792
21
2009-09-07T15:00:30Z
[ "python", "data-structures", "save" ]
I am working on a program in Python and want users to be able to save data they are working on. I have looked into cPickle; it seems like it would be a fast and easy way to save data, it seems insecure. Since entire functions, classes, etc can be pickled, I am worried that a rogue save file could inject harmful code in...
From your description JSON encoding is the secure and fast solution. There is a json module in python2.6, you can use it like this: ``` import json obj = {'key1': 'value1', 'key2': [1, 2, 3, 4], 'key3': 1322} encoded = json.dumps(obj) obj = json.loads(encoded) ``` JSON format is human readable and is very similar to ...
How to run django shell from Emacs?
1,389,835
9
2009-09-07T15:16:28Z
1,392,730
8
2009-09-08T08:33:27Z
[ "python", "django", "emacs", "ipython" ]
I'd like to be able to run `./manage.py shell` in an Emacs buffer, with all the nice stuff that you get from ipython, like magic commands and autocompletion. Ideally I would also like to be able evaluate code from a buffer to the django shell. Is this possible?
OK, so I hacked this by myself today. A major part of it is copy-and-paste from `py-shell` from `python-mode.el`. ``` (defun django-shell (&optional argprompt) (interactive "P") ;; Set the default shell if not already set (labels ((read-django-project-dir (prompt dir) (let* ((dir (read-directory-name pr...
Removing redundant symbols from string
1,390,657
2
2009-09-07T19:14:06Z
1,390,666
9
2009-09-07T19:17:02Z
[ "python", "floating-point" ]
Let's say I have a string like that: `'12,423,343.93'`. How to convert it to `float` in simple, effective and yet elegant way? It seems I need to remove redundant commas from the string and then call `float()`, but I have no good solution for that. Thanks
``` s = "12,423,343.93" f = float(s.replace(",", "")) ```
Google App Engine - Request class query_string
1,391,026
6
2009-09-07T21:31:07Z
1,391,032
17
2009-09-07T21:34:38Z
[ "python", "google-app-engine" ]
In Python and GAE, I would like to ask how to get the parameters of a query string in the url. As I know, the query\_string part returns all the part after the "?" in the url. So what I have to do is to split the query string with "&", and use the variables. Is there any other convinient way to manage the query string?...
You don't need to complicate. You can retrieve all GET parameters with: ``` self.request.get('var_name') ``` Or if you want to retrieve them all in one list you can use: ``` self.request.get_all() ``` You can find more info on the Request class [here](http://code.google.com/appengine/docs/python/tools/webapp/reques...
function decorators in c#
1,391,157
21
2009-09-07T22:19:37Z
1,391,176
8
2009-09-07T22:26:29Z
[ "c#", "python", "reflection", "decorator" ]
Is there a C# analog for Python's function decorators? It feels like it's doable with attributes and the reflection framework, but I don't see a way to replace functions at runtime. [Python decorators](http://www.artima.com/weblogs/viewpost.jsp?thread=240808) generally work this way: ``` class decorator(obj): def...
You can do that using [Post Sharp](http://www.postsharp.org/). Check out the demo video for instructions.
function decorators in c#
1,391,157
21
2009-09-07T22:19:37Z
1,391,202
12
2009-09-07T22:37:40Z
[ "c#", "python", "reflection", "decorator" ]
Is there a C# analog for Python's function decorators? It feels like it's doable with attributes and the reflection framework, but I don't see a way to replace functions at runtime. [Python decorators](http://www.artima.com/weblogs/viewpost.jsp?thread=240808) generally work this way: ``` class decorator(obj): def...
The way I achieve this is through [AOP frameworks](http://en.wikipedia.org/wiki/Aspect-oriented%5Fprogramming) like [Castle Dynamic Proxy](http://www.castleproject.org/dynamicproxy/index.html), [Spring.NET](http://www.springframework.net/doc/reference/html/aop-quickstart.html) or even the [Policy Injection Application ...
similar function to php's str_replace in python?
1,391,429
2
2009-09-08T00:37:49Z
1,391,466
11
2009-09-08T00:48:01Z
[ "python" ]
is there a similar function in python that takes search(array) and replace(array) as a parameter? Then takes a value from each array and uses them to do search and replace on subject(string). I know I can achieve this using for loops, but just looking more elegant way.
I believe the answer is no. I would specify your search/replace strings in a list, and the iterate over it: ``` edits = [(search0, replace0), (search1, replace1), (search2, replace2)] # etc. for search, replace in edits: s = s.replace(search, replace) ``` Even if python did have a `str_replace`-style function, I...
Python web scraping involving HTML tags with attributes
1,391,657
6
2009-09-08T02:23:25Z
1,391,752
10
2009-09-08T03:01:06Z
[ "python", "beautifulsoup", "lxml", "screen-scraping" ]
I'm trying to make a web scraper that will parse a web-page of publications and extract the authors. The skeletal structure of the web-page is the following: ``` <html> <body> <div id="container"> <div id="contents"> <table> <tbody> <tr> <td class="author">####I want whatever is located here ###</td> </tr> </tbody> </...
It's not clear to me from your question why you need to worry about the `div` tags -- what about doing just: ``` soup = BeautifulSoup(html) thetd = soup.find('td', attrs={'class': 'author'}) print thetd.string ``` On the HTML you give, running this emits exactly: ``` ####I want whatever is located here ### ``` whic...
Advantages of UserDict class in Python
1,392,396
9
2009-09-08T07:00:17Z
1,394,572
25
2009-09-08T15:11:39Z
[ "python", "oop" ]
What are advantages of using **UserDict** class? I mean, what I really get if instead of ``` class MyClass(object): def __init__(self): self.a = 0 self.b = 0 ... m = MyClass() m.a = 5 m.b = 7 ``` I will write the following: ``` class MyClass(UserDict): def __init__(self): UserDict.__...
[`UserDict.UserDict` has no substantial added value since Python 2.2, since, as @gs mention, you can now subclass `dict` directly -- it exists only for backwards compatibility with Python 2.1 and earlier, when builtin types could not be subclasses. Still, it was kept in Python 3 (now in its proper place in the `collect...
Calculating a directory size using Python?
1,392,413
78
2009-09-08T07:06:42Z
1,392,549
104
2009-09-08T07:48:15Z
[ "python", "directory" ]
Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.
This grabs subdirectories: ``` import os def get_size(start_path = '.'): total_size = 0 for dirpath, dirnames, filenames in os.walk(start_path): for f in filenames: fp = os.path.join(dirpath, f) total_size += os.path.getsize(fp) return total_size print get_size() ``` And a...
Calculating a directory size using Python?
1,392,413
78
2009-09-08T07:06:42Z
4,368,431
13
2010-12-06T16:12:22Z
[ "python", "directory" ]
Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.
Here is a recursive function (it recursively sums up the size of all subfolders and their respective files) which returns exactly the same bytes as when running "du -sb ." in linux (where the "." means "the current folder"): ``` import os def getFolderSize(folder): total_size = os.path.getsize(folder) for ite...
Calculating a directory size using Python?
1,392,413
78
2009-09-08T07:06:42Z
25,574,638
13
2014-08-29T19:00:48Z
[ "python", "directory" ]
Before i re-invent this particular wheel, has anybody got a nice routine for calculating the size of a directory using Python? It would be very nice if the routine would format the size nicely in Mb/Gb etc.
Some of the approaches suggested so far implement a recursion, others employ a shell or will not produce neatly formatted results. When your code is one-off for Linux platforms, you can get formatting as usual, recursion included, as a one-liner. Except for the `print` in the last line, it will work for current version...
Python: Why is ("hello" is "hello")?
1,392,433
48
2009-09-08T07:13:19Z
1,392,440
76
2009-09-08T07:15:09Z
[ "python", "identity" ]
Why is `"hello" is "hello" == True` in Python? I read the following [here](http://zetcode.com/tutorials/pythontutorial/keywords/): > If two string literals are equal, they have been put to same > memory location. A string is an immutable entity. No harm can > be done. So there is one and only one place in memory for...
Python (like Java, C, C++, .NET) uses string pooling / interning. The interpreter realises that "hello" is the same as "hello", so it optimizes and uses the same location in memory. Another goodie: "hell" + "o" is "hello" ==> True
Python: Why is ("hello" is "hello")?
1,392,433
48
2009-09-08T07:13:19Z
1,392,449
12
2009-09-08T07:16:34Z
[ "python", "identity" ]
Why is `"hello" is "hello" == True` in Python? I read the following [here](http://zetcode.com/tutorials/pythontutorial/keywords/): > If two string literals are equal, they have been put to same > memory location. A string is an immutable entity. No harm can > be done. So there is one and only one place in memory for...
Literal strings are probably grouped based on their hash or something similar. Two of the same literal strings will be stored in the same memory, and any references both refer to that. ``` Memory Code ------- | myLine = "hello" | / |hello < | \ | myLine = "hello" ------- ```
Python: Why is ("hello" is "hello")?
1,392,433
48
2009-09-08T07:13:19Z
1,392,927
55
2009-09-08T09:19:59Z
[ "python", "identity" ]
Why is `"hello" is "hello" == True` in Python? I read the following [here](http://zetcode.com/tutorials/pythontutorial/keywords/): > If two string literals are equal, they have been put to same > memory location. A string is an immutable entity. No harm can > be done. So there is one and only one place in memory for...
> So there is one and only one place in memory for every Python string? No, only ones the interpreter has decided to optimise, which is a decision based on a policy that isn't part of the language specification and which may change in different CPython versions. eg. on my install (2.6.2 Linux): ``` >>> 'X'*10 is 'X'...
Django template, how to make a dropdown box with the predefined value selected?
1,392,706
4
2009-09-08T08:27:48Z
1,392,747
9
2009-09-08T08:40:05Z
[ "python", "django", "django-templates" ]
I am trying to create a drop down list box with the selected value equal to a value passed from the template values, but with no success. Can anyone take a look and show me what I am doing wrong. ``` <select name="movie"> {% for movie in movies %} {% ifequal movie.id selected_movie.id %} <option v...
Your code works for me with django 1.0.2 and firefox 3.5. You can use {% else %} instead of {% ifnotequal %} and set selected="selected". Hope it helps. ``` <select name="movie"> {% for movie in movies %} {% ifequal movie.id selected_movie.id %} <option value="{{movie.key}}" selected="selected...
Problem with subprocess.call
1,392,757
11
2009-09-08T08:42:10Z
1,392,905
7
2009-09-08T09:16:02Z
[ "python", "subprocess" ]
In my current working directory I have the dir ROOT/ with some files inside. I know I can exec `cp -r ROOT/* /dst` and I have no problems. But if I open my Python console and I write this: ``` import subprocess subprocess.call(['cp', '-r', 'ROOT/*', '/dst']) ``` It doesn't work! I have this error: `cp: cannot stat...
Try ``` subprocess.call('cp -r ROOT/* /dst', shell=True) ``` Note the use of a single string rather than an array here. Or build up your own implementation with [listdir](http://docs.python.org/library/os.html#os.listdir) and [copy](http://docs.python.org/library/shutil.html#shutil.copy)
Problem with subprocess.call
1,392,757
11
2009-09-08T08:42:10Z
5,040,567
9
2011-02-18T11:10:52Z
[ "python", "subprocess" ]
In my current working directory I have the dir ROOT/ with some files inside. I know I can exec `cp -r ROOT/* /dst` and I have no problems. But if I open my Python console and I write this: ``` import subprocess subprocess.call(['cp', '-r', 'ROOT/*', '/dst']) ``` It doesn't work! I have this error: `cp: cannot stat...
Just came across this while trying to do something similar. > The \* will not be expanded to filenames Exactly. If you look at the man page of `cp` you can call it with any number of source arguments and you can easily change the order of the arguments with the `-t` switch. ``` import glob import subprocess subproce...
Django: add image in an ImageField from image url
1,393,202
65
2009-09-08T10:29:43Z
1,393,316
22
2009-09-08T10:54:40Z
[ "python", "django", "urllib", "django-models" ]
please excuse me for my ugly english ;-) Imagine this very simple model : ``` class Photo(models.Model): image = models.ImageField('Label', upload_to='path/') ``` I would like to create a Photo from an image URL (i.e., not by hand in the django admin site). I think that I need to do something like this : ``` f...
``` from myapp.models import Photo import urllib from urlparse import urlparse from django.core.files import File img_url = 'http://www.site.com/image.jpg' photo = Photo() # set any other fields, but don't commit to DB (ie. don't save()) name = urlparse(img_url).path.split('/')[-1] content = urllib.urlretrieve(img...
Django: add image in an ImageField from image url
1,393,202
65
2009-09-08T10:29:43Z
2,141,823
80
2010-01-26T18:59:14Z
[ "python", "django", "urllib", "django-models" ]
please excuse me for my ugly english ;-) Imagine this very simple model : ``` class Photo(models.Model): image = models.ImageField('Label', upload_to='path/') ``` I would like to create a Photo from an image URL (i.e., not by hand in the django admin site). I think that I need to do something like this : ``` f...
I just created <http://www.djangosnippets.org/snippets/1890/> for this same problem. The code is similar to pithyless' answer above except it uses urllib2.urlopen because urllib.urlretrieve doesn't perform any error handling by default so it's easy to get the contents of a 404/500 page instead of what you needed. You c...
In Python, given a URL to a text file, what is the simplest way to read the contents of the text file?
1,393,324
44
2009-09-08T10:56:08Z
1,393,355
10
2009-09-08T11:02:09Z
[ "python" ]
In Python, when given the URL for a text file, what is the simplest way to access the contents off the text file and print the contents of the file out locally line-by-line without saving a local copy of the text file? ``` TargetURL=http://www.myhost.com/SomeFile.txt #read the file #print first line #print second line...
``` import urllib2 for line in urllib2.urlopen("http://www.myhost.com/SomeFile.txt"): print line ```
In Python, given a URL to a text file, what is the simplest way to read the contents of the text file?
1,393,324
44
2009-09-08T10:56:08Z
1,393,367
60
2009-09-08T11:04:28Z
[ "python" ]
In Python, when given the URL for a text file, what is the simplest way to access the contents off the text file and print the contents of the file out locally line-by-line without saving a local copy of the text file? ``` TargetURL=http://www.myhost.com/SomeFile.txt #read the file #print first line #print second line...
Actually the simplest way is : ``` import urllib2 # the lib that handles the url stuff data = urllib2.urlopen(target_url) # it's a file like object and works just like a file for line in data: # files are iterable print line ``` You don't even need "readlines", as Will suggested. You could even shorten it to `...
In Python, given a URL to a text file, what is the simplest way to read the contents of the text file?
1,393,324
44
2009-09-08T10:56:08Z
1,396,288
16
2009-09-08T20:55:15Z
[ "python" ]
In Python, when given the URL for a text file, what is the simplest way to access the contents off the text file and print the contents of the file out locally line-by-line without saving a local copy of the text file? ``` TargetURL=http://www.myhost.com/SomeFile.txt #read the file #print first line #print second line...
There's really no need to read line-by-line. You can get the whole thing like this: ``` import urllib txt = urllib.urlopen(target_url).read() ```
In Python, what is the best way to execute a local Linux command stored in a string?
1,394,198
6
2009-09-08T14:00:48Z
1,394,253
13
2009-09-08T14:10:02Z
[ "python" ]
In Python, what is the simplest way to execute a local Linux command stored in a string while catching any potential exceptions that are thrown and logging the output of the Linux command and any caught errors to a common log file? ``` String logfile = “/dev/log” String cmd = “ls” #try #execute cmd sending o...
Using the [subprocess](http://docs.python.org/library/subprocess.html#subprocess.Popen) module is the correct way to do it: ``` import subprocess logfile = open("/dev/log", "w") output, error = subprocess.Popen( ["ls"], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate...
python: combine sort-key-functions itemgetter and str.lower
1,394,475
5
2009-09-08T14:56:24Z
1,394,530
11
2009-09-08T15:06:47Z
[ "python", "function", "sorting", "key" ]
I want to sort a list of dictionaries by dictionary key, where I don't want to distinguish between upper and lower case characters. ``` dict1 = {'name':'peter','phone':'12355'} dict2 = {'name':'Paul','phone':'545435'} dict3 = {'name':'klaus','phone':'55345'} dict4 = {'name':'Krishna','phone':'12345'} dict5 = {'name':'...
How about this: ``` list_of_dicts.sort(key=lambda a: a['name'].lower()) ```
python: combine sort-key-functions itemgetter and str.lower
1,394,475
5
2009-09-08T14:56:24Z
1,394,609
9
2009-09-08T15:19:54Z
[ "python", "function", "sorting", "key" ]
I want to sort a list of dictionaries by dictionary key, where I don't want to distinguish between upper and lower case characters. ``` dict1 = {'name':'peter','phone':'12355'} dict2 = {'name':'Paul','phone':'545435'} dict3 = {'name':'klaus','phone':'55345'} dict4 = {'name':'Krishna','phone':'12345'} dict5 = {'name':'...
In the general case, you'll want to write your key-extraction function for sorting purposes; only in special (though important) cases it happens that you can just reuse an existing callable to extract the keys for you, or just conjoin a couple of existing ones (in a "quick and dirty" way using `lambda`, since there's n...
How do I propagate C++ exceptions to Python in a SWIG wrapper library?
1,394,484
20
2009-09-08T14:57:44Z
1,513,274
15
2009-10-03T09:10:42Z
[ "python", "exception", "swig" ]
I'm writing a SWIG wrapper around a custom C++ library which defines its own C++ exception types. The library's exception types are richer and more specific than standard exceptions. (For example, one class represents parse errors and has a collection of line numbers.) How do I propagate those exceptions back to Python...
I know this question is a few weeks old but I just found it as I was researching a solution for myself. So I'll take a stab at an answer, but I'll warn in advance it may not be an attractive solution since swig interface files can be more complicated than hand coding the wrapper. Also, as far as I can tell, the swig do...
How do I copy a remote image in python?
1,394,721
14
2009-09-08T15:40:05Z
1,394,744
28
2009-09-08T15:45:41Z
[ "python", "download", "file-copying" ]
I need to copy a remote image (for example `http://example.com/image.jpg`) to my server. Is this possible? How do you verify that this is indeed an image?
To download: ``` import urllib2 img = urllib2.urlopen("http://example.com/image.jpg").read() ``` To verify can use [PIL](http://www.pythonware.com/products/pil/) ``` import StringIO from PIL import Image try: im = Image.open(StringIO.StringIO(img)) im.verify() except Exception, e: # The image is not vali...
How to do "hit any key" in python?
1,394,956
24
2009-09-08T16:32:27Z
1,394,994
30
2009-09-08T16:41:04Z
[ "python" ]
How would I do a "hit any key" (or grab a menu option) in Python? * raw\_input requires you hit return. * Windows msvcrt has getch() and getche(). Is there a portable way to do this using the standard libs?
``` try: # Win32 from msvcrt import getch except ImportError: # UNIX def getch(): import sys, tty, termios fd = sys.stdin.fileno() old = termios.tcgetattr(fd) try: tty.setraw(fd) return sys.stdin.read(1) finally: termios.tcsetat...
How to do "hit any key" in python?
1,394,956
24
2009-09-08T16:32:27Z
1,395,006
9
2009-09-08T16:43:11Z
[ "python" ]
How would I do a "hit any key" (or grab a menu option) in Python? * raw\_input requires you hit return. * Windows msvcrt has getch() and getche(). Is there a portable way to do this using the standard libs?
``` try: os.system('pause') #windows, doesn't require enter except whatever_it_is: os.system('read -p "Press any key to continue"') #linux ```
Parsing SQL with Python
1,394,998
29
2009-09-08T16:42:03Z
1,395,854
25
2009-09-08T19:25:54Z
[ "python", "sql", "parsing", "pyparsing" ]
I want to create a SQL interface on top of a non-relational data store. Non-relational data store, but it makes sense to access the data in a relational manner. I am looking into using [ANTLR](http://www.antlr.org/) to produce an AST that represents the SQL as a relational algebra expression. Then return data by evalu...
I have looked into this issue quite extensively. Python-sqlparse is a non validating parser which is not really what you need. The examples in antlr need a lot of work to convert to a nice ast in python. The sql standard grammers are [here](http://savage.net.au/SQL/), but it would be a full time job to convert them you...
How can I make `bin(30)` return `00011110` instead of `0b11110`?
1,395,356
15
2009-09-08T17:53:38Z
1,395,376
21
2009-09-08T17:56:26Z
[ "python" ]
What does the "b" stand for in the output of bin(30): "0b11110"? Is there any way I can get rid of this "b"? How can I get the output of bin() to always return a standard 8 digit output?
0b is like 0x - it indicates the number is formatted in binary (0x indicates the number is in hex). See [How do you express binary literals in python?](http://stackoverflow.com/questions/1476/how-do-you-express-binary-literals-in-python) See <http://docs.python.org/dev/whatsnew/2.6.html#pep-3127-integer-literal-suppo...
How can I make `bin(30)` return `00011110` instead of `0b11110`?
1,395,356
15
2009-09-08T17:53:38Z
1,395,408
29
2009-09-08T18:02:31Z
[ "python" ]
What does the "b" stand for in the output of bin(30): "0b11110"? Is there any way I can get rid of this "b"? How can I get the output of bin() to always return a standard 8 digit output?
Using [zfill()](http://docs.python.org/library/stdtypes.html#str.zfill): > Return the numeric string left filled with zeros in a string of length width. A sign prefix is handled correctly. The original string is returned if width is less than len(s). ``` >>> bin(30)[2:].zfill(8) '00011110' >>> ```
How can I make `bin(30)` return `00011110` instead of `0b11110`?
1,395,356
15
2009-09-08T17:53:38Z
22,863,621
8
2014-04-04T13:02:10Z
[ "python" ]
What does the "b" stand for in the output of bin(30): "0b11110"? Is there any way I can get rid of this "b"? How can I get the output of bin() to always return a standard 8 digit output?
``` >>> print format(30, 'b') 11110 >>> print format(30, 'b').zfill(8) 00011110 ``` Should do. Here `'b'` stands for binary just like `'x'`, `'o'` & `'d'` for hexadecimal, octal and decimal respectively.
Managing resources in a Python project
1,395,593
15
2009-09-08T18:37:39Z
1,396,657
17
2009-09-08T22:22:05Z
[ "python", "resources", "setuptools", "distutils", "decoupling" ]
I have a Python project in which I am using many non-code files. Currently these are all images, but I might use other kinds of files in the future. What would be a good scheme for storing and referencing these files? I considered just making a folder "resources" in the main directory, but there is a problem; Some ima...
You may want to use `pkg_resources` library that comes with `setuptools`. For example, I've made up a quick little package `"proj"` to illustrate the resource organization scheme I'd use: ``` proj/setup.py proj/proj/__init__.py proj/proj/code.py proj/proj/resources/__init__.py proj/proj/resources/images/__init__.py p...
Trouble with simple Python Code
1,395,603
4
2009-09-08T18:39:48Z
1,395,617
7
2009-09-08T18:42:13Z
[ "python" ]
I'm learning Python, and I'm having trouble with this simple piece of code: ``` a = raw_input('Enter a number: ') if a > 0: print 'Positive' elif a == 0: print 'Null' elif a < 0: print 'Negative' ``` It works great, apart from the fact that it always prints 'Positive', no matter if i enter a positive or ...
That's because `a` is a string as inputted. Use `int()` to convert it to an integer before doing numeric comparisons. ``` a = int(raw_input('Enter a number: ')) if a > 0: print 'Positive' elif a == 0: print 'Null' elif a < 0: print 'Negative' ``` Alternatively, `input()` will do type conversion for you. ...
Trouble with simple Python Code
1,395,603
4
2009-09-08T18:39:48Z
1,395,635
7
2009-09-08T18:43:50Z
[ "python" ]
I'm learning Python, and I'm having trouble with this simple piece of code: ``` a = raw_input('Enter a number: ') if a > 0: print 'Positive' elif a == 0: print 'Null' elif a < 0: print 'Negative' ``` It works great, apart from the fact that it always prints 'Positive', no matter if i enter a positive or ...
Because you are using `raw_input` you are getting the value as a String, which is always considered greater than 0 (even if the String is '-10') Instead, try using input('Enter a number: ') and python will do the type conversion for you. The final code would look like this: ``` a = input('Enter a number: ') if a > 0...
Trouble with simple Python Code
1,395,603
4
2009-09-08T18:39:48Z
1,396,057
7
2009-09-08T20:07:12Z
[ "python" ]
I'm learning Python, and I'm having trouble with this simple piece of code: ``` a = raw_input('Enter a number: ') if a > 0: print 'Positive' elif a == 0: print 'Null' elif a < 0: print 'Negative' ``` It works great, apart from the fact that it always prints 'Positive', no matter if i enter a positive or ...
Expanding on my comment on the [accepted answer](http://stackoverflow.com/questions/1395603/trouble-with-simple-python-code/1395635#1395635), here's how I would do it. ``` value = None getting_input = True while getting_input: try: value = int(raw_input('Gimme a number: ')) getting_input = False ...
Proper way to handle multiple forms on one page in Django
1,395,807
123
2009-09-08T19:17:09Z
1,395,866
81
2009-09-08T19:29:10Z
[ "python", "django", "forms" ]
I have a template page expecting two forms. If I just use one form, things are fine as in this typical example: ``` if request.method == 'POST': form = AuthorForm(request.POST,) if form.is_valid(): form.save() # do something. else: form = AuthorForm() ``` If I want to work with multiple fo...
You have a few options: 1. Put different URLs in the action for the two forms. Then you'll have two different view functions to deal with the two different forms. 2. Read the submit button values from the POST data. You can tell which submit button was clicked: [How can I build multiple submit buttons django form?](ht...
Proper way to handle multiple forms on one page in Django
1,395,807
123
2009-09-08T19:17:09Z
1,395,970
30
2009-09-08T19:50:05Z
[ "python", "django", "forms" ]
I have a template page expecting two forms. If I just use one form, things are fine as in this typical example: ``` if request.method == 'POST': form = AuthorForm(request.POST,) if form.is_valid(): form.save() # do something. else: form = AuthorForm() ``` If I want to work with multiple fo...
A method for future reference is something like this. bannedphraseform is the first form and expectedphraseform is the second. If the first one is hit, the second one is skipped (which is a reasonable assumption in this case): ``` if request.method == 'POST': bannedphraseform = BannedPhraseForm(request.POST, prefi...
Proper way to handle multiple forms on one page in Django
1,395,807
123
2009-09-08T19:17:09Z
17,303,425
9
2013-06-25T17:09:50Z
[ "python", "django", "forms" ]
I have a template page expecting two forms. If I just use one form, things are fine as in this typical example: ``` if request.method == 'POST': form = AuthorForm(request.POST,) if form.is_valid(): form.save() # do something. else: form = AuthorForm() ``` If I want to work with multiple fo...
Django's class based views provide a generic FormView but for all intents and purposes it is designed to only handle one form. One way to handle multiple forms with same target action url using Django's generic views is to extend the 'TemplateView' as shown below; I use this approach often enough that I have made it i...
How to drop into REPL (Read, Eval, Print, Loop) from Python code
1,395,913
66
2009-09-08T19:40:33Z
1,395,925
14
2009-09-08T19:42:26Z
[ "python", "interactive" ]
Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line? I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to allow for t...
You can launch the debugger: ``` import pdb;pdb.set_trace() ``` Not sure what you want the REPL for, but the debugger is very similar.
How to drop into REPL (Read, Eval, Print, Loop) from Python code
1,395,913
66
2009-09-08T19:40:33Z
1,396,190
27
2009-09-08T20:31:58Z
[ "python", "interactive" ]
Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line? I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to allow for t...
Here's how you should do it (IPython > v0.11): ``` import IPython IPython.embed() ``` For IPython <= v0.11: ``` from IPython.Shell import IPShellEmbed ipshell = IPShellEmbed() ipshell() # this call anywhere in your program will start IPython ``` You should use IPython, the Cadillac of Python REPLs. See <http://ip...
How to drop into REPL (Read, Eval, Print, Loop) from Python code
1,395,913
66
2009-09-08T19:40:33Z
1,396,199
50
2009-09-08T20:34:12Z
[ "python", "interactive" ]
Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line? I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to allow for t...
You could try using the interactive option for python: ``` python -i program.py ``` This will execute the code in program.py, then go to the REPL. Anything you define or import in the top level of program.py will be available.
How to drop into REPL (Read, Eval, Print, Loop) from Python code
1,395,913
66
2009-09-08T19:40:33Z
1,396,386
87
2009-09-08T21:18:44Z
[ "python", "interactive" ]
Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line? I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to allow for t...
I frequently use this: ``` def interact(): import code code.InteractiveConsole(locals=globals()).interact() ```
How to drop into REPL (Read, Eval, Print, Loop) from Python code
1,395,913
66
2009-09-08T19:40:33Z
1,396,504
13
2009-09-08T21:48:45Z
[ "python", "interactive" ]
Is there a way to programmatically force a Python script to drop into a REPL at an arbitrary point in its execution, even if the script was launched from the command line? I'm writing a quick and dirty plotting program, which I want to read data from stdin or a file, plot it, and then drop into the REPL to allow for t...
To get use of iPython and functionality of debugger you should use [ipdb](http://pypi.python.org/pypi/ipdb/), You can use it in the same way as pdb, with the addition of : ``` import ipdb ipdb.set_trace() ```
Customizing how Python's `copy` module treats my objects
1,396,547
3
2009-09-08T21:58:48Z
1,397,416
7
2009-09-09T03:33:51Z
[ "python", "copy", "pickle" ]
From the [`copy` documentation](http://docs.python.org/library/copy.html): > Classes can use the same interfaces to control copying that they use to control pickling. > > [...] > > In order for a class to define its own copy implementation, it can define special methods `__copy__()` and `__deepcopy__()` So which one ...
It works as follows: if a class defines `__copy__`, that takes precedence for `copy.copy` purposes (and similarly `__deepcopy__` takes precedence for `copy.deepcopy` purposes). If these very specific special methods are not defined, then the same mechanisms as for pickling and unpickling are tested (this includes, but ...
Why is subtraction faster than addition in Python?
1,396,564
32
2009-09-08T22:01:59Z
1,396,597
13
2009-09-08T22:09:23Z
[ "python", "performance", "addition", "subtraction" ]
I was optimising some Python code, and tried the following experiment: ``` import time start = time.clock() x = 0 for i in range(10000000): x += 1 end = time.clock() print '+=',end-start start = time.clock() x = 0 for i in range(10000000): x -= -1 end = time.clock() print '-=',end-start ``` The second loo...
``` $ python -m timeit -s "x=0" "x+=1" 10000000 loops, best of 3: 0.151 usec per loop $ python -m timeit -s "x=0" "x-=-1" 10000000 loops, best of 3: 0.154 usec per loop ``` Looks like you've some [measurement bias](http://www-plan.cs.colorado.edu/diwan/asplos09.pdf)
Why is subtraction faster than addition in Python?
1,396,564
32
2009-09-08T22:01:59Z
1,396,671
7
2009-09-08T22:27:52Z
[ "python", "performance", "addition", "subtraction" ]
I was optimising some Python code, and tried the following experiment: ``` import time start = time.clock() x = 0 for i in range(10000000): x += 1 end = time.clock() print '+=',end-start start = time.clock() x = 0 for i in range(10000000): x -= -1 end = time.clock() print '-=',end-start ``` The second loo...
I think the "general programming lesson" is that it is *really* hard to predict, solely by looking at the source code, which sequence of statements will be the fastest. Programmers at all levels frequently get caught up by this sort of "intuitive" optimisation. What you think you know may not necessarily be true. Ther...
Why is subtraction faster than addition in Python?
1,396,564
32
2009-09-08T22:01:59Z
1,396,744
71
2009-09-08T22:47:51Z
[ "python", "performance", "addition", "subtraction" ]
I was optimising some Python code, and tried the following experiment: ``` import time start = time.clock() x = 0 for i in range(10000000): x += 1 end = time.clock() print '+=',end-start start = time.clock() x = 0 for i in range(10000000): x -= -1 end = time.clock() print '-=',end-start ``` The second loo...
I can reproduce this on my Q6600 (Python 2.6.2); increasing the range to 100000000: ``` ('+=', 11.370000000000001) ('-=', 10.769999999999998) ``` First, some observations: * This is 5% for a trivial operation. That's significant. * The speed of the native addition and subtraction opcodes is irrelevant. It's in the n...
Python: Get object by id
1,396,668
63
2009-09-08T22:26:56Z
1,396,690
29
2009-09-08T22:34:56Z
[ "python" ]
Let's say I have an id of a Python object, which I retrieved by doing `id(thing)`. How do I find `thing` again by the id number I was given?
You can use the [gc](http://docs.python.org/library/gc.html) module to get all the objects currently tracked by the Python garbage collector. ``` import gc def objects_by_id(id_): for obj in gc.get_objects(): if id(obj) == id_: return obj raise Exception("No found") ```
Python: Get object by id
1,396,668
63
2009-09-08T22:26:56Z
1,396,696
34
2009-09-08T22:37:30Z
[ "python" ]
Let's say I have an id of a Python object, which I retrieved by doing `id(thing)`. How do I find `thing` again by the id number I was given?
Short answer, you can't. Long answer, you can maintain a dict for mapping IDs to objects, or look the ID up by exhaustive search of `gc.get_objects()`, but this will create one of two problems: either the dict's reference will keep the object alive and prevent GC, or (if it's a WeakValue dict or you use `gc.get_object...
Python: Get object by id
1,396,668
63
2009-09-08T22:26:56Z
1,396,739
20
2009-09-08T22:46:31Z
[ "python" ]
Let's say I have an id of a Python object, which I retrieved by doing `id(thing)`. How do I find `thing` again by the id number I was given?
You'll probably want to consider implementing it another way. Are you aware of the weakref module? (Edited) The Python [weakref module](http://docs.python.org/library/weakref.html) lets you keep references, dictionary references, and proxies to objects without having those references count in the reference counter. Th...
Python: Get object by id
1,396,668
63
2009-09-08T22:26:56Z
15,702,647
72
2013-03-29T11:51:23Z
[ "python" ]
Let's say I have an id of a Python object, which I retrieved by doing `id(thing)`. How do I find `thing` again by the id number I was given?
This can be done easily by `ctypes`: ``` import ctypes a = "hello world" print ctypes.cast(id(a), ctypes.py_object).value ``` output: ``` hello world ```
How to read formatted input in python?
1,397,827
7
2009-09-09T06:19:59Z
1,397,841
15
2009-09-09T06:24:52Z
[ "python", "input" ]
I want to read from stdin five numbers entered as follows: 3, 4, 5, 1, 8 into seperate variables a,b,c,d & e. How do I do this in python? I tried this: ``` import string a=input() b=a.split(', ') ``` for two integers, but it does not work. I get: ``` Traceback (most recent call last): File "C:\Users\Desktop\co...
Use [`raw_input()`](http://docs.python.org/library/functions.html#raw%5Finput) instead of `input()`. ``` # Python 2.5.4 >>> a = raw_input() 3, 4, 5 >>> a '3, 4, 5' >>> b = a.split(', ') >>> b ['3', '4', '5'] >>> [s.strip() for s in raw_input().split(",")] # one liner 3, 4, 5 ['3', '4', '5'] ``` The misleadingly names...
looping over all member variables of a class in python
1,398,022
40
2009-09-09T07:15:42Z
1,398,059
52
2009-09-09T07:23:45Z
[ "python" ]
How do you get a list of all variables in a class thats iteratable? Kind of like locals(), but for a class ``` class Example(object): bool143 = True bool2 = True blah = False foo = True foobar2000 = False def as_list(self) ret = [] for field in XXX: if getattr(self, fi...
``` dir(obj) ``` gives you all attributes of the object. You need to filter out the members from methods etc yourself: ``` class Example(object): bool143 = True bool2 = True blah = False foo = True foobar2000 = False members = [attr for attr in dir(Example()) if not callable(attr) and not attr.s...
looping over all member variables of a class in python
1,398,022
40
2009-09-09T07:15:42Z
1,939,279
18
2009-12-21T10:14:47Z
[ "python" ]
How do you get a list of all variables in a class thats iteratable? Kind of like locals(), but for a class ``` class Example(object): bool143 = True bool2 = True blah = False foo = True foobar2000 = False def as_list(self) ret = [] for field in XXX: if getattr(self, fi...
@truppo: your answer is almost correct, but callable will always return false since you're just passing in a string. You need something like the following: ``` [attr for attr in dir(obj()) if not callable(getattr(obj(),attr)) and not attr.startswith("__")] ``` which will filter out functions
looping over all member variables of a class in python
1,398,022
40
2009-09-09T07:15:42Z
13,286,863
41
2012-11-08T10:10:22Z
[ "python" ]
How do you get a list of all variables in a class thats iteratable? Kind of like locals(), but for a class ``` class Example(object): bool143 = True bool2 = True blah = False foo = True foobar2000 = False def as_list(self) ret = [] for field in XXX: if getattr(self, fi...
If you want only the variables (without functions) use: ``` vars(your_object) ```
Initialize a string variable in Python: "" or None?
1,398,164
30
2009-09-09T07:49:17Z
1,398,178
35
2009-09-09T07:52:45Z
[ "python" ]
Suppose I have a class with a **string** instance attribute. Should I initialize this attribute with **""** value or **None**? Is either okay? ``` def __init__(self, mystr="") self.mystr = mystr ``` or ``` def __init__(self, mystr=None) self.mystr = mystr ``` **Edit**: What I thought is that if I use **""** a...
If not having a value has a meaning in your program (e.g. an optional value), you should use None. That's its purpose anyway. If the value must be provided by the caller of \_\_init\_\_, I would recommend not to initialize it. If "" makes sense as a default value, use it. In Python the type is deduced from the usage...
Django: show list of many to many items in the admin interface
1,398,606
8
2009-09-09T09:43:11Z
1,398,652
19
2009-09-09T09:52:52Z
[ "python", "django" ]
This might be a simple question, but i can't seem to grasp it. I have two simple models in models.py: Service and Host. Host.services has a m2m relationship with Service. In other words, a host has several services and one service can reside on multiple hosts; a basic m2m. models.py ``` class Service(models.Model): ...
You should change `get_services` to something like: ``` def get_services(self): return "\n".join([s.servicename for s in self.services.all()]) ``` **Update:** Try using `\n` as the separator rather than `<br/>`, as the output of get\_services is being escaped.
Python: display the time in a different time zone
1,398,674
16
2009-09-09T09:57:52Z
1,398,729
24
2009-09-09T10:10:43Z
[ "python", "time", "timezone" ]
Is there an elegant way to display the current time in another time zone? I would like to have something with the general spirit of: ``` cur=<Get the current time, perhaps datetime.datetime.now()> print "Local time ", cur print "Pacific time ", <something like cur.tz('PST')> print "Israeli time ", <something like c...
You could use the [pytz](http://pytz.sourceforge.net/) library: ``` >>> from datetime import datetime, timedelta >>> from pytz import timezone >>> import pytz >>> utc = pytz.utc >>> utc.zone 'UTC' >>> eastern = timezone('US/Eastern') >>> eastern.zone 'US/Eastern' >>> amsterdam = timezone('Europe/Amsterdam') >>> fmt = ...
Python: display the time in a different time zone
1,398,674
16
2009-09-09T09:57:52Z
5,096,669
37
2011-02-23T20:26:12Z
[ "python", "time", "timezone" ]
Is there an elegant way to display the current time in another time zone? I would like to have something with the general spirit of: ``` cur=<Get the current time, perhaps datetime.datetime.now()> print "Local time ", cur print "Pacific time ", <something like cur.tz('PST')> print "Israeli time ", <something like c...
A simpler method: ``` from datetime import datetime from pytz import timezone south_africa = timezone('Africa/Johannesburg') sa_time = datetime.now(south_africa) print sa_time.strftime('%Y-%m-%d_%H-%M-%S') ```
Problems with Snow Leopard, Django & PIL
1,398,701
5
2009-09-09T10:05:13Z
1,413,877
14
2009-09-12T00:43:05Z
[ "python", "django", "osx-snow-leopard", "python-imaging-library", "libjpeg" ]
I am having some trouble getting Django & PIL work properly since upgrading to Snow Leopard. I have installed freetype, libjpeg and then PIL, which tells me: ``` --- TKINTER support ok --- JPEG support ok --- ZLIB (PNG/ZIP) support ok --- FREETYPE2 support ok ``` but when I try to upload a jpeg through the django ad...
Cato I had the same experience with Leopard 10.5.x Here is what I did to fix it, (may not work for you). 1. Go to your PIL working folder (where you unzipped PIL) cd to your build folder cd to your lib.macosx-10.\* folder (specific to your os) remove \*.so cd back to your PIL build folder (I logged in ...
using cookies with twisted.web.client
1,398,740
3
2009-09-09T10:12:10Z
1,687,928
7
2009-11-06T14:23:05Z
[ "python", "cookies", "twisted" ]
I'm trying to make a web client application using twisted but having some trouble with cookies. Does anyone have an example I can look at?
While it's true that `getPage` doesn't easily allow direct access to the request or response headers (just one example of how `getPage` isn't a super awesome API), cookies are actually supported. ``` cookies = {cookies: tosend} d = getPage(url, cookies=cookies) def cbPage(result): print 'Look at my cookies:', cook...
Downloading file using IE from python
1,398,780
7
2009-09-09T10:18:42Z
4,590,561
7
2011-01-04T04:08:48Z
[ "python", "internet-explorer", "com" ]
I'm trying to download file with Python using IE: ``` from win32com.client import DispatchWithEvents class EventHandler(object): def OnDownloadBegin(self): pass ie = DispatchWithEvents("InternetExplorer.Application", EventHandler) ie.Visible = 0 ie.Navigate('http://website/file.xml') ``` After this, I...
This works for me as long as the IE dialogs are in the foreground and the downloaded file does not already exist in the "Save As" directory: ``` import time import threading import win32ui, win32gui, win32com, pythoncom, win32con from win32com.client import Dispatch class IeThread(threading.Thread): def run(self)...
The Assignment Problem, a numpy function?
1,398,822
6
2009-09-09T10:28:36Z
22,773,632
10
2014-03-31T22:44:35Z
[ "python", "numpy", "scipy" ]
Since an [assignment problem](http://en.wikipedia.org/wiki/Assignment%5Fproblem) can be posed in the form of a single matrix, I am wandering if numpy has a function to solve such a matrix. So far I have found none. Maybe one of you guys know if numpy/scipy has an assignment-problem-solve function? **Edit:** In the mea...
There is now a numpy implementation of the munkres algorithm in scikit-learn under [sklearn/utils/linear\_assignment\_.py](https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/utils/linear_assignment_.py) its only dependency is numpy. I tried it with some approximately 20x20 matrices, and it seems to be abo...