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 |
|---|---|---|---|---|---|---|---|---|---|
Convert hex to binary | 1,425,493 | 49 | 2009-09-15T06:41:37Z | 1,427,846 | 9 | 2009-09-15T15:22:44Z | [
"python",
"string",
"binary",
"hex",
"string-formatting"
] | I have ABC123EFFF.
I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).
How? | Here's a fairly raw way to do it using bit fiddling to generate the binary strings.
The key bit to understand is:
```
(n & (1 << i)) and 1
```
Which will generate either a 0 or 1 if the i'th bit of n is set.
```
import binascii
def byte_to_binary(n):
return ''.join(str((n & (1 << i)) and 1) for i in reversed(r... |
Convert hex to binary | 1,425,493 | 49 | 2009-09-15T06:41:37Z | 4,859,937 | 58 | 2011-02-01T07:17:53Z | [
"python",
"string",
"binary",
"hex",
"string-formatting"
] | I have ABC123EFFF.
I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).
How? | For solving the left-side trailing zero problem:
---
```
my_hexdata = "1a"
scale = 16 ## equals to hexadecimal
num_of_bits = 8
bin(int(my_hexdata, scale))[2:].zfill(num_of_bits)
```
---
It will give 00011010 instead of the trimmed version. |
Convert hex to binary | 1,425,493 | 49 | 2009-09-15T06:41:37Z | 9,486,791 | 11 | 2012-02-28T17:28:51Z | [
"python",
"string",
"binary",
"hex",
"string-formatting"
] | I have ABC123EFFF.
I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).
How? | ```
"{0:020b}".format(int('ABC123EFFF', 16))
``` |
Convert hex to binary | 1,425,493 | 49 | 2009-09-15T06:41:37Z | 25,016,156 | 13 | 2014-07-29T13:10:58Z | [
"python",
"string",
"binary",
"hex",
"string-formatting"
] | I have ABC123EFFF.
I want to have 001010101111000001001000111110111111111111 (i.e. binary repr. with, say, 42 digits and leading zeroes).
How? | ```
>>> bin( 0xABC123EFFF )
```
'0b1010101111000001001000111110111111111111' |
Calling Py_Finalize() from C | 1,427,002 | 9 | 2009-09-15T12:51:46Z | 1,434,508 | 7 | 2009-09-16T17:48:38Z | [
"c++",
"python",
"c"
] | This is a follow up to <http://stackoverflow.com/questions/1417473/call-python-from-c>
At the startup of the programm I call the following function to initialize the interpreter:
```
void initPython(){
PyEval_InitThreads();
Py_Initialize();
PyEval_ReleaseLock();
}
```
Every thread creates it's own data s... | Yeah the whole section is rather dubious but I think I've got my mistake.
I've got to save the PyThreadState when initializing the interpreter and swap this state back in when I finish it (no idea why I need a specific ThreadState to call Finalize - shouldn't every State work as well?)
Anyways the example if other pe... |
Encoding issues with python's etree.tostring | 1,428,172 | 7 | 2009-09-15T16:20:37Z | 1,428,220 | 16 | 2009-09-15T16:30:15Z | [
"python",
"xml",
"utf-8",
"tostring"
] | I'm using python 2.6.2's xml.etree.cElementTree to create an xml document:
```
import xml.etree.cElementTree as etree
elem = etree.Element('tag')
elem.text = (u"Würth Elektronik Midcom").encode('utf-8')
xml = etree.tostring(elem,encoding='UTF-8')
```
At the end of the day, xml looks like:
```
<?xml version='1.0' en... | You're encoding the text twice. Try this:
```
import xml.etree.cElementTree as etree
elem = etree.Element('tag')
elem.text = u"Würth Elektronik Midcom"
xml = etree.tostring(elem,encoding='UTF-8')
``` |
Python switch order of elements | 1,428,547 | 2 | 2009-09-15T17:30:18Z | 1,428,588 | 13 | 2009-09-15T17:39:11Z | [
"python"
] | I am a newbie and seeking for the Zen of Python :) Today's koan was finding the most Pythonesq way to solve the following problem:
> Permute the letters of a string pairwise, e.g.
>
> ```
> input: 'abcdefgh'
> output: 'badcfehg'
> ``` | I'd go for:
```
s="abcdefgh"
print "".join(b+a for a,b in zip(s[::2],s[1::2]))
```
s[start:end:step] takes every step'th letter, zip matches them up pairwise, the loop swaps them, and the join gives you back a string. |
Is it possible to make re find the smallest match while using greedy characters | 1,428,780 | 3 | 2009-09-15T18:07:11Z | 1,428,802 | 10 | 2009-09-15T18:11:28Z | [
"python",
"regex"
] | Disclaimer: I'm not a regex expert.
I'm using Python re module to perform regex matching on many htm files. One of the patterns is something like this:
```
<bla><blabla>87765.*</blabla><bla>
```
The problem I've encountered is that instead of finding all (say) five occurrences of the pattern, it will find only one. ... | You can use a reluctant qualifier in your pattern (for more details, reference the [python documentation](http://docs.python.org/library/re.html) on the `*?`, `+?`, and `??` operators):
```
<bla><blabla>87765.*?</blabla><bla>
```
Or, exclude `<` from the possible matched characters:
```
<bla><blabla>87765[^<]*</blab... |
Python 3 smtplib send with unicode characters | 1,429,147 | 7 | 2009-09-15T19:22:08Z | 1,430,542 | 8 | 2009-09-16T02:00:56Z | [
"python",
"email",
"unicode",
"python-3.x",
"smtplib"
] | I'm having a problem emailing unicode characters using smtplib in Python 3. This fails in 3.1.1, but works in 2.5.4:
```
import smtplib
from email.mime.text import MIMEText
sender = to = '[email protected]'
server = 'smtp.DEF.com'
msg = MIMEText('â¬10')
msg['Subject'] = 'Hello'
msg['From'] = sender
msg['To... | The key is in [the docs](http://docs.python.org/3.1/library/email.mime.html#email.mime.text.MIMEText):
```
class email.mime.text.MIMEText(_text, _subtype='plain', _charset='us-ascii')
```
> A subclass of MIMENonMultipart, the
> MIMEText class is used to create MIME
> objects of major type text. \_text is
> the string... |
Does Python have an equivalent to 'switch'? | 1,429,505 | 13 | 2009-09-15T20:41:33Z | 1,429,518 | 27 | 2009-09-15T20:43:18Z | [
"python",
"syntax",
"switch-statement"
] | I am trying to check each index in an 8 digit binary string. If it is `'0'` then it is `'OFF'` otherwise its `'ON'`.
Is there a more concise way to write this code with a switch-like feature.? | ["Why isn't there a switch or case statement in Python?"](http://docs.python.org/faq/design.html#why-isn-t-there-a-switch-or-case-statement-in-python) |
Does Python have an equivalent to 'switch'? | 1,429,505 | 13 | 2009-09-15T20:41:33Z | 1,429,537 | 15 | 2009-09-15T20:48:50Z | [
"python",
"syntax",
"switch-statement"
] | I am trying to check each index in an 8 digit binary string. If it is `'0'` then it is `'OFF'` otherwise its `'ON'`.
Is there a more concise way to write this code with a switch-like feature.? | No it doesn't. In the Python core language, one of the rules is to only have one way to do something. The switch is redundant to:
```
if x == 1:
pass
elif x == 5:
pass
elif x == 10:
pass
```
(without the fall-through, of course).
The switch was originally introduced as a compiler optimization for C. Mode... |
How to programmatically set a global (module) variable? | 1,429,814 | 22 | 2009-09-15T21:50:47Z | 1,429,835 | 26 | 2009-09-15T21:56:13Z | [
"python",
"module",
"global-variables"
] | I would like to define globals in a "programmatic" way. Something similar to what I want to do would be:
```
definitions = {'a': 1, 'b': 2, 'c': 123.4}
for definition in definitions.items():
exec("%s = %r" % definition) # a = 1, etc.
```
Specifically, I want to create a module `fundamentalconstants` that contain... | You can set globals in the dictionary returned by globals():
```
definitions = {'a': 1, 'b': 2, 'c': 123.4}
for name, value in definitions.items():
globals()[name] = value
``` |
How to programmatically set a global (module) variable? | 1,429,814 | 22 | 2009-09-15T21:50:47Z | 1,430,178 | 33 | 2009-09-15T23:37:45Z | [
"python",
"module",
"global-variables"
] | I would like to define globals in a "programmatic" way. Something similar to what I want to do would be:
```
definitions = {'a': 1, 'b': 2, 'c': 123.4}
for definition in definitions.items():
exec("%s = %r" % definition) # a = 1, etc.
```
Specifically, I want to create a module `fundamentalconstants` that contain... | Here is a better way to do it:
```
import sys
definitions = {'a': 1, 'b': 2, 'c': 123.4}
module = sys.modules[__name__]
for name, value in definitions.iteritems():
setattr(module, name, value)
``` |
Create a temporary FIFO (named pipe) in Python? | 1,430,446 | 21 | 2009-09-16T01:16:58Z | 1,430,566 | 19 | 2009-09-16T02:09:15Z | [
"python",
"security",
"file",
"fifo",
"mkfifo"
] | How can you create a temporary FIFO (named pipe) in Python? This should work:
```
import tempfile
temp_file_name = mktemp()
os.mkfifo(temp_file_name)
open(temp_file_name, os.O_WRONLY)
# ... some process, somewhere, will read it ...
```
However, I'm hesitant because of the big warning in [Python Docs 11.6](http://doc... | `os.mkfifo()` will fail with exception `OSError: [Errno 17] File exists` if the file already exists, so there is no security issue here. The security issue with using `tempfile.mktemp()` is the race condition where it is possible for an attacker to create a file with the same name before you open it yourself, but since... |
Add an "empty" option to a ChoiceField based on model datas | 1,431,966 | 2 | 2009-09-16T09:34:08Z | 1,432,100 | 8 | 2009-09-16T10:08:23Z | [
"python",
"django",
"forms",
"choicefield"
] | I'm defining a ChoiceField based on a model's datas.
```
field = forms.ChoiceField(choices=[[r.id, r.name] for r in Model.objects.all()])
```
However I'd like to prepend my options with an empty one to select "no" objects.
But I can't find a nice way to prepend that.
All my tests like :
```
field = forms.ChoiceFiel... | An easy answer is to do:
```
field = forms.ChoiceField(choices=[[0, '----------']] + [[r.id, r.name] for r in Model.objects.all()])
```
Unfortunately, your approach is flawed. Even with your 'working' approach, the field choices are defined when the form is defined, not when it is instantiated - so if you add element... |
how to get content of a small ascii file in python? | 1,432,126 | 20 | 2009-09-16T10:13:28Z | 1,432,238 | 29 | 2009-09-16T10:48:20Z | [
"python",
"file"
] | Let's say we want to implement an equivalent of the PHP's [`file_get_content`](http://fr2.php.net/manual/en/function.file-get-contents.php).
What is the best practice? (elegant and reliable)
Here are some proposition, are they correct?
using `with` statement:
```
def file_get_contents(filename):
with file(filen... | In the current implementation of CPython, both will generally immediately close the file. However, Python the language makes no such guarantee for the second one - the file will eventually be closed, but the finaliser may not be called until the next gc cycle. Implementations like Jython and IronPython will work like t... |
Any way to clear python's IDLE window? | 1,432,480 | 80 | 2009-09-16T11:49:36Z | 1,432,505 | 41 | 2009-09-16T11:54:59Z | [
"python",
"python-idle"
] | I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.
How do I clear python's IDLE window? | `os.system('clear')` works on linux. If you are running windows try `os.system('CLS')` instead.
You need to import os first like this:
```
import os
``` |
Any way to clear python's IDLE window? | 1,432,480 | 80 | 2009-09-16T11:49:36Z | 1,433,135 | 7 | 2009-09-16T13:56:11Z | [
"python",
"python-idle"
] | I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.
How do I clear python's IDLE window? | The way to execute commands in Python 2.4+ is to use the [subprocess](http://docs.python.org/library/subprocess.html) module. You can use it in the same way that you use `os.system`.
```
import subprocess
subprocess.call("clear") # linux/mac
subprocess.call("cls", shell=True) # windows
```
If you're executing this in... |
Any way to clear python's IDLE window? | 1,432,480 | 80 | 2009-09-16T11:49:36Z | 1,433,818 | 64 | 2009-09-16T15:44:21Z | [
"python",
"python-idle"
] | I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.
How do I clear python's IDLE window? | The "cls" and "clear" are commands which will clear a terminal (ie a DOS prompt, or terminal window). From your screenshot, you are using the shell within IDLE, which won't be affected by such things. Unfortunately, I don't think there is a way to clear the screen in IDLE. The best you could do is to scroll the screen ... |
Any way to clear python's IDLE window? | 1,432,480 | 80 | 2009-09-16T11:49:36Z | 8,352,839 | 14 | 2011-12-02T07:04:16Z | [
"python",
"python-idle"
] | I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.
How do I clear python's IDLE window? | An extension for clearing the shell can be found in [Issue6143](http://bugs.python.org/issue6143) as a "feature request". This extension is included with [IdleX](http://idlex.sourceforge.net). |
Any way to clear python's IDLE window? | 1,432,480 | 80 | 2009-09-16T11:49:36Z | 24,466,596 | 7 | 2014-06-28T11:59:57Z | [
"python",
"python-idle"
] | I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.
How do I clear python's IDLE window? | Most of the answers appear here do clearing the DOS prompt screen clearing commands. Which is not the Question asked here. An other answer here posted was the printing blank lines to show a clearing effect of the screen.
The simplest answer of this question is
> It is not possible to clear python IDLE shell without s... |
Any way to clear python's IDLE window? | 1,432,480 | 80 | 2009-09-16T11:49:36Z | 29,189,588 | 12 | 2015-03-22T00:19:55Z | [
"python",
"python-idle"
] | I know there's a similar topic about python console, but I do not know if they are the same. I tried system("clear") and it didn't work here.
How do I clear python's IDLE window? | `ctrl` + `L` clears the screen on Ubuntu Linux. |
python: Change the scripts working directory to the script's own directory | 1,432,924 | 85 | 2009-09-16T13:21:51Z | 1,432,949 | 100 | 2009-09-16T13:26:24Z | [
"python",
"working-directory"
] | I run a python shell from crontab every minute:
```
* * * * * /home/udi/foo/bar.py
```
`/home/udi/foo` has some necessary subdirectories, like `/home/udi/foo/log` and `/home/udi/foo/config`, which `/home/udi/foo/bar.py` refers to.
The problem is that `crontab` runs the script from a different working directory, so t... | This will change your current working directory to so that opening relative paths will work:
```
import os
os.chdir("/home/udi/foo")
```
However, you asked how to change into whatever directory your Python script is located, even if you don't know what directory that will be when you're writing your script. To do thi... |
python: Change the scripts working directory to the script's own directory | 1,432,924 | 85 | 2009-09-16T13:21:51Z | 1,433,009 | 14 | 2009-09-16T13:34:21Z | [
"python",
"working-directory"
] | I run a python shell from crontab every minute:
```
* * * * * /home/udi/foo/bar.py
```
`/home/udi/foo` has some necessary subdirectories, like `/home/udi/foo/log` and `/home/udi/foo/config`, which `/home/udi/foo/bar.py` refers to.
The problem is that `crontab` runs the script from a different working directory, so t... | Don't do this.
Your scripts and your data should not be mashed into one big directory. Put your code in some known location (`site-packages` or `/var/opt/udi` or something) separate from your data. Use good version control on your code to be sure that you have current and previous versions separated from each other so... |
python: Change the scripts working directory to the script's own directory | 1,432,924 | 85 | 2009-09-16T13:21:51Z | 9,130,405 | 16 | 2012-02-03T14:41:28Z | [
"python",
"working-directory"
] | I run a python shell from crontab every minute:
```
* * * * * /home/udi/foo/bar.py
```
`/home/udi/foo` has some necessary subdirectories, like `/home/udi/foo/log` and `/home/udi/foo/config`, which `/home/udi/foo/bar.py` refers to.
The problem is that `crontab` runs the script from a different working directory, so t... | You can get a shorter version by using `sys.path[0]`.
```
os.chdir(sys.path[0])
```
From <http://docs.python.org/library/sys.html#sys.path>
> As initialized upon program startup, the first item of this list,
> `path[0]`, is the directory containing the script that was used to
> invoke the Python interpreter |
python: Change the scripts working directory to the script's own directory | 1,432,924 | 85 | 2009-09-16T13:21:51Z | 14,628,314 | 9 | 2013-01-31T14:37:45Z | [
"python",
"working-directory"
] | I run a python shell from crontab every minute:
```
* * * * * /home/udi/foo/bar.py
```
`/home/udi/foo` has some necessary subdirectories, like `/home/udi/foo/log` and `/home/udi/foo/config`, which `/home/udi/foo/bar.py` refers to.
The problem is that `crontab` runs the script from a different working directory, so t... | Change your crontab command to
```
* * * * * (cd /home/udi/foo/ || exit 1; ./bar.py)
```
The `(...)` starts a sub-shell that your crond executes as a single command. The `|| exit 1` causes your cronjob to fail in case that the directory is unavailable.
Though the other solutions may be more elegant in the long run f... |
Generate and parse Python code from C# application | 1,432,998 | 5 | 2009-09-16T13:33:10Z | 1,433,330 | 7 | 2009-09-16T14:29:00Z | [
"c#",
"python",
"code-generation",
"ironpython",
"cocor"
] | I need to generate Python code to be more specific [IronPyton](http://ironpython.codeplex.com/). I also need to be able to parse the code and load it into [AST](http://en.wikipedia.org/wiki/Abstract%5Fsyntax%5Ftree). I just started looking at some tools. I played with ["Oslo"](http://msdn.microsoft.com/en-us/oslo/defau... | The [IronPython](http://ironpython.codeplex.com/) implementation itself includes [a parser](http://ironpython.codeplex.com/SourceControl/changeset/view/59195#992853) and [an AST representation](http://ironpython.codeplex.com/SourceControl/changeset/view/59195#992331) of Python programs which can be walked with a [`Pyth... |
Can we use a python variable to hold an entire file? | 1,433,577 | 6 | 2009-09-16T15:03:20Z | 1,433,601 | 11 | 2009-09-16T15:08:40Z | [
"python",
"file",
"variables"
] | Provided that we know that all the file will be loaded in memory and we can afford it,
what are the drawbacks (if any) or limitations (if any) of loading an entire file (possibly a binary file) in a python variable. If this is technically possible, should this be avoided, and why ?
Regarding file size concerns, to wha... | * Yes, you can
* The only drawback is memory usage, and possible also speed if the file is big.
* File size should be limited to how much space you have in memory.
In general, there are better ways to do it, but for one-off scripts where you know memory is not an issue, sure. |
Compiling Python | 1,434,144 | 41 | 2009-09-16T16:42:51Z | 1,434,155 | 25 | 2009-09-16T16:44:03Z | [
"python",
"compiler-construction"
] | How can I compile and run a python file (\*.py extension)? | `python yourfile.py`
You have to have python installed first. It will automatically compile your file into a .pyc binary, and then run it for you. It will automatically recompile any time your file changes.
<http://www.python.org/download/> |
Compiling Python | 1,434,144 | 41 | 2009-09-16T16:42:51Z | 1,434,170 | 15 | 2009-09-16T16:48:05Z | [
"python",
"compiler-construction"
] | How can I compile and run a python file (\*.py extension)? | Python compiles its files to bytecode before executing them. That means you have to have a Python interpreter installed on the target machine.
If you don't want to install Python on the target machine use [py2exe](http://www.py2exe.org/), [py2app](http://svn.pythonmac.org/py2app/py2app/trunk/doc/index.html) or somethi... |
Compiling Python | 1,434,144 | 41 | 2009-09-16T16:42:51Z | 1,434,486 | 8 | 2009-09-16T17:44:59Z | [
"python",
"compiler-construction"
] | How can I compile and run a python file (\*.py extension)? | Python is an interpreted language, so you don't need to compile it; just to run it. As it happens, the standard version of python will compile this to "bytecode", just like Java etc. does, and will save that (in .pyc files) and run it next time around, saving time, if you haven't updated the file since. If you've updat... |
Compiling Python | 1,434,144 | 41 | 2009-09-16T16:42:51Z | 1,529,049 | 9 | 2009-10-07T01:27:11Z | [
"python",
"compiler-construction"
] | How can I compile and run a python file (\*.py extension)? | If you just want to compile sources, without running them, you can do this
```
compileall.py <directory>
```
this command will compile python code in that directory recursively
**compileall** script is usually located in directory like
```
/usr/local/lib/python2.6
```
i.e. `<prefix>/lib/python2.6` (or similar, dep... |
Socket in use error when reusing sockets | 1,434,914 | 3 | 2009-09-16T19:10:31Z | 1,436,261 | 11 | 2009-09-17T01:09:07Z | [
"c++",
"python",
"sockets",
"xml-rpc"
] | I am writing an XMLRPC client in c++ that is intended to talk to a python XMLRPC server.
Unfortunately, at this time, the python XMLRPC server is only capable of fielding one request on a connection, then it shuts down, I discovered this thanks to mhawke's response to my previous query about a [related subject](http:/... | The problem is being caused by sockets hanging around in the TIME\_WAIT state which is entered once you close the client's socket. By default the socket will remain in this state for 4 minutes before it is available for reuse. Your client (possibly helped by other processes) is consuming them all within a 4 minute peri... |
Python memory leaks | 1,435,415 | 72 | 2009-09-16T20:56:04Z | 1,435,426 | 52 | 2009-09-16T20:58:17Z | [
"python",
"debugging",
"memory-management",
"memory-leaks"
] | I have a long-running script which, if let to run long enough, will consume all the memory on my system.
Without going into details about the script, I have two questions:
1. Are there any "Best Practices" to follow, which will help prevent leaks from occurring?
2. What techniques are there to debug memory leaks in P... | Have a look at this article: [Tracing python memory leaks](http://www.lshift.net/blog/2008/11/14/tracing-python-memory-leaks)
Also, note that the [garbage collection module](http://docs.python.org/library/gc.html) actually can have debug flags set. Look at the set\_debug function. Additionally, look at [this code by G... |
Python memory leaks | 1,435,415 | 72 | 2009-09-16T20:56:04Z | 23,883,524 | 9 | 2014-05-27T07:32:36Z | [
"python",
"debugging",
"memory-management",
"memory-leaks"
] | I have a long-running script which, if let to run long enough, will consume all the memory on my system.
Without going into details about the script, I have two questions:
1. Are there any "Best Practices" to follow, which will help prevent leaks from occurring?
2. What techniques are there to debug memory leaks in P... | Let me recommend [mem\_top](https://pypi.python.org/pypi/mem_top) tool,
that helped me to solve a similar issue.
It just instantly shows top suspects for memory leaks in a Python program. |
Python memory leaks | 1,435,415 | 72 | 2009-09-16T20:56:04Z | 29,923,561 | 33 | 2015-04-28T15:27:15Z | [
"python",
"debugging",
"memory-management",
"memory-leaks"
] | I have a long-running script which, if let to run long enough, will consume all the memory on my system.
Without going into details about the script, I have two questions:
1. Are there any "Best Practices" to follow, which will help prevent leaks from occurring?
2. What techniques are there to debug memory leaks in P... | I tried out most options mentioned previously but found this small and intuitive package to be the best: [pympler](https://github.com/pympler/pympler)
It's quite straight forward to trace objects that were not garbage-collected, check this small example:
install package via `pip install pympler`
```
from pympler.tra... |
manage.py syncdb doesn't add tables for some models | 1,435,523 | 4 | 2009-09-16T21:17:42Z | 1,435,758 | 8 | 2009-09-16T22:06:55Z | [
"python",
"django",
"django-models",
"django-syncdb"
] | My second not-so-adept question of the day: I have a django project with four installed apps. When I run manage.py syndb, it only creates tables for two of them. To my knowledge, there are no problems in any of my models files, and all the apps are specified in INSTALLED\_APPS in my settings file. Manage.py syndb just ... | I think I ran across something similar.
I had an issue where a model wasn't being reset.
In this case it turned out that there was an error in my models that wasn't being spit out.
Although I think syncdb, when run, spit out some kind of error.
In any case try to import your models file from the shell and see if you... |
Matplotlib Legend for Scatter with custom colours | 1,435,535 | 10 | 2009-09-16T21:20:11Z | 1,435,977 | 9 | 2009-09-16T23:06:52Z | [
"python",
"charts",
"matplotlib"
] | I'm a bit of newbie at this and am trying to create a scatter chart with custom bubble sizes and colours. The chart displays fine but how do I get a legend saying what the colours refer to. This is as far as I've got:
```
inc = []
out = []
bal = []
col = []
fig=Figure()
ax=fig.add_subplot(111)
inc = (30000,20000,700... | Maybe this [example](http://en.wikipedia.org/wiki/File%3aWeight_Growth_of_RN_First_Rate_Line-of-Battle_Ships_1630-1875.svg) is helpful.
In general, the items in the legend are related with some kind of *plotted object*. The `scatter` function/method treats all circles as a single object, see:
```
print type(ax.scatte... |
Python - Iterate over all classes | 1,436,384 | 2 | 2009-09-17T02:03:31Z | 1,436,451 | 9 | 2009-09-17T02:34:35Z | [
"python",
"google-app-engine",
"loops"
] | How can I iterate over a list of all classes loaded in memory?
I'm thinking of doing it for a backup, looking for all classes inheriting from db.Model (Google App Engine).
Thanks,
Neal Walters | In "normal" Python, you can reach all objects via the `gc.getobjects()` function of the `gc` standard library module; it's then very easy to loop on them, checking which one are classes (rather than instances or anything else -- I do believe you mean *instances* of classes, but you can very easily get the classes thems... |
Python: Passing a class name as a parameter to a function? | 1,436,444 | 21 | 2009-09-17T02:32:43Z | 1,436,461 | 13 | 2009-09-17T02:37:09Z | [
"python",
"function"
] | ```
class TestSpeedRetrieval(webapp.RequestHandler):
"""
Test retrieval times of various important records in the BigTable database
"""
def get(self):
commandValidated = True
beginTime = time()
itemList = Subscriber.all().fetch(1000)
for item in itemList:
pass
endTi... | ```
class TestSpeedRetrieval(webapp.RequestHandler):
"""
Test retrieval times of various important records in the BigTable database
"""
def __init__(self, cls):
self.cls = cls
def get(self):
commandValidated = True
beginTime = time()
itemList = self.cls.all().fetch(1000)
for... |
Python: Passing a class name as a parameter to a function? | 1,436,444 | 21 | 2009-09-17T02:32:43Z | 1,436,462 | 9 | 2009-09-17T02:37:23Z | [
"python",
"function"
] | ```
class TestSpeedRetrieval(webapp.RequestHandler):
"""
Test retrieval times of various important records in the BigTable database
"""
def get(self):
commandValidated = True
beginTime = time()
itemList = Subscriber.all().fetch(1000)
for item in itemList:
pass
endTi... | If you pass the class object directly, as in your code between "like this" and "or",
you can get its name as the `__name__` attribute.
Starting with the name (as in your code *after* "or") makes it REALLY hard (and not unambiguous) to retrieve the class object unless you have some indication about where the class obje... |
Difference between __str__ and __repr__ in Python | 1,436,703 | 1,363 | 2009-09-17T04:27:45Z | 1,436,721 | 99 | 2009-09-17T04:35:36Z | [
"python"
] | What is the difference between `__str__` and `__repr__` in Python? | **`__repr__`**: representation of python object usually eval will convert it back to that object
**`__str__`**: is whatever you think is that object in text form
e.g.
```
>>> s="""w'o"w"""
>>> repr(s)
'\'w\\\'o"w\''
>>> str(s)
'w\'o"w'
>>> eval(str(s))==s
Traceback (most recent call last):
File "<stdin>", line 1, ... |
Difference between __str__ and __repr__ in Python | 1,436,703 | 1,363 | 2009-09-17T04:27:45Z | 1,436,756 | 215 | 2009-09-17T04:49:40Z | [
"python"
] | What is the difference between `__str__` and `__repr__` in Python? | Unless you specifically act to ensure otherwise, most classes don't have helpful results for either:
```
>>> class Sic(object): pass
...
>>> print str(Sic())
<__main__.Sic object at 0x8b7d0>
>>> print repr(Sic())
<__main__.Sic object at 0x8b7d0>
>>>
```
As you see -- no difference, and no info beyond the class and o... |
Difference between __str__ and __repr__ in Python | 1,436,703 | 1,363 | 2009-09-17T04:27:45Z | 1,438,297 | 205 | 2009-09-17T11:35:13Z | [
"python"
] | What is the difference between `__str__` and `__repr__` in Python? | My rule of thumb: `__repr__` is for developers, `__str__` is for customers. |
Difference between __str__ and __repr__ in Python | 1,436,703 | 1,363 | 2009-09-17T04:27:45Z | 2,626,364 | 1,475 | 2010-04-13T00:56:52Z | [
"python"
] | What is the difference between `__str__` and `__repr__` in Python? | Alex summarized well but, surprisingly, was too succinct.
First, let me reiterate the main points in Alexâs post:
* The default implementation is useless (itâs hard to think of one which wouldnât be, but yeah)
* `__repr__` goal is to be unambiguous
* `__str__` goal is to be readable
* Containerâs `__str__` us... |
Difference between __str__ and __repr__ in Python | 1,436,703 | 1,363 | 2009-09-17T04:27:45Z | 19,597,196 | 55 | 2013-10-25T18:38:52Z | [
"python"
] | What is the difference between `__str__` and `__repr__` in Python? | > In short, the goal of `__repr__` is to be unambiguous and `__str__` is to be
> readable.
Here is a good example:
```
>>> import datetime
>>> today = datetime.datetime.now()
>>> str(today)
'2012-03-14 09:21:58.130922'
>>> repr(today)
'datetime.datetime(2012, 3, 14, 9, 21, 58, 130922)'
```
Read this documentation fo... |
Difference between __str__ and __repr__ in Python | 1,436,703 | 1,363 | 2009-09-17T04:27:45Z | 28,132,458 | 38 | 2015-01-25T02:01:30Z | [
"python"
] | What is the difference between `__str__` and `__repr__` in Python? | > # What is the difference between `__str__` and `__repr__` in Python?
`__str__` (read as "dunder (double-underscore) string") and `__repr__` (read as "dunder-repper" (for "representation")) are both special methods that return strings based on the state of the object.
`__repr__` provides backup behavior if `__str__`... |
Python sort() method on list vs builtin sorted() function | 1,436,962 | 26 | 2009-09-17T06:07:36Z | 1,436,999 | 7 | 2009-09-17T06:20:30Z | [
"python",
"sorting"
] | I know that `__builtin__` sorted() function works on any iterable. But can someone explain this huge (10x) performance difference between anylist.sort() vs sorted(anylist) ? Also, please point out if I am doing anything wrong with way this is measured.
```
"""
Example Output:
$ python list_sort_timeit.py
Using sort m... | Because list.sort does in place sorting, so first time it sorts but next time you are sorting the sorted list.
e.g. try this and you will get same results
in timeit case most of the time is spent is copying and sorted also does one more copy
```
import time
import random
test_list1=random.sample(xrange(1000),1000)
te... |
Python sort() method on list vs builtin sorted() function | 1,436,962 | 26 | 2009-09-17T06:07:36Z | 1,437,009 | 40 | 2009-09-17T06:23:30Z | [
"python",
"sorting"
] | I know that `__builtin__` sorted() function works on any iterable. But can someone explain this huge (10x) performance difference between anylist.sort() vs sorted(anylist) ? Also, please point out if I am doing anything wrong with way this is measured.
```
"""
Example Output:
$ python list_sort_timeit.py
Using sort m... | Your error in measurement is as follows: after your first call of `test_list1.sort()`, that list object IS sorted -- and Python's sort, aka [timsort](http://svn.python.org/projects/python/trunk/Objects/listsort.txt), is **wickedly fast** on already sorted lists!!! That's the most frequent error in using `timeit` -- ina... |
How to install iPython on Snow Leopard | 1,437,402 | 10 | 2009-09-17T08:11:26Z | 1,437,514 | 21 | 2009-09-17T08:37:58Z | [
"python",
"osx",
"ipython"
] | Does iPython work on Mac OS X 10.6.1 Snow Leopard? I'm python noob, how can I install iPython on my Mac? Links? suggestions?
Thanks | To install with the Apple-supplied Python in 10.6:
```
$ sudo /usr/bin/easy_install-2.6 ipython
```
To use:
```
$ ipython
``` |
How to install iPython on Snow Leopard | 1,437,402 | 10 | 2009-09-17T08:11:26Z | 2,341,928 | 8 | 2010-02-26T13:32:49Z | [
"python",
"osx",
"ipython"
] | Does iPython work on Mac OS X 10.6.1 Snow Leopard? I'm python noob, how can I install iPython on my Mac? Links? suggestions?
Thanks | I may add that running
```
$ sudo /usr/bin/easy_install-2.6 readline ipython
```
gives you the ability to use tab completion to see the attributes of a module.... |
Why does Psyco use a lot of memory? | 1,438,220 | 5 | 2009-09-17T11:18:42Z | 1,438,279 | 10 | 2009-09-17T11:31:48Z | [
"python",
"memory",
"compiler-construction",
"jit",
"psyco"
] | [Psyco](http://psyco.sourceforge.net/) is a specialising compiler for Python. The [documentation states](http://psyco.sourceforge.net/psycoguide/memlimits.html)
> Psyco can and will use large amounts of memory.
What are the main reasons for this memory usage? Is substantial memory overhead a feature of JIT compilers ... | From psyco website "The difference with the traditional approach to JIT compilers is that Psyco writes **several version of the same blocks** (a block is a bit of a function), which are optimized by being specialized to some kinds of variables (a "kind" can mean a type, but it is more general)" |
Installing Python Imaging Library (PIL) on Snow Leopard with updated Python 2.6.2 | 1,438,270 | 26 | 2009-09-17T11:29:17Z | 1,439,772 | 11 | 2009-09-17T16:02:09Z | [
"python",
"osx-snow-leopard",
"python-imaging-library"
] | I have a fresh install (started with a wiped drive) of Snow Leopard with the developer tools installed during the Snow Leopard installation.
I then installed Python 2.6.2, replacing the Snow Leopard default python 2.6.1. I've tried to install PIL by:
1. `easy_install`
2. `pip`
3. downloading source and running `pytho... | The python.org Python was built with an earlier gcc. Try using gcc-4.0 instead of SL's default of 4.2:
```
export CC=/usr/bin/gcc-4.0
```
See similar problem [here](http://thread.gmane.org/gmane.comp.python.apple/16087).
That gets past the stdarg problem. You may then run into later build problems with various depen... |
Installing Python Imaging Library (PIL) on Snow Leopard with updated Python 2.6.2 | 1,438,270 | 26 | 2009-09-17T11:29:17Z | 1,439,865 | 7 | 2009-09-17T16:19:14Z | [
"python",
"osx-snow-leopard",
"python-imaging-library"
] | I have a fresh install (started with a wiped drive) of Snow Leopard with the developer tools installed during the Snow Leopard installation.
I then installed Python 2.6.2, replacing the Snow Leopard default python 2.6.1. I've tried to install PIL by:
1. `easy_install`
2. `pip`
3. downloading source and running `pytho... | # Modified Answer
Here are the steps that I took to successfully install PIL on Mac OS X 10.6 (without using MacPorts or Fink).
1. Install readline
```
cd ~/src
curl -O ftp://ftp.cwru.edu/pub/bash/readline-6.0.tar.gz
tar -xvzf readline-6.0.tar.gz
cd readline-6.0
./configure
make
sudo make... |
Installing Python Imaging Library (PIL) on Snow Leopard with updated Python 2.6.2 | 1,438,270 | 26 | 2009-09-17T11:29:17Z | 2,222,294 | 18 | 2010-02-08T14:42:02Z | [
"python",
"osx-snow-leopard",
"python-imaging-library"
] | I have a fresh install (started with a wiped drive) of Snow Leopard with the developer tools installed during the Snow Leopard installation.
I then installed Python 2.6.2, replacing the Snow Leopard default python 2.6.1. I've tried to install PIL by:
1. `easy_install`
2. `pip`
3. downloading source and running `pytho... | The problem I ran into was that PIL was being compiled against PowerPC architecture (-arch ppc).
Do this before setup/build/compile:
```
export ARCHFLAGS="-arch i386"
```
(Assuming you're on i386) |
How to use Python plugin reCaptcha client for validation? | 1,440,239 | 15 | 2009-09-17T17:32:07Z | 1,440,429 | 24 | 2009-09-17T18:06:28Z | [
"python",
"validation",
"plugins",
"captcha",
"recaptcha"
] | I want to make a captcha validation.
I get the key from the [recaptcha website](http://recaptcha.net/) and already succeed to put the public key to load the webpage with the challenge.
```
<script type="text/javascript"
src="http://api.recaptcha.net/challenge?k=<your_public_key>">
</script>
<noscript>
<iframe ... | It is quite straightforward.
This is an example from a trivial trac plugin I'm using:
```
from recaptcha.client import captcha
if req.method == 'POST':
response = captcha.submit(
req.args['recaptcha_challenge_field'],
req.args['recaptcha_response_field'],
self.private_key,
req.remo... |
Class usage in Python | 1,440,434 | 7 | 2009-09-17T18:07:33Z | 1,440,467 | 15 | 2009-09-17T18:13:28Z | [
"python",
"oop",
"class-design",
"procedural-programming"
] | I write a lot of scripts in Python to analyze and plot experimental data as well as write simple simulations to test how theories fit the data. The scripts tend to be very procedural; calculate some property, calculate some other property, plot properties, analyze plot...
Rather than just writing a procedure, would th... | By using Object Oriented Programming, you will have objects, that have associated functions, that are (should) be the only way to modify its properties (internal variables).
It was common to have functions called `trim_string(string)`, while with a `string` class you could do `string.trim()`. The difference is noticea... |
Maximum size of object that can be saved in memcached with memcache.py | 1,440,722 | 20 | 2009-09-17T19:00:13Z | 1,440,773 | 30 | 2009-09-17T19:07:28Z | [
"python",
"memcached"
] | I need to return a rather big file (11MB) to the user. For certain reasons, I can't just provide a direct url to the file (<http://www.sample.com/mybigfile.exe>); instead it must be accessed through code.
Instead of having to read it from disk over and over, I thought of saving it in memcached (if this is not a good i... | There are two entries about that in the [memcached FAQ](http://docs.oracle.com/cd/E17952_01/refman-5.6-en/ha-memcached-faq.html) :
* [What is the maximum size of an object you can store in memcached? Is that configurable?](http://docs.oracle.com/cd/E17952_01/refman-5.6-en/ha-memcached-faq.html#qandaitem-17-6-5-1-2)
T... |
Maximum size of object that can be saved in memcached with memcache.py | 1,440,722 | 20 | 2009-09-17T19:00:13Z | 11,730,559 | 27 | 2012-07-30T22:22:29Z | [
"python",
"memcached"
] | I need to return a rather big file (11MB) to the user. For certain reasons, I can't just provide a direct url to the file (<http://www.sample.com/mybigfile.exe>); instead it must be accessed through code.
Instead of having to read it from disk over and over, I thought of saving it in memcached (if this is not a good i... | As of memcache 1.4.2, this is a user-configurable parameter:
<http://code.google.com/p/memcached/wiki/ReleaseNotes142>
> Configurable maximum item size
>
> Many people have asked for memcached to be able to store items larger
> than 1MB, while it's generally recommended that one not do this, it is
> now supported on ... |
Maximum size of object that can be saved in memcached with memcache.py | 1,440,722 | 20 | 2009-09-17T19:00:13Z | 18,182,563 | 18 | 2013-08-12T08:32:25Z | [
"python",
"memcached"
] | I need to return a rather big file (11MB) to the user. For certain reasons, I can't just provide a direct url to the file (<http://www.sample.com/mybigfile.exe>); instead it must be accessed through code.
Instead of having to read it from disk over and over, I thought of saving it in memcached (if this is not a good i... | To summarise the necessary steps:
1) Update Memcache to version 1.4.2 or later.
2) Add the flag -I 15M (or however many megabytes) to your memcache run command.
That's either command line, or in Ubuntu, add the line
```
-I 15M
```
to anywhere in /etc/memcached.conf and restart the service.
3) Add the necessary fl... |
Finding the command for a specific PID in Linux from Python | 1,440,941 | 5 | 2009-09-17T19:44:09Z | 1,440,969 | 7 | 2009-09-17T19:49:53Z | [
"python",
"linux",
"process"
] | I'd like to know if it's possible to find out the "command" that a PID is set to. When I say command, I mean what you see in the last column when you run the command "top" in a linux shell. I'd like to get this information from Python somehow when I have a specific PID.
Any help would be great. Thanks. | ### Look in `/proc/$PID/cmdline` |
Finding the command for a specific PID in Linux from Python | 1,440,941 | 5 | 2009-09-17T19:44:09Z | 1,441,057 | 8 | 2009-09-17T20:06:02Z | [
"python",
"linux",
"process"
] | I'd like to know if it's possible to find out the "command" that a PID is set to. When I say command, I mean what you see in the last column when you run the command "top" in a linux shell. I'd like to get this information from Python somehow when I have a specific PID.
Any help would be great. Thanks. | PLEASE, do not use `/proc` filesystem in production code. Instead, use well-defined POSIX interfaces, such as glibc calls and standard shell commands! Make the Linux world more standardized, it really needs to!
What you need is well achieved by invoking a shell command
```
ps -p <YOUR PID> -o cmd h
```
No parsing is... |
Plotting color map with zip codes in R or Python | 1,441,717 | 25 | 2009-09-17T22:50:42Z | 1,442,254 | 9 | 2009-09-18T01:51:40Z | [
"python",
"graphics",
"zipcode"
] | I have some US demographic and firmographic data.
I would like to plot zipcode areas in a state or a smaller region (e.g. city). Each area would be annotated by color and/or text specific to that area. The output would be similar to <http://maps.huge.info/> but a) with annotated text; b) pdf output; c) scriptable in ... | There are many ways to do this in R (see the [spatial view](http://cran.r-project.org/web/views/Spatial.html)); many of these [depend on the "maps" package](http://cran.r-project.org/web/packages/maps/index.html).
* Check out this [cool example of the US 2004 election](http://www.ai.rug.nl/~hedderik/R/US2004/). It end... |
Plotting color map with zip codes in R or Python | 1,441,717 | 25 | 2009-09-17T22:50:42Z | 1,446,144 | 33 | 2009-09-18T18:21:07Z | [
"python",
"graphics",
"zipcode"
] | I have some US demographic and firmographic data.
I would like to plot zipcode areas in a state or a smaller region (e.g. city). Each area would be annotated by color and/or text specific to that area. The output would be similar to <http://maps.huge.info/> but a) with annotated text; b) pdf output; c) scriptable in ... | I am assuming you want static maps.

1) Get the shapefiles of the [zip](http://www.census.gov/geo/www/cob/zt%5Fmetadata.html) boundaries and [state](http://www.census.gov/geo/www/cob/st2000.html) boundaries at census.gov:
2) Use the plot.heat function I posted in t... |
Python imaging alternatives | 1,441,967 | 10 | 2009-09-18T00:05:57Z | 1,442,062 | 16 | 2009-09-18T00:37:44Z | [
"python",
"command-line",
"libraries",
"imaging"
] | I have python code that needs to do just a couple simple things to photographs: crop, resize, and overlay a watermark. I've used PIL, and the resample/resize results are TERRIBLE. I've used imagemagick, and the interface and commands were designed by packaging a cat in a box, and then repeatedly throwing it down a set ... | > I've used PIL, and the resample/resize results are TERRIBLE.
They shouldn't be, as long as you:
1. use only Image.ANTIALIAS filtering for downscaling operations
2. use only Image.BICUBIC filtering for upscaling operations.
3. remember to convert to 'RGB' colour mode before the resize if you are using a paletted ima... |
Subdomains and Logins | 1,442,017 | 4 | 2009-09-18T00:19:48Z | 1,442,029 | 10 | 2009-09-18T00:23:13Z | [
"python",
"django",
"login",
"subdomain",
"login-control"
] | If you multiple subdomains e.g.:
> sub1.domain\_name.com
>
> sub2.domain\_name.com
Is there a way to have a user be able to log into both of these without issues and double login issue?
The platform is Python, Django. | Without information regarding what platform you are using, it is difficult to say. If you use cookies to store authentication information, and you are using subdomains as you describe, then you can force the cookie to be issued for the highest level domain, e.g. domain\_name.com.
This will be accessable by both sub1 a... |
Full-featured date and time library | 1,442,264 | 7 | 2009-09-18T02:00:01Z | 1,442,519 | 11 | 2009-09-18T03:55:47Z | [
"python",
"c",
"datetime"
] | I'm wondering if anyone knows of a good date and time library that has correctly-implemented features like the following:
* **Microsecond resolution**
* **Daylight savings**
+ *Example:* it knows that 2:30am did not exist in the US on 8 March 2009 for timezones that respect daylight savings.
+ I should be able to ... | Python's standard library's `datetime` module is deliberately limited to non-controversial aspects that aren't changing all the time by legislative fiat -- that's why it deliberately excludes direct support for timezones, DST, fuzzy parsing and ill-defined arithmetic (such as "one month later"...) and the like. On top ... |
Python program to split a list into two lists with alternating elements | 1,442,782 | 11 | 2009-09-18T05:53:08Z | 1,442,788 | 7 | 2009-09-18T05:55:46Z | [
"python",
"algorithm",
"list"
] | Can you make it more simple/elegant?
```
def zigzag(seq):
"""Return two sequences with alternating elements from `seq`"""
x, y = [], []
p, q = x, y
for e in seq:
p.append(e)
p, q = q, p
return x, y
``` | ```
def zigzag(seq):
return seq[::2], seq[1::2]
``` |
Python program to split a list into two lists with alternating elements | 1,442,782 | 11 | 2009-09-18T05:53:08Z | 1,442,794 | 34 | 2009-09-18T05:57:45Z | [
"python",
"algorithm",
"list"
] | Can you make it more simple/elegant?
```
def zigzag(seq):
"""Return two sequences with alternating elements from `seq`"""
x, y = [], []
p, q = x, y
for e in seq:
p.append(e)
p, q = q, p
return x, y
``` | If `seq`, as you say, is a list, then:
```
def zigzag(seq):
return seq[::2], seq[1::2]
```
If `seq` is a totally generic iterable, such as possibly a generator:
```
def zigzag(seq):
results = [], []
for i, e in enumerate(seq):
results[i%2].append(e)
return results
``` |
Python program to split a list into two lists with alternating elements | 1,442,782 | 11 | 2009-09-18T05:53:08Z | 1,443,595 | 9 | 2009-09-18T10:04:10Z | [
"python",
"algorithm",
"list"
] | Can you make it more simple/elegant?
```
def zigzag(seq):
"""Return two sequences with alternating elements from `seq`"""
x, y = [], []
p, q = x, y
for e in seq:
p.append(e)
p, q = q, p
return x, y
``` | This takes an iterator and returns two iterators:
```
import itertools
def zigzag(seq):
t1,t2 = itertools.tee(seq)
even = itertools.islice(t1,0,None,2)
odd = itertools.islice(t2,1,None,2)
return even,odd
```
If you prefer lists then you can `return list(even),list(odd)`. |
Lauch default editor (like 'webbrowser' module) | 1,442,841 | 7 | 2009-09-18T06:18:43Z | 1,443,128 | 10 | 2009-09-18T08:01:24Z | [
"python",
"command-line",
"editor"
] | Is there a simple way to lauch the systems default editor from a Python command-line tool, like the [webbrowser](http://docs.python.org/library/webbrowser.html) module? | Under windows you can simply "execute" the file and the default action will be taken:
`os.system('c:/tmp/sample.txt')`
For this example a default editor will spawn. Under UNIX there is an environment variable called `EDITOR`, so you need to use something like:
`os.system('%s %s' % (os.getenv('EDITOR'), filename))` |
Completely wrap an object in Python | 1,443,129 | 15 | 2009-09-18T08:01:42Z | 1,445,289 | 27 | 2009-09-18T15:30:42Z | [
"python",
"reflection"
] | I am wanting to completely wrap an object so that all attribute and method requests get forwarded to the object it's wrapping, but also overriding any methods or variables that I want, as well as providing some of my own methods. This wrapper class should appear 100% as the existing class (`isinstance` must act as if i... | The simplest way in most cases is probably:
```
class ObjectWrapper(BaseClass):
def __init__(self, baseObject):
self.__class__ = type(baseObject.__class__.__name__,
(self.__class__, baseObject.__class__),
{})
self.__dict__ = baseObject.__d... |
Django : Iterate over a query set without cache | 1,443,279 | 5 | 2009-09-18T08:40:47Z | 1,443,304 | 11 | 2009-09-18T08:49:48Z | [
"python",
"django",
"caching"
] | I have a dumb simple loop
```
for alias in models.Alias.objects.all() :
alias.update_points()
```
but looking into the django QuerySet it seems to keep around a `_result_cache` of all the previous results. This is eating Gigs and Gigs of my machine and eventually everything blows up.
How can I throw away all the... | Use the queryset's [`iterator()`](http://docs.djangoproject.com/en/dev/ref/models/querysets/#iterator) method to return the models in chunks, without populating the result cache:
```
for alias in models.Alias.objects.iterator() :
alias.update_points()
``` |
How to read a structure containing an array using Python's ctypes and readinto? | 1,444,159 | 4 | 2009-09-18T12:05:54Z | 1,444,339 | 8 | 2009-09-18T12:43:48Z | [
"python",
"ctypes"
] | We have some binary files created by a C program.
One type of file is created by calling fwrite to write the following C structure to file:
```
typedef struct {
unsigned long int foo;
unsigned short int bar;
unsigned short int bow;
} easyStruc;
```
In Python, I read the structs of this file as follows:
... | According to this [documentation page](http://docs.activestate.com/activepython/3.1/python/library/ctypes.html) (section: 15.15.1.13. Arrays), it should be something like:
```
class strucWithArrays(Structure):
_fields_ = [
("foo", c_ulong),
("barFloat", c_float * 4),
("bowFloat", c_float * 17)]
```
Check that... |
Differences between Framework and non-Framework builds of Python on Mac OS X | 1,444,543 | 44 | 2009-09-18T13:27:54Z | 1,445,711 | 11 | 2009-09-18T16:53:24Z | [
"python",
"osx",
"frameworks"
] | ### Question
What are the differences between a Framework build and a non-Framework build (i.e., standard UNIX build) of Python on Mac OS X? Also, what are the advantages and disadvantages of each?
### Preliminary Research
Here is the information that I found prior to posting this question:
* [[Pythonmac-SIG] Why i... | You've already listed all important advantages of making a framework (congratulations for excellent research and reporting thereof!); the only flip side is that it's harder to arrange to build one properly, but if you take your clues from the examples in the installer you quote, it should be doable.
BTW, what's wrong ... |
Python: module for creating PID-based lockfile? | 1,444,790 | 16 | 2009-09-18T14:10:52Z | 1,444,850 | 9 | 2009-09-18T14:18:47Z | [
"python",
"pid",
"lockfile"
] | I'm writing a Python script that may or may not (depending on a bunch of things) run for a long time, and I'd like to make sure that multiple instances (started via cron) don't step on each others toes. The logical way to do this seems to be a PID-based lockfile⦠But I don't want to re-invent the wheel if there is al... | This might be of help to you: [lockfile](http://pypi.python.org/pypi/zc.lockfile) |
Python: module for creating PID-based lockfile? | 1,444,790 | 16 | 2009-09-18T14:10:52Z | 1,444,860 | 8 | 2009-09-18T14:19:54Z | [
"python",
"pid",
"lockfile"
] | I'm writing a Python script that may or may not (depending on a bunch of things) run for a long time, and I'd like to make sure that multiple instances (started via cron) don't step on each others toes. The logical way to do this seems to be a PID-based lockfile⦠But I don't want to re-invent the wheel if there is al... | If you can use GPLv2, Mercurial has a module for that:
<http://bitbucket.org/mirror/mercurial/src/tip/mercurial/lock.py>
Example usage:
```
from mercurial import error, lock
try:
l = lock.lock("/path/to/lock", timeout=600) # wait at most 10 minutes
# do something
except error.LockHeld:
# couldn't take ... |
What is the best-maintained generic functions implementation for Python? | 1,445,065 | 7 | 2009-09-18T14:54:28Z | 1,445,119 | 7 | 2009-09-18T15:02:01Z | [
"python",
"generics"
] | A [generic function](http://en.wikipedia.org/wiki/Generic%5Ffunctions) is dispatched based on the type of all its arguments. The programmer defines several implementations of a function. The correct one is chosen at call time based on the types of its arguments. This is useful for object adaptation among other things. ... | I'd recommend the [PEAK-Rules](http://pypi.python.org/pypi/PEAK-Rules) library by P. Eby. By the same author (deprecated though) is the [RuleDispatch](http://peak.telecommunity.com/) package (the predecessor of PEAK-Rules). The latter being no longer maintained IIRC.
PEAK-Rules has a lot of nice features, one being, t... |
Why can't a Python class definition assign a closure variable to itself? | 1,445,207 | 2 | 2009-09-18T15:17:37Z | 1,445,231 | 9 | 2009-09-18T15:21:23Z | [
"python",
"closures"
] | Why doesn't the following work in Python?
```
def make_class(a):
class A(object):
a=a
return A
``` | works just fine:
```
>>> def make_class(a):
class A(object):
_a=a
return A
>>> make_class('df')
<class '__main__.A'>
>>> make_class('df')._a
'df'
```
btw, `function` is not a reserved keyword in Python. |
How can I find out why subprocess.Popen wait() waits forever if stdout=PIPE? | 1,445,627 | 12 | 2009-09-18T16:30:59Z | 1,445,647 | 28 | 2009-09-18T16:36:04Z | [
"python",
"subprocess"
] | I have a program that writes to stdout and possibly stderr. I want to run it from python, capturing the stdout and stderr. My code looks like:
```
from subprocess import *
p = Popen( exe, shell=TRUE, stdout=PIPE, stderr=PIPE )
rtrncode = p.wait()
```
For a couple of programs, this works fine, but when I added a new ... | When a pipe's buffer fills up (typically 4KB or so), the writing process stops until a reading process has read some of the data in question; but here you're reading nothing until the subprocess is done, hence the deadlock. [The docs](http://docs.python.org/library/subprocess.html#subprocess.Popen.wait) on `wait` put i... |
Passing Python Data to JavaScript via Django | 1,445,989 | 39 | 2009-09-18T17:52:53Z | 1,446,170 | 58 | 2009-09-18T18:26:20Z | [
"javascript",
"python",
"django"
] | I'm using Django and Apache to serve webpages. My JavaScript code currently includes a data object with values to be displayed in various HTML widgets based on the user's selection from a menu of choices. I want to derive these data from a Python dictionary. I think I know how to embed the JavaScript code in the HTML, ... | I recommend against putting much JavaScript in your Django templates - it tends to be hard to write and debug, particularly as your project expands. Instead, try writing all of your JavaScript in a separate script file which your template loads and simply including just a JSON data object in the template. This allows y... |
Passing Python Data to JavaScript via Django | 1,445,989 | 39 | 2009-09-18T17:52:53Z | 13,297,018 | 24 | 2012-11-08T20:13:26Z | [
"javascript",
"python",
"django"
] | I'm using Django and Apache to serve webpages. My JavaScript code currently includes a data object with values to be displayed in various HTML widgets based on the user's selection from a menu of choices. I want to derive these data from a Python dictionary. I think I know how to embed the JavaScript code in the HTML, ... | For anyone who might be having a problems with this, be sure you are rendering your json object under safe mode in the template. You can manually set this like this
```
<script type="text/javascript">
data_from_django = {{ my_data|safe }};
widget.init(data_from_django);
</script>
``` |
Python 2.6 send connection object over Queue / Pipe / etc | 1,446,004 | 11 | 2009-09-18T17:55:30Z | 1,446,407 | 7 | 2009-09-18T19:20:09Z | [
"python",
"queue",
"multiprocessing",
"pipe",
"pickle"
] | Given [this bug (Python Issue 4892)](http://bugs.python.org/issue4892) that gives rise to the following error:
```
>>> import multiprocessing
>>> multiprocessing.allow_connection_pickling()
>>> q = multiprocessing.Queue()
>>> p = multiprocessing.Pipe()
>>> q.put(p)
>>> q.get()
Traceback (most recent call last):
File... | Here's roughly what I did:
```
# Producer
from multiprocessing.reduction import reduce_connection
from multiprocessing import Pipe
# Producer and Consumer share the Queue we call queue
def handle(queue):
reader, writer = Pipe()
pickled_writer = pickle.dumps(reduce_connection(writer))
queue.put(pickled_wri... |
Python 2.6 send connection object over Queue / Pipe / etc | 1,446,004 | 11 | 2009-09-18T17:55:30Z | 4,719,933 | 8 | 2011-01-18T02:24:23Z | [
"python",
"queue",
"multiprocessing",
"pipe",
"pickle"
] | Given [this bug (Python Issue 4892)](http://bugs.python.org/issue4892) that gives rise to the following error:
```
>>> import multiprocessing
>>> multiprocessing.allow_connection_pickling()
>>> q = multiprocessing.Queue()
>>> p = multiprocessing.Pipe()
>>> q.put(p)
>>> q.get()
Traceback (most recent call last):
File... | (What I believe is) A better method, after some playing around (I was having the same problem. Wanted to pass a pipe through a pipe.) before discovering this post:
```
>>> from multiprocessing import Pipe, reduction
>>> i, o = Pipe()
>>> reduced = reduction.reduce_connection(i)
>>> newi = reduced[0](*reduced[1])
>>> n... |
How to find out if Python is compiled with UCS-2 or UCS-4? | 1,446,347 | 45 | 2009-09-18T19:06:49Z | 1,446,411 | 17 | 2009-09-18T19:20:44Z | [
"python",
"unicode",
"ucs2"
] | Just what the title says.
```
$ ./configure --help | grep -i ucs
--enable-unicode[=ucs[24]]
```
Searching the official documentation, I found this:
> **[sys.maxunicode](http://docs.python.org/3.1/library/sys.html#sys.maxunicode)**: An integer giving the
> largest supported code point for a
> Unicode character. The... | It's 0xFFFF (or 65535) for UCS-2, and 0x10FFFF (or 1114111) for UCS-4:
```
Py_UNICODE
PyUnicode_GetMax(void)
{
#ifdef Py_UNICODE_WIDE
return 0x10FFFF;
#else
/* This is actually an illegal character, so it should
not be passed to unichr. */
return 0xFFFF;
#endif
}
```
The maximum character in UCS-4 ... |
How to find out if Python is compiled with UCS-2 or UCS-4? | 1,446,347 | 45 | 2009-09-18T19:06:49Z | 1,446,456 | 79 | 2009-09-18T19:33:45Z | [
"python",
"unicode",
"ucs2"
] | Just what the title says.
```
$ ./configure --help | grep -i ucs
--enable-unicode[=ucs[24]]
```
Searching the official documentation, I found this:
> **[sys.maxunicode](http://docs.python.org/3.1/library/sys.html#sys.maxunicode)**: An integer giving the
> largest supported code point for a
> Unicode character. The... | When built with --enable-unicode=ucs4:
```
>>> import sys
>>> print sys.maxunicode
1114111
```
When built with --enable-unicode=ucs2:
```
>>> import sys
>>> print sys.maxunicode
65535
``` |
How to find out if Python is compiled with UCS-2 or UCS-4? | 1,446,347 | 45 | 2009-09-18T19:06:49Z | 1,450,155 | 9 | 2009-09-20T02:50:11Z | [
"python",
"unicode",
"ucs2"
] | Just what the title says.
```
$ ./configure --help | grep -i ucs
--enable-unicode[=ucs[24]]
```
Searching the official documentation, I found this:
> **[sys.maxunicode](http://docs.python.org/3.1/library/sys.html#sys.maxunicode)**: An integer giving the
> largest supported code point for a
> Unicode character. The... | I had this same issue once. I documented it for myself on my wiki at
<http://arcoleo.org/dsawiki/Wiki.jsp?page=Python%20UTF%20-%20UCS2%20or%20UCS4>
I wrote -
```
import sys
sys.maxunicode > 65536 and 'UCS4' or 'UCS2'
``` |
Embed a spreadsheet/table in a PyGTK application? | 1,447,187 | 2 | 2009-09-18T23:10:48Z | 1,450,766 | 12 | 2009-09-20T10:49:20Z | [
"python",
"pygtk",
"spreadsheet"
] | In my application, we want to present the user with a typical spreadsheet/table (OO.O/Excel-style), and then pull out the values and do something with them internally.
Is there a preexisting widget for PyGTK that does this? The [PyGTK FAQ](http://faq.pygtk.org/index.py?req=all#19.14) mentions [GtkGrid](http://www.sice... | `GtkGrid` is deprecated in favor of the more powerful and more customizable [`GtkTreeView`](http://library.gnome.org/devel/pygtk/stable/class-gtktreeview.html).
It can display trees and lists. To make it work like a table, you must define a [`ListStore`](http://library.gnome.org/devel/pygtk/stable/class-gtkliststore.h... |
Format floats with standard json module | 1,447,287 | 53 | 2009-09-19T00:08:37Z | 1,447,562 | 7 | 2009-09-19T02:40:29Z | [
"python",
"json",
"formatting",
"floating-point"
] | I am using the standard [json module](http://docs.python.org/library/json.html) in python 2.6 to serialize a list of floats. However, I'm getting results like this:
```
>>> import json
>>> json.dumps([23.67, 23.97, 23.87])
'[23.670000000000002, 23.969999999999999, 23.870000000000001]'
```
I want the floats to be form... | You can do what you need to do, but it isn't documented:
```
>>> import json
>>> json.encoder.FLOAT_REPR = lambda f: ("%.2f" % f)
>>> json.dumps([23.67, 23.97, 23.87])
'[23.67, 23.97, 23.87]'
``` |
Format floats with standard json module | 1,447,287 | 53 | 2009-09-19T00:08:37Z | 1,447,581 | 52 | 2009-09-19T02:48:41Z | [
"python",
"json",
"formatting",
"floating-point"
] | I am using the standard [json module](http://docs.python.org/library/json.html) in python 2.6 to serialize a list of floats. However, I'm getting results like this:
```
>>> import json
>>> json.dumps([23.67, 23.97, 23.87])
'[23.670000000000002, 23.969999999999999, 23.870000000000001]'
```
I want the floats to be form... | Unfortunately, I believe you have to do this by monkey-patching (which, to my opinion, indicates a design defect in the standard library `json` package). E.g., this code:
```
import json
from json import encoder
encoder.FLOAT_REPR = lambda o: format(o, '.2f')
print json.dumps(23.67)
print json.dumps([23.67, 23.97, 23... |
Format floats with standard json module | 1,447,287 | 53 | 2009-09-19T00:08:37Z | 1,733,105 | 37 | 2009-11-14T03:16:28Z | [
"python",
"json",
"formatting",
"floating-point"
] | I am using the standard [json module](http://docs.python.org/library/json.html) in python 2.6 to serialize a list of floats. However, I'm getting results like this:
```
>>> import json
>>> json.dumps([23.67, 23.97, 23.87])
'[23.670000000000002, 23.969999999999999, 23.870000000000001]'
```
I want the floats to be form... | ```
import simplejson
class PrettyFloat(float):
def __repr__(self):
return '%.15g' % self
def pretty_floats(obj):
if isinstance(obj, float):
return PrettyFloat(obj)
elif isinstance(obj, dict):
return dict((k, pretty_floats(v)) for k, v in obj.items())
elif isinstance(obj, (list... |
Format floats with standard json module | 1,447,287 | 53 | 2009-09-19T00:08:37Z | 5,574,182 | 19 | 2011-04-06T23:29:36Z | [
"python",
"json",
"formatting",
"floating-point"
] | I am using the standard [json module](http://docs.python.org/library/json.html) in python 2.6 to serialize a list of floats. However, I'm getting results like this:
```
>>> import json
>>> json.dumps([23.67, 23.97, 23.87])
'[23.670000000000002, 23.969999999999999, 23.870000000000001]'
```
I want the floats to be form... | If you're using Python 2.7, a simple solution is to simply round your floats explicitly to the desired precision.
```
>>> sys.version
'2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)]'
>>> json.dumps(1.0/3.0)
'0.3333333333333333'
>>> json.dumps(round(1.0/3.0, 2))
'0.33'
```
This works because Pyt... |
Symlinks on windows? | 1,447,575 | 25 | 2009-09-19T02:44:58Z | 1,447,591 | 8 | 2009-09-19T02:54:33Z | [
"python",
"winapi",
"symlink",
"pywin32"
] | Does anyone know of a way to make/read symbolic links across versions of win32 from Python? Ideally there should be a minimum amount of platform specific code, as I need my app to be cross platform. | Problem is, as explained e.g. [here](http://en.wikipedia.org/wiki/Symbolic%5Flink#Microsoft%5FWindows), that Windows' own support for the functionality of symbolic links varies across Windows releases, so that e.g. in Vista (with lots of work) you can get more functionality than in XP or 2000 (nothing AFAIK on other wi... |
Symlinks on windows? | 1,447,575 | 25 | 2009-09-19T02:44:58Z | 1,447,651 | 27 | 2009-09-19T03:37:05Z | [
"python",
"winapi",
"symlink",
"pywin32"
] | Does anyone know of a way to make/read symbolic links across versions of win32 from Python? Ideally there should be a minimum amount of platform specific code, as I need my app to be cross platform. | NTFS file system has junction points, i think you may use them instead
copied from my answer to [Create NTFS junction point in Python](http://stackoverflow.com/questions/1143260/create-ntfs-junction-point-in-python)
you can use python win32 API modules e.g.
```
import win32file
win32file.CreateSymbolicLink(fileSrc,... |
Symlinks on windows? | 1,447,575 | 25 | 2009-09-19T02:44:58Z | 7,924,557 | 9 | 2011-10-28T02:35:43Z | [
"python",
"winapi",
"symlink",
"pywin32"
] | Does anyone know of a way to make/read symbolic links across versions of win32 from Python? Ideally there should be a minimum amount of platform specific code, as I need my app to be cross platform. | [python ntfslink extension](https://github.com/juntalis/ntfslink-python)
Or if you want to use pywin32, you can use the previously stated method, and to read, use:
```
from win32file import *
from winioctlcon import FSCTL_GET_REPARSE_POINT
__all__ = ['islink', 'readlink']
# Win32file doesn't seem to have this attri... |
What are the best benefits of using Pinax? | 1,448,292 | 24 | 2009-09-19T10:28:01Z | 1,448,640 | 13 | 2009-09-19T14:25:29Z | [
"python",
"django",
"pinax"
] | I recently discovered [Pinax](http://pinaxproject.com/) that appear to be an django stack with added most-used apps so easy and speed up development.
I never used or heard of Pinax before and like to know if you have feedback about it. I love Django and would like to understand what are to parts of web dev Pinax helps... | Pinax is a collection of Django-Apps that have already been glued together for you with some code and sample templates.
It's not plug&play, because Django is not a CMS and Apps are not plugins, but you can get your site going really fast. You just have to remove the stuff you don't need, add other Django Apps that you... |
How to install MySQLdb (Python data access library to MySQL) on Mac OS X? | 1,448,429 | 81 | 2009-09-19T12:04:41Z | 1,448,446 | 36 | 2009-09-19T12:17:11Z | [
"python",
"mysql",
"osx"
] | I'm a Python newbie, but I've just spent a day working out how to get MySQLdb working properly, and the universe according to google includes numerous references to what a PITA it is, and an inordinate number of guides that seem to be outdated. Given that this site is intended to address these sorts of problems, and I ... | Install mysql and python via [Macports](http://guide.macports.org/) The porters have done all the difficult work.
```
sudo port install py26-mysql
sudo port install mysql5-server
```
should install what you need. (see [Stack overflow for comments re mysql server](http://stackoverflow.com/questions/1081231/macports-d... |
How to install MySQLdb (Python data access library to MySQL) on Mac OS X? | 1,448,429 | 81 | 2009-09-19T12:04:41Z | 1,448,476 | 119 | 2009-09-19T12:37:04Z | [
"python",
"mysql",
"osx"
] | I'm a Python newbie, but I've just spent a day working out how to get MySQLdb working properly, and the universe according to google includes numerous references to what a PITA it is, and an inordinate number of guides that seem to be outdated. Given that this site is intended to address these sorts of problems, and I ... | Here is the tale of my rambling experience with this problem. Would love to see it edited or generalised if you have better experience of the issue... apply a bit of that SO magic.
**Note: Comments in next paragraph applied to Snow Leopard, but not to Lion, which appears to require 64-bit MySQL**
First off, the autho... |
How to install MySQLdb (Python data access library to MySQL) on Mac OS X? | 1,448,429 | 81 | 2009-09-19T12:04:41Z | 6,025,504 | 13 | 2011-05-17T02:07:24Z | [
"python",
"mysql",
"osx"
] | I'm a Python newbie, but I've just spent a day working out how to get MySQLdb working properly, and the universe according to google includes numerous references to what a PITA it is, and an inordinate number of guides that seem to be outdated. Given that this site is intended to address these sorts of problems, and I ... | Here's another step I had to go through, after receiving an error on completing Step 9:
```
ImportError: dlopen(/Users/rick/.python-eggs/MySQL_python-1.2.3-py2.6-macosx-10.6-universal.egg-tmp/_mysql.so, 2): Library not loaded: libmysqlclient.18.dylib
sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/li... |
How to install MySQLdb (Python data access library to MySQL) on Mac OS X? | 1,448,429 | 81 | 2009-09-19T12:04:41Z | 18,178,419 | 66 | 2013-08-12T01:32:58Z | [
"python",
"mysql",
"osx"
] | I'm a Python newbie, but I've just spent a day working out how to get MySQLdb working properly, and the universe according to google includes numerous references to what a PITA it is, and an inordinate number of guides that seem to be outdated. Given that this site is intended to address these sorts of problems, and I ... | A quick and easy way for Mac OS X **10.8** (Mountain Lion), **10.9** (Mavericks), **10.10** (Yosemite), and **10.11** (El Capitan):
I assume you have XCode, it's [command line tool](https://stackoverflow.com/questions/9329243/xcode-4-4-and-later-install-command-line-tools), Python and MySQL installed.
1. Install PIP:... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.