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 force refresh of a wx.Panel? | 1,230,630 | 7 | 2009-08-05T00:40:39Z | 1,231,708 | 10 | 2009-08-05T07:41:06Z | [
"python",
"wxpython",
"refresh",
"panel"
] | I am trying to modify the controls of a Panel, have it update, then continue on with code execution. The problem seems to be that the Panel is waiting for Idle before it will refresh itself. I've tried refresh of course as well as GetSizer().Layout() and even sent a resize event to the frame using the SendSizeEvent() m... | You need to call the [`Update`](http://www.wxpython.org/docs/api/wx.Window-class.html#Update) method. |
subprocess: deleting child processes in Windows | 1,230,669 | 25 | 2009-08-05T00:53:49Z | 1,230,853 | 7 | 2009-08-05T02:12:55Z | [
"python",
"windows",
"process",
"subprocess",
"kill-process"
] | On Windows, `subprocess.Popen.terminate` calls win32's `TerminalProcess`. However, the behavior I see is that child processes of the process I am trying to terminate are still running. Why is that? How do I ensure all child processes started by the process are killed? | This is a hard thing to do. Windows does not actually store a process tree in the process space. Nor is it possible to terminate a process and specify that it's children should also die.
One way around that is to use taskkill and tell it to wack the whole tree.
Another way to do it (assuming that you are spawning the... |
subprocess: deleting child processes in Windows | 1,230,669 | 25 | 2009-08-05T00:53:49Z | 4,229,404 | 41 | 2010-11-19T21:11:59Z | [
"python",
"windows",
"process",
"subprocess",
"kill-process"
] | On Windows, `subprocess.Popen.terminate` calls win32's `TerminalProcess`. However, the behavior I see is that child processes of the process I am trying to terminate are still running. Why is that? How do I ensure all child processes started by the process are killed? | By using [psutil](http://code.google.com/p/psutil):
```
import psutil, os
def kill_proc_tree(pid, including_parent=True):
parent = psutil.Process(pid)
children = parent.children(recursive=True)
for child in children:
child.kill()
psutil.wait_procs(children, timeout=5)
if including_pare... |
subprocess: deleting child processes in Windows | 1,230,669 | 25 | 2009-08-05T00:53:49Z | 10,830,753 | 17 | 2012-05-31T09:21:14Z | [
"python",
"windows",
"process",
"subprocess",
"kill-process"
] | On Windows, `subprocess.Popen.terminate` calls win32's `TerminalProcess`. However, the behavior I see is that child processes of the process I am trying to terminate are still running. Why is that? How do I ensure all child processes started by the process are killed? | Use `taskkill` with the `/T` flag
```
p = subprocess.Popen(...)
<wait>
subprocess.call(['taskkill', '/F', '/T', '/PID', str(p.pid)])
```
The flags to taskkill has the following docs:
```
TASKKILL [/S system [/U username [/P [password]]]]
{ [/FI filter] [/PID processid | /IM imagename] } [/T] [/F]
/S sys... |
Python Multiprocessing Exit Elegantly How? | 1,231,599 | 30 | 2009-08-05T07:07:23Z | 1,231,648 | 34 | 2009-08-05T07:23:47Z | [
"python",
"multiprocessing"
] | ```
import multiprocessing
import time
class testM(multiprocessing.Process):
def __init__(self):
multiprocessing.Process.__init__(self)
self.exit = False
def run(self):
while not self.exit:
pass
print "You exited!"
return
def shutdown(self):
se... | The reason you are not seeing this happen is because you are not communicating with the subprocess. You are trying to use a local variable (local to the parent process) to signal to the child that it should shutdown.
Take a look at the information on [synchonization primatives](http://docs.python.org/library/multiproc... |
How do I remove packages installed with Python's easy_install? | 1,231,688 | 572 | 2009-08-05T07:33:13Z | 1,231,745 | 27 | 2009-08-05T07:53:43Z | [
"python",
"packages",
"setuptools",
"easy-install"
] | Python's `easy_install` makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.
What is the best way of finding out what's installed, and what is the preferred way of removing in... | There are [several](http://thingsilearned.com/2009/04/13/easy_install-uninstalling/) sources on the net suggesting a hack by reinstalling the package with the -m option and then just removing the .egg file in lib/ and the binaries in bin/. Also, discussion about this setuptools issue can be found on the python bug trac... |
How do I remove packages installed with Python's easy_install? | 1,231,688 | 572 | 2009-08-05T07:33:13Z | 1,233,261 | 23 | 2009-08-05T13:28:37Z | [
"python",
"packages",
"setuptools",
"easy-install"
] | Python's `easy_install` makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.
What is the best way of finding out what's installed, and what is the preferred way of removing in... | If the problem is a serious-enough annoyance to you, you might consider [virtualenv](http://pypi.python.org/pypi/virtualenv). It allows you to create an environment that encapsulates python libraries. You install packages there rather than in the global site-packages directory. Any scripts you run in that environment h... |
How do I remove packages installed with Python's easy_install? | 1,231,688 | 572 | 2009-08-05T07:33:13Z | 1,233,282 | 164 | 2009-08-05T13:31:53Z | [
"python",
"packages",
"setuptools",
"easy-install"
] | Python's `easy_install` makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.
What is the best way of finding out what's installed, and what is the preferred way of removing in... | To uninstall an `.egg` you need to `rm -rf` the egg (it might be a directory) and remove the matching line from `site-packages/easy-install.pth` |
How do I remove packages installed with Python's easy_install? | 1,231,688 | 572 | 2009-08-05T07:33:13Z | 3,297,522 | 14 | 2010-07-21T08:40:36Z | [
"python",
"packages",
"setuptools",
"easy-install"
] | Python's `easy_install` makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.
What is the best way of finding out what's installed, and what is the preferred way of removing in... | try
```
$ easy_install -m [PACKAGE]
```
then
```
$ rm -rf .../python2.X/site-packages/[PACKAGE].egg
``` |
How do I remove packages installed with Python's easy_install? | 1,231,688 | 572 | 2009-08-05T07:33:13Z | 3,297,564 | 536 | 2010-07-21T08:47:21Z | [
"python",
"packages",
"setuptools",
"easy-install"
] | Python's `easy_install` makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.
What is the best way of finding out what's installed, and what is the preferred way of removing in... | [pip](http://pypi.python.org/pypi/pip/), an alternative to setuptools/easy\_install, provides an "uninstall" command.
Install pip according to the [installation instructions](http://pip.readthedocs.org/en/stable/installing/):
```
$ wget https://bootstrap.pypa.io/get-pip.py
$ python get-pip.py
```
Then you can use `p... |
How do I remove packages installed with Python's easy_install? | 1,231,688 | 572 | 2009-08-05T07:33:13Z | 3,454,856 | 13 | 2010-08-11T02:28:14Z | [
"python",
"packages",
"setuptools",
"easy-install"
] | Python's `easy_install` makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.
What is the best way of finding out what's installed, and what is the preferred way of removing in... | Official(?) instructions: <http://peak.telecommunity.com/DevCenter/EasyInstall#uninstalling-packages>
> If you have replaced a package with another version, then you can just delete the package(s) you don't need by deleting the PackageName-versioninfo.egg file or directory (found in the installation directory).
>
> If... |
How do I remove packages installed with Python's easy_install? | 1,231,688 | 572 | 2009-08-05T07:33:13Z | 6,263,564 | 128 | 2011-06-07T09:56:47Z | [
"python",
"packages",
"setuptools",
"easy-install"
] | Python's `easy_install` makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.
What is the best way of finding out what's installed, and what is the preferred way of removing in... | First you have to run this command:
```
$ easy_install -m [PACKAGE]
```
It removes all dependencies of the package.
Then remove egg file of that package:
```
$ sudo rm -rf /usr/local/lib/python2.X/site-packages/[PACKAGE].egg
``` |
How do I remove packages installed with Python's easy_install? | 1,231,688 | 572 | 2009-08-05T07:33:13Z | 8,718,590 | 49 | 2012-01-03T21:04:44Z | [
"python",
"packages",
"setuptools",
"easy-install"
] | Python's `easy_install` makes installing new packages extremely convenient. However, as far as I can tell, it doesn't implement the other common features of a dependency manager - listing and removing installed packages.
What is the best way of finding out what's installed, and what is the preferred way of removing in... | All the info is in the other answers, but none summarizes *both* your requests or seem to make things needlessly complex:
* For your removal needs use:
```
pip uninstall <package>
```
(install using `easy_install pip`)
* For your 'list installed packages' needs either use:
```
pip freeze
```
Or:
... |
How does mercurial work without Python installed? | 1,231,853 | 8 | 2009-08-05T08:22:55Z | 1,232,605 | 7 | 2009-08-05T11:16:36Z | [
"python",
"mercurial",
"ironpython"
] | I have Mercurial 1.3 installed on my Windows 7 machine. I don't have python installed, but Mercurial seems to be OK with that.
How does it work?
Also, is it possible to force Mercurial run on IronPython and will it be compatible?
Thank you. | Since there is a "library.zip"(9MB), Mercurial's Windows binary package maybe made by [py2exe](http://www.py2exe.org/), py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation. |
How does mercurial work without Python installed? | 1,231,853 | 8 | 2009-08-05T08:22:55Z | 1,232,767 | 17 | 2009-08-05T11:52:12Z | [
"python",
"mercurial",
"ironpython"
] | I have Mercurial 1.3 installed on my Windows 7 machine. I don't have python installed, but Mercurial seems to be OK with that.
How does it work?
Also, is it possible to force Mercurial run on IronPython and will it be compatible?
Thank you. | The Mercurial windows installer is packaged using [py2exe](http://www.py2exe.org/). This places the python interpreter as a DLL inside of a file called "library.zip".
On my machine, it is placed in "C:\Program Files\TortoiseHg\library.zip"
This zip file also contains the python libraries that are required by mercuria... |
MySQL LOAD DATA LOCAL INFILE example in python? | 1,231,900 | 10 | 2009-08-05T08:36:26Z | 1,234,705 | 18 | 2009-08-05T17:46:39Z | [
"python",
"mysql",
"load-data-infile"
] | I am looking for a syntax definition, example, sample code, wiki, etc. for
executing a LOAD DATA LOCAL INFILE command from python.
I believe I can use mysqlimport as well if that is available, so any feedback (and code snippet) on which is the better route, is welcome. A Google search is not turning up much in the way... | Well, using python's MySQLdb, I use this:
```
connection = MySQLdb.Connect(host='**', user='**', passwd='**', db='**')
cursor = connection.cursor()
query = "LOAD DATA INFILE '/path/to/my/file' INTO TABLE sometable FIELDS TERMINATED BY ';' ENCLOSED BY '\"' ESCAPED BY '\\\\'"
cursor.execute( query )
connection.commit()
... |
How can I use a class instance variable as an argument for a method decorator in Python? | 1,231,950 | 4 | 2009-08-05T08:49:25Z | 1,232,055 | 7 | 2009-08-05T09:11:19Z | [
"python",
"decorator"
] | How can I use a class instance variable as an argument for a method decorator in Python?
The following is a minimal example shows what I'm trying to do. It obviously fails as the decorator function does not have access to the reference to the instance and I have no idea how to get access to the reference from the decor... | It's not going to work; the decorator is called during *class creation* time, which is long before an instance is created (*if* that ever happens). So if your "decorator" needs the instance, you have to do the "decorating" at instantiation time:
```
def get_decorator(arg1):
def my_decorator(function):
prin... |
"Upload" a file from django shell | 1,232,434 | 10 | 2009-08-05T10:41:15Z | 1,232,567 | 17 | 2009-08-05T11:07:11Z | [
"python",
"django",
"file",
"import",
"data-importer"
] | I need to import some data from a excel file and a folder with images, every row in the excel describes every entry and have a list of filenames in the folder (photos related to the entry).
I've done a script which creates every entry in the database and saves it trough the django shell, but i have no idea how to inst... | Finally I found the answer.
```
from django.core.files import File
f = File(open(os.path.join(IMPORT_DIR, 'fotos', photo), 'r'))
p = Photo(name=f.name, image=f, parent=supply.supply_ptr)
name = str(uuid1()) + os.path.splitext(f.name)[1]
p.image.save(name, f)
p.save()
``` |
Concatenating Dictionaries | 1,232,904 | 6 | 2009-08-05T12:22:03Z | 1,232,938 | 13 | 2009-08-05T12:27:35Z | [
"python",
"dictionary",
"merge",
"key"
] | I have three lists, the first is a list of names, the second is a list of dictionaries, and the third is a list of data. Each position in a list corresponds with the same positions in the other lists. List\_1[0] has corresponding data in List\_2[0] and List\_3[0], etc. I would like to turn these three lists into a dict... | ```
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = [7,8,9]
>>> dict(zip(a, zip(b, c)))
{1: (4, 7), 2: (5, 8), 3: (6, 9)}
```
See the [documentation](http://docs.python.org/library/functions.html#zip) for more info on `zip`.
As lionbest points out below, you might want to look at [`itertools.izip()`](http://docs.python.org/l... |
Python multiprocessing easy way to implement a simple counter? | 1,233,222 | 7 | 2009-08-05T13:19:56Z | 1,233,363 | 20 | 2009-08-05T13:46:06Z | [
"python",
"multiprocessing"
] | Hey everyone, I am using multiprocessing in python now. and I am just wondering whether there exists some sort of simple counter variable that each process when they are done processing some task could just increment ( kind of like how much work done in total).
I looked up the API for Value, don't think it's mutable. | `Value` is indeed mutable; you specify the datatype you want from the `ctypes` module and then it can be mutated. Here's a complete, working script that demonstrates this:
```
from time import sleep
from ctypes import c_int
from multiprocessing import Value, Lock, Process
counter = Value(c_int) # defaults to 0
count... |
No Multiline Lambda in Python: Why not? | 1,233,448 | 129 | 2009-08-05T14:00:30Z | 1,233,509 | 75 | 2009-08-05T14:10:30Z | [
"python",
"syntax",
"lambda"
] | I've heard it said that multiline lambdas can't be added in Python because they would clash syntactically with the other syntax constructs in Python. I was thinking about this on the bus today and realized I couldn't think of a single Python construct that multiline lambdas clash with. Given that I know the language pr... | Look at the following:
```
map(multilambda x:
y=x+1
return y
, [1,2,3])
```
Is this a lambda returning `(y, [1,2,3])` (thus map only gets one parameter, resulting in an error)? Or does it return `y`? Or is it a syntax error, because the comma on the new line is misplaced? How would Python know what you... |
No Multiline Lambda in Python: Why not? | 1,233,448 | 129 | 2009-08-05T14:00:30Z | 1,233,520 | 300 | 2009-08-05T14:12:30Z | [
"python",
"syntax",
"lambda"
] | I've heard it said that multiline lambdas can't be added in Python because they would clash syntactically with the other syntax constructs in Python. I was thinking about this on the bus today and realized I couldn't think of a single Python construct that multiline lambdas clash with. Given that I know the language pr... | Guido van Rossum (the inventor of Python) answers this exact question himself in [an old blog post](http://www.artima.com/weblogs/viewpost.jsp?thread=147358).
Basically, he admits that it's theoretically possible, but that any proposed solution would be un-Pythonic:
> "But the complexity of any proposed solution for... |
No Multiline Lambda in Python: Why not? | 1,233,448 | 129 | 2009-08-05T14:00:30Z | 1,233,611 | 12 | 2009-08-05T14:27:04Z | [
"python",
"syntax",
"lambda"
] | I've heard it said that multiline lambdas can't be added in Python because they would clash syntactically with the other syntax constructs in Python. I was thinking about this on the bus today and realized I couldn't think of a single Python construct that multiline lambdas clash with. Given that I know the language pr... | A couple of relevant links:
For a while, I was following the development of Reia, which was initially going to have Python's indentation based syntax with Ruby blocks too, all on top of Erlang. But, the designer wound up giving up on indentation sensitivity, and this post he wrote about that decision includes a discus... |
No Multiline Lambda in Python: Why not? | 1,233,448 | 129 | 2009-08-05T14:00:30Z | 13,672,943 | 14 | 2012-12-02T19:32:22Z | [
"python",
"syntax",
"lambda"
] | I've heard it said that multiline lambdas can't be added in Python because they would clash syntactically with the other syntax constructs in Python. I was thinking about this on the bus today and realized I couldn't think of a single Python construct that multiline lambdas clash with. Given that I know the language pr... | This is generally very ugly (but sometimes the alternatives are even more ugly), so a workaround is to make a braces expression:
```
lambda: (
doFoo('abc'),
doBar(123),
doBaz())
```
It won't accept any assignments though, so you'll have to prepare data beforehand.
The place I found this useful is the PySi... |
Python Dictionary to URL Parameters | 1,233,539 | 64 | 2009-08-05T14:14:06Z | 1,233,551 | 128 | 2009-08-05T14:16:28Z | [
"python",
"dictionary",
"url-parameters"
] | I am trying to convert a Python dictionary to a string for use as URL parameters. I am sure that there is a better, more [Pythonic](http://en.wikipedia.org/wiki/Pythonic) way of doing this. What is it?
```
x = ""
for key, val in {'a':'A', 'b':'B'}.items():
x += "%s=%s&" %(key,val)
x = x[:-1]
``` | Use [`urllib.urlencode()`](http://docs.python.org/library/urllib.html#urllib.urlencode). It takes a dictionary of key-value pairs, and converts it into a form suitable for a URL (e.g., `key1=val1&key2=val2`).
If you are using Python3, use [`urllib.parse.urlencode()`](https://docs.python.org/3/library/urllib.parse.html... |
PYTHON: Converting list of tuples into a dictionary | 1,233,546 | 30 | 2009-08-05T14:15:49Z | 1,233,588 | 12 | 2009-08-05T14:22:30Z | [
"python",
"list",
"dictionary"
] | I'm looking for a way to convert **list of tuples** which looks like this:
```
[(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
```
into **a dictionary**, where key:value pair looks like this:
```
{4:[1,2,3] ,15:[4,5,9,11,12], 23:[6,7,8,10]}
```
Second element from a tuple becom... | ```
>>> a = [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
>>> b = {}
>>> for i, j in a:
... b.setdefault(j, []).append(i)
...
>>> b
{23: [6, 7, 8, 10], 4: [1, 2, 3], 15: [4, 5, 9, 11, 12]}
>>>
``` |
PYTHON: Converting list of tuples into a dictionary | 1,233,546 | 30 | 2009-08-05T14:15:49Z | 1,233,628 | 41 | 2009-08-05T14:29:46Z | [
"python",
"list",
"dictionary"
] | I'm looking for a way to convert **list of tuples** which looks like this:
```
[(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
```
into **a dictionary**, where key:value pair looks like this:
```
{4:[1,2,3] ,15:[4,5,9,11,12], 23:[6,7,8,10]}
```
Second element from a tuple becom... | ```
>>> from collections import defaultdict
>>> l= [(1,4),(2,4),(3,4),(4,15),(5,15),(6,23),(7,23),(8,23),(9,15),(10,23),(11,15),(12,15)]
>>> d= defaultdict( list )
>>> for v, k in l:
... d[k].append(v)
...
>>> d
defaultdict(<type 'list'>, {23: [6, 7, 8, 10], 4: [1, 2, 3], 15: [4, 5, 9, 11, 12]})
>>> [ {k:d[k]} for... |
What is the simplest way to SSH using Python? | 1,233,655 | 73 | 2009-08-05T14:34:25Z | 1,233,729 | 8 | 2009-08-05T14:44:49Z | [
"python",
"linux",
"unix",
"ssh"
] | How can I simply SSH to a remote server from a local Python (3.0) script, supply a login/password, execute a command and print the output to the Python console?
I would rather not use any large external library or install anything on the remote server. | Your definition of "simplest" is important here - simple code means using a module (though "large external library" is an exaggeration).
I believe the most up-to-date (actively developed) module is [paramiko](http://www.lag.net/paramiko/). It comes with demo scripts in the download, and has detailed online API documen... |
What is the simplest way to SSH using Python? | 1,233,655 | 73 | 2009-08-05T14:34:25Z | 1,233,763 | 37 | 2009-08-05T14:49:05Z | [
"python",
"linux",
"unix",
"ssh"
] | How can I simply SSH to a remote server from a local Python (3.0) script, supply a login/password, execute a command and print the output to the Python console?
I would rather not use any large external library or install anything on the remote server. | I haven't tried it, but this [pysftp](http://pypi.python.org/pypi/pysftp/) module might help, which in turn uses paramiko. I believe everything is client-side.
The interesting command is probably `.execute()` which executes an arbitrary command on the remote machine. (The module also features `.get()` and `.put` metho... |
What is the simplest way to SSH using Python? | 1,233,655 | 73 | 2009-08-05T14:34:25Z | 1,233,845 | 59 | 2009-08-05T15:00:29Z | [
"python",
"linux",
"unix",
"ssh"
] | How can I simply SSH to a remote server from a local Python (3.0) script, supply a login/password, execute a command and print the output to the Python console?
I would rather not use any large external library or install anything on the remote server. | You can code it yourself using Paramiko, as suggested above. Alternatively, you can look into Fabric, a python application for doing all the things you asked about:
> Fabric is a Python library and
> command-line tool designed to
> streamline deploying applications or
> performing system administration tasks
> via the... |
What is the simplest way to SSH using Python? | 1,233,655 | 73 | 2009-08-05T14:34:25Z | 1,233,872 | 21 | 2009-08-05T15:05:39Z | [
"python",
"linux",
"unix",
"ssh"
] | How can I simply SSH to a remote server from a local Python (3.0) script, supply a login/password, execute a command and print the output to the Python console?
I would rather not use any large external library or install anything on the remote server. | If you want to avoid any extra modules, you can use the subprocess module to run
```
ssh [host] [command]
```
and capture the output.
Try something like:
```
process = subprocess.Popen("ssh example.com ls", shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
output,stderr = process.communicate()
statu... |
What is the simplest way to SSH using Python? | 1,233,655 | 73 | 2009-08-05T14:34:25Z | 5,142,224 | 15 | 2011-02-28T12:51:11Z | [
"python",
"linux",
"unix",
"ssh"
] | How can I simply SSH to a remote server from a local Python (3.0) script, supply a login/password, execute a command and print the output to the Python console?
I would rather not use any large external library or install anything on the remote server. | I have written [Python bindings for libssh2](http://www.no-ack.org/2010/11/python-bindings-for-libssh2.html). Libssh2 is a client-side library implementing the SSH2 protocol.
```
import socket
import libssh2
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('exmaple.com', 22))
session = libssh2.... |
Installing Pinax on Windows | 1,233,670 | 4 | 2009-08-05T14:36:04Z | 1,416,015 | 7 | 2009-09-12T20:13:08Z | [
"python",
"django",
"web-applications",
"pinax"
] | Can I install [Pinax](http://pinaxproject.com/) on Windows Environment?
Is there a easy way?
Which environment do you recommend? | I have pinax 0.7rc1 installed and working on windows 7, with no problems.
Check out this video for a great example on how to do this. He uses pinax 0.7beta3 on windows XP.
<http://www.vimeo.com/6098872>
Here are the steps I followed.
1. download and install python
2. download and install python image library
3. dow... |
PIL does not save transparency | 1,233,772 | 9 | 2009-08-05T14:50:26Z | 1,233,807 | 28 | 2009-08-05T14:55:20Z | [
"python",
"png",
"python-imaging-library"
] | ```
from PIL import Image
img = Image.open('1.png')
img.save('2.png')
```
The first image has a transparent background, but when I save it, the transparency is gone (background is white)
What am I doing wrong? | Probably the image is indexed (mode "P" in PIL), so the transparency is not set in PNG alpha channel, but in metadata info.
You can get transparent background palette index with the following code:
```
from PIL import Image
img = Image.open('1.png')
png_info = img.info
img.save('2.png', **png_info)
```
image info i... |
In GTK, how do I get the actual size of a widget on screen? | 1,234,223 | 5 | 2009-08-05T16:09:08Z | 1,234,294 | 9 | 2009-08-05T16:23:46Z | [
"python",
"api",
"user-interface",
"gtk",
"pygtk"
] | First I looked at the `get_size_request` method. The docs there end with:
> To get the size a widget will actually use, call the `size_request()` instead of this method.
I look at `size_request()`, and it ends with
> Also remember that the size request is not necessarily the size a widget will actually be allocated.... | This should be it (took some time to find):
> The get\_allocation() method returns a gtk.gdk.Rectangle containing the bounds of the widget's allocation.
From [here](http://library.gnome.org/devel/pygtk/stable/class-gtkwidget.html#method-gtkwidget--get-allocation). |
How to roll my own pypi? | 1,235,331 | 36 | 2009-08-05T19:43:35Z | 1,236,347 | 12 | 2009-08-06T00:00:39Z | [
"python",
"pypi"
] | I would like to run my own internal pypi server, for egg distribution within my organization.
I have found a few projects, such as:
* <http://pypi.python.org/pypi/EggBasket/>
* <http://plone.org/products/plonesoftwarecenter>
As I understand it, pypi.python.org uses software called Cheese Shop.
My questions:
1. Why... | The source to Cheese Shop can be downloaded from <https://bitbucket.org/pypa/pypi/src>. There is also an example, from the page you linked to, of using Apache as a "dumb" Python package repository:
```
# Mount pypi repositories into URI space
Alias /pypi /var/pypi
# /pypi/dev: Redirect for unknown packages (fallbac... |
How to roll my own pypi? | 1,235,331 | 36 | 2009-08-05T19:43:35Z | 12,874,682 | 12 | 2012-10-13T15:46:42Z | [
"python",
"pypi"
] | I would like to run my own internal pypi server, for egg distribution within my organization.
I have found a few projects, such as:
* <http://pypi.python.org/pypi/EggBasket/>
* <http://plone.org/products/plonesoftwarecenter>
As I understand it, pypi.python.org uses software called Cheese Shop.
My questions:
1. Why... | For light-weight solution, use [pypiserver](http://pypi.python.org/pypi/pypiserver). |
Python: how can I handle any unhandled exception in an alternative way? | 1,235,349 | 6 | 2009-08-05T19:46:05Z | 1,235,434 | 13 | 2009-08-05T20:02:35Z | [
"python",
"exception"
] | Normally unhandled exceptions go to the stdout (or stderr?), I am building an app where I want to pass this info to the GUI before shutting down and display it to the user and, at the same time I want to write it to a log file. So, I need an str with the full text of the exception.
How can I do this? | Use sys.excepthook to replace the base exception handler. You can do something like:
```
import sys
from PyQt4 import QtGui
import os.path
import traceback
def handle_exception(exc_type, exc_value, exc_traceback):
""" handle all exceptions """
## KeyboardInterrupt is a special case.
## We don't raise the erro... |
Python: how can I handle any unhandled exception in an alternative way? | 1,235,349 | 6 | 2009-08-05T19:46:05Z | 1,236,614 | 8 | 2009-08-06T02:01:42Z | [
"python",
"exception"
] | Normally unhandled exceptions go to the stdout (or stderr?), I am building an app where I want to pass this info to the GUI before shutting down and display it to the user and, at the same time I want to write it to a log file. So, I need an str with the full text of the exception.
How can I do this? | You already got excellent answers, I just wanted to add one more tip that's served me well over the years in a variety of language for the specific problem "how to cleanly diagnose, log, etc, `out of memory` errors?". Problem is, if your code gets control before enough objects have been destroyed and their memory recyc... |
Comparing persistent storage solutions in python | 1,235,594 | 10 | 2009-08-05T20:37:18Z | 1,235,620 | 8 | 2009-08-05T20:41:50Z | [
"python",
"orm",
"persistence"
] | I'm starting on a new scientific project which has a lot of data (millions of entries) I'd like to store in an easily and quickly accessible format. I've come across a number of different potential options, but I'm not sure how to pick amongst them. My data can probably just be stored as a dictionary, or potentially a ... | A RDBMS.
Nothing is more realiable than using tables on a well known RDBMS. [Postgresql](http://www.postgresql.org/) comes to mind.
That automatically gives you some choices for the future like clustering. Also you automatically have a lot of tools to administer your database, and you can use it from other software w... |
Comparing persistent storage solutions in python | 1,235,594 | 10 | 2009-08-05T20:37:18Z | 1,235,947 | 13 | 2009-08-05T21:49:31Z | [
"python",
"orm",
"persistence"
] | I'm starting on a new scientific project which has a lot of data (millions of entries) I'd like to store in an easily and quickly accessible format. I've come across a number of different potential options, but I'm not sure how to pick amongst them. My data can probably just be stored as a dictionary, or potentially a ... | Might want to give [mongodb](http://www.mongodb.org/) a shot - the PyMongo library works with dictionaries and supports most Python types. Easy to install, very performant + scalable. MongoDB (and PyMongo) is also used [in production](http://www.mongodb.org/display/DOCS/Production+Deployments) at some big names. |
Python: remove dictionary from list | 1,235,618 | 19 | 2009-08-05T20:41:13Z | 1,235,631 | 40 | 2009-08-05T20:43:26Z | [
"python",
"list",
"dictionary"
] | If I have a list of dictionaries, say:
```
[{'id': 1, 'name': 'paul'},
{'id': 2, 'name': 'john'}]
```
and I would like to remove the dictionary with `id` of 2 (or name john), what is the most efficient way to go about this programmatically (that is to say, I don't know the index of the entry in the list so it can't s... | ```
thelist[:] = [d for d in thelist if d.get('id') != 2]
```
**Edit**: as some doubts have been expressed in a comment about the performance of this code (some based on misunderstanding Python's performance characteristics, some on assuming beyond the given specs that there is exactly one dict in the list with a valu... |
Execute python code inside browser without Jython | 1,235,629 | 17 | 2009-08-05T20:43:04Z | 1,235,778 | 9 | 2009-08-05T21:10:38Z | [
"python",
"browser",
"remote-execution"
] | Is there a way to execute python code in a browser, other than using Jython and an applet?
The execution does not have to deal with anything related to graphics. For example, just sum all the digits of a binary 1Gb file (chosen by the browser user) and then return the result to the server.
I am aware that [python can... | The [Pyjamas](http://pyjs.org/) project has a compiler called pyjs which turns Python code into Javascript. |
Compiling python modules whith DEBUG defined on MSVC | 1,236,060 | 17 | 2009-08-05T22:16:28Z | 1,236,116 | 19 | 2009-08-05T22:33:08Z | [
"python",
"debugging",
"visual-c++"
] | Python rather stupidly has a pragma directive in its include files that forces a link against `python26_d.lib` when the `DEBUG` preprocessor variable is defined. This is a problem because the python installer doesn't come with `python26_d.lib`! So I can't build applications in msvc in debug mode. If i temporarily `#und... | From [python list](http://mail.python.org/pipermail/python-list/2009-March/1198717.html)
> As a workaround to the situation, try
> to copy the file python26.dll to
> python26\_d.dll. (I'm not sure this
> will work; you say you are building a
> SWIG library in debug mode, and it's
> possible that SWIG will try to use
>... |
Compiling python modules whith DEBUG defined on MSVC | 1,236,060 | 17 | 2009-08-05T22:16:28Z | 3,548,850 | 7 | 2010-08-23T15:06:34Z | [
"python",
"debugging",
"visual-c++"
] | Python rather stupidly has a pragma directive in its include files that forces a link against `python26_d.lib` when the `DEBUG` preprocessor variable is defined. This is a problem because the python installer doesn't come with `python26_d.lib`! So I can't build applications in msvc in debug mode. If i temporarily `#und... | After you comment out "#define Py\_DEBUG" on line 332 and modify
```
# ifdef _DEBUG
# pragma comment(lib,"python26_d.lib")
# else
```
to
```
# ifdef _DEBUG
# pragma comment(lib,"python26.lib")
# else
```
you do not need to python26\_d.lib anymore. |
How do I see stdout when running Django tests? | 1,236,285 | 24 | 2009-08-05T23:34:08Z | 1,239,545 | 28 | 2009-08-06T15:09:16Z | [
"python",
"django",
"debugging",
"testing",
"stdout"
] | When I run tests with `./manage.py test`, whatever I send to the standard output through `print` doesn't show. When tests fail, I see an "stdout" block per failed test, so I guess Django traps it (but doesn't show it when tests pass). | Checked `TEST_RUNNER` in `settings.py`, it's using a project-specific runner that calls out to Nose. *Nose has the `-s` option to stop it from capturing `stdout`*, but if I run:
`./manage.py test -s`
`manage.py` captures it first and throws a "no such option" error. The help for `manage.py` doesn't mention this, but ... |
How do I see stdout when running Django tests? | 1,236,285 | 24 | 2009-08-05T23:34:08Z | 22,777,773 | 22 | 2014-04-01T05:48:07Z | [
"python",
"django",
"debugging",
"testing",
"stdout"
] | When I run tests with `./manage.py test`, whatever I send to the standard output through `print` doesn't show. When tests fail, I see an "stdout" block per failed test, so I guess Django traps it (but doesn't show it when tests pass). | Yeah, this issue is cause by `NoseTestSuiteRunner`. Add `-- -s` is a tricky but not the best solutions.
Try to add follow lines in the `settings.py`:
```
NOSE_ARGS = ['--nocapture',
'--nologcapture',]
```
Which solved my problems. |
Comma separated lists in django templates | 1,236,593 | 41 | 2009-08-06T01:50:18Z | 1,236,619 | 89 | 2009-08-06T02:02:37Z | [
"python",
"django",
"list",
"django-templates"
] | If `fruits` is the list `['apples', 'oranges', 'pears']`,
is there a quick way using django template tags to produce "apples, oranges, and pears"?
I know it's not difficult to do this using a loop and `{% if counter.last %}` statements, but because I'm going to use this repeatedly I think I'm going to have to learn h... | First choice: use the existing join template tag.
<http://docs.djangoproject.com/en/dev/ref/templates/builtins/#join>
Here's their example
```
{{ value|join:" // " }}
```
Second choice: do it in the view.
```
fruits_text = ", ".join( fruits )
```
Provide `fruits_text` to the template for rendering. |
Comma separated lists in django templates | 1,236,593 | 41 | 2009-08-06T01:50:18Z | 1,236,716 | 26 | 2009-08-06T02:41:01Z | [
"python",
"django",
"list",
"django-templates"
] | If `fruits` is the list `['apples', 'oranges', 'pears']`,
is there a quick way using django template tags to produce "apples, oranges, and pears"?
I know it's not difficult to do this using a loop and `{% if counter.last %}` statements, but because I'm going to use this repeatedly I think I'm going to have to learn h... | I would suggest a custom django templating *filter* rather than a custom *tag* -- filter is handier and simpler (where appropriate, like here). `{{ fruits | joinby:", " }}` looks like what I'd want to have for the purpose... with a custom `joinby` filter:
```
def joinby(value, arg):
return arg.join(value)
```
whi... |
Comma separated lists in django templates | 1,236,593 | 41 | 2009-08-06T01:50:18Z | 3,649,002 | 47 | 2010-09-06T04:28:13Z | [
"python",
"django",
"list",
"django-templates"
] | If `fruits` is the list `['apples', 'oranges', 'pears']`,
is there a quick way using django template tags to produce "apples, oranges, and pears"?
I know it's not difficult to do this using a loop and `{% if counter.last %}` statements, but because I'm going to use this repeatedly I think I'm going to have to learn h... | Here's a super simple solution. Put this code into comma.html:
```
{% if not forloop.last %}{% ifequal forloop.revcounter 2 %} and {% else %}, {% endifequal %}{% else %}{% endif %}
```
And now wherever you'd put the comma, include "comma.html" instead:
```
{% for cat in cats %}
Kitty {{cat.name}}{% include "comma.ht... |
Is 'for x in array' always result in sorted x? [Python/NumPy] | 1,236,695 | 4 | 2009-08-06T02:31:46Z | 1,236,701 | 9 | 2009-08-06T02:34:00Z | [
"python",
"arrays",
"list",
"numpy"
] | For arrays and lists in Python and Numpy are the following lines equivalent:
```
itemlist = []
for j in range(len(myarray)):
item = myarray[j]
itemlist.append(item)
```
and:
```
itemlist = []
for item in myarray:
itemlist.append(item)
```
I'm interested in the *order* of itemlist. In a few examples that... | Yes, it's entirely guaranteed. `for item in myarray` (where `myarray` is a *sequence*, which includes numpy's arrays, builtin lists, Python's array.arrays, etc etc), is in fact equivalent in Python to:
```
_aux = 0
while _aux < len(myarray):
item = myarray[_aux]
...etc...
```
for some phantom variable `_aux`;-). ... |
Is 'for x in array' always result in sorted x? [Python/NumPy] | 1,236,695 | 4 | 2009-08-06T02:31:46Z | 1,236,808 | 7 | 2009-08-06T03:17:50Z | [
"python",
"arrays",
"list",
"numpy"
] | For arrays and lists in Python and Numpy are the following lines equivalent:
```
itemlist = []
for j in range(len(myarray)):
item = myarray[j]
itemlist.append(item)
```
and:
```
itemlist = []
for item in myarray:
itemlist.append(item)
```
I'm interested in the *order* of itemlist. In a few examples that... | It is guaranteed for lists. I think the more relevant Python parallel to your C# example would be to iterate over the keys in a dictionary, which is NOT guaranteed to be in any order.
```
# Always prints 0-9 in order
a_list = [0,1,2,3,4,5,6,7,8,9]
for x in a_list:
print x
# May or may not print 0-9 in order. Impl... |
math.sin incorrect result | 1,237,085 | 4 | 2009-08-06T05:16:09Z | 1,237,087 | 22 | 2009-08-06T05:18:56Z | [
"python",
"math",
"trigonometry",
"sin"
] | ```
>>> import math
>>> math.sin(68)
-0.897927680689
```
But
```
sin(68) = 0.927 (3 decimal places)
```
Any ideas about why I am getting this result?
Thanks. | ```
>>> import math
>>> print math.sin.__doc__
sin(x)
Return the sine of x (measured in radians).
```
math.sin expects its argument to be in radians, not degrees, so:
```
>>> import math
>>> print math.sin(math.radians(68))
0.927183854567
``` |
How do I set sys.excepthook to invoke pdb globally in python? | 1,237,379 | 6 | 2009-08-06T07:15:46Z | 1,237,407 | 17 | 2009-08-06T07:27:07Z | [
"python",
"debugging",
"configuration",
"pdb"
] | From Python docs:
> `sys.excepthook(type, value, traceback)`
>
> This function prints out a given traceback and exception to `sys.stderr`.
>
> When an exception is raised and uncaught, the interpreter calls `sys.excepthook` with three arguments, the exception class, exception instance, and a traceback object. In an in... | Here's what you need
<http://ynniv.com/blog/2007/11/debugging-python.html>
Three ways, the first is simple but crude ([Thomas Heller](http://mail.python.org/pipermail/python-list/2001-April/713230.html)) - add the following to site-packages/sitecustomize.py:
```
import pdb, sys, traceback
def info(type, value, tb):
... |
Choose the filename of an uploaded file with Django | 1,237,602 | 6 | 2009-08-06T08:26:14Z | 1,237,741 | 18 | 2009-08-06T08:59:38Z | [
"python",
"django",
"django-models"
] | I'm uploading images (represented by a FileField) and I need to rename those files when they are uploaded.
I want them to be formated like that:
`"%d-%d-%s.%s" % (width, height, md5hash, original_extension)`
I've read the documentation but I don't know if I need to write my own FileSystemStorage class or my own File... | You don't need to write your own FileStorage class or anything that complicated.
The 'upload\_to' parameter on File/ImageFields can take a function that returns the path/file to use.
How to do this has already been answered [here](http://stackoverflow.com/questions/1190697/django-filefield-with-uploadto-determined-at... |
Python: binary/hex string conversion? | 1,238,002 | 7 | 2009-08-06T10:03:27Z | 1,238,129 | 20 | 2009-08-06T10:36:46Z | [
"python",
"binary",
"hex"
] | I have a string that has both binary and string characters and I would like to convert it to binary first, then to hex.
The string is as below:
```
<81>^Q<81>"^Q^@^[)^G ^Q^A^S^A^V^@<83>^Cd<80><99>}^@N^@^@^A^@^@^@^@^@^@^@j
```
How do I go about converting this string in Python so that the output in hex format is simi... | You can use ord and hex like this :
```
>>> s = 'some string'
>>> hex_chars = map(hex,map(ord,s))
>>> print hex_chars
['0x73', '0x6f', '0x6d', '0x65', '0x20', '0x73', '0x74', '0x72', '0x69', '0x6e', '0x67']
>>> hex_string = "".join(c[2:4] for c in hex_chars)
>>> print hex_string
736f6d6520737472696e67
>>>
```
Or use ... |
What does % do to strings in Python? | 1,238,306 | 11 | 2009-08-06T11:29:00Z | 1,238,316 | 20 | 2009-08-06T11:30:46Z | [
"python",
"string",
"documentation",
"operators"
] | I have failed to find documentation for the operator % as it is used on strings in Python. Does someone know where that documentation is? | It's the string formatting operator. Read up on [string formatting in Python](http://docs.python.org/library/stdtypes.html#string-formatting-operations).
```
format % values
```
Creates a string where `format` specifies a format and `values` are the values to be filled in. |
Is it necessary or useful to inherit from python's object in Python 3.x? | 1,238,606 | 32 | 2009-08-06T12:39:53Z | 1,238,632 | 27 | 2009-08-06T12:43:53Z | [
"python",
"python-3.x"
] | In older python version when you create a class in python, it can inherit from *object* which is as far I understand a special built-in python element that allow your object to be a new-style object.
What about newer version (> 3.0 and 2.6)? I googled about the class object but I get so much result (for an obvious rea... | You don't need to inherit from `object` to have new style in python 3. All classes are new-style. |
Can all language constructs be first-class in languages with offside-rules? | 1,238,975 | 2 | 2009-08-06T13:44:22Z | 1,239,032 | 9 | 2009-08-06T13:54:55Z | [
"python",
"lisp",
"expression",
"indentation",
"if-statement"
] | In LISP-like languages all language constructs are first-class citizens.
Consider the following example in Dylan:
```
let x = if (c)
foo();
else
bar();
end;
```
and in LISP:
```
(setf x (if c (foo) (bar)))
```
In Python you would have to write:
```
if c:
x = foo();
else:
... | Python has the following syntax that performs the same thing:
```
x = foo() if c else bar()
``` |
Asynchronous method call in Python? | 1,239,035 | 92 | 2009-08-06T13:55:35Z | 1,239,059 | 25 | 2009-08-06T13:59:22Z | [
"python",
"asynchronous"
] | I was wondering if there's any library for asynchronous method calls in [Python](http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29). It would be great if you could do something like
```
@async
def longComputation():
<code>
token = longComputation()
token.registerCallback(callback_function)
# alt... | It's not in the language core, but a very mature library that does what you want is [Twisted](http://twistedmatrix.com/). It introduces the Deferred object, which you can attach callbacks or error handlers ("errbacks") to. A Deferred is basically a "promise" that a function will have a result eventually. |
Asynchronous method call in Python? | 1,239,035 | 92 | 2009-08-06T13:55:35Z | 1,239,108 | 108 | 2009-08-06T14:05:52Z | [
"python",
"asynchronous"
] | I was wondering if there's any library for asynchronous method calls in [Python](http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29). It would be great if you could do something like
```
@async
def longComputation():
<code>
token = longComputation()
token.registerCallback(callback_function)
# alt... | What about something like
```
import threading
thr = threading.Thread(target=foo, args=(), kwargs={})
thr.start() # will run "foo"
....
thr.is_alive() # will return whether foo is running currently
....
thr.join() # will wait till "foo" is done
```
See the docs at <https://docs.python.org/2/library/threading.html#mo... |
Asynchronous method call in Python? | 1,239,035 | 92 | 2009-08-06T13:55:35Z | 1,239,252 | 82 | 2009-08-06T14:28:14Z | [
"python",
"asynchronous"
] | I was wondering if there's any library for asynchronous method calls in [Python](http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29). It would be great if you could do something like
```
@async
def longComputation():
<code>
token = longComputation()
token.registerCallback(callback_function)
# alt... | You can use the [multiprocessing module](http://docs.python.org/library/multiprocessing.html#module-multiprocessing) added in Python 2.6. You can use pools of processes and then get results asynchronously with:
```
apply_async(func[, args[, kwds[, callback]]])
```
E.g.:
```
from multiprocessing import Pool
def f(x)... |
Asynchronous method call in Python? | 1,239,035 | 92 | 2009-08-06T13:55:35Z | 5,485,574 | 16 | 2011-03-30T11:16:36Z | [
"python",
"asynchronous"
] | I was wondering if there's any library for asynchronous method calls in [Python](http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29). It would be great if you could do something like
```
@async
def longComputation():
<code>
token = longComputation()
token.registerCallback(callback_function)
# alt... | You can implement a decorator to make your functions asynchronous, though that's a bit tricky. The `multiprocessing` module is full of little quirks and seemingly arbitrary restrictions â all the more reason to encapsulate it behind a friendly interface, though.
```
from inspect import getmodule
from multiprocessing... |
Asynchronous method call in Python? | 1,239,035 | 92 | 2009-08-06T13:55:35Z | 12,780,318 | 7 | 2012-10-08T10:57:53Z | [
"python",
"asynchronous"
] | I was wondering if there's any library for asynchronous method calls in [Python](http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29). It would be great if you could do something like
```
@async
def longComputation():
<code>
token = longComputation()
token.registerCallback(callback_function)
# alt... | Just
```
import threading, time
def f():
print "f started"
time.sleep(3)
print "f finished"
threading.Thread(target=f).start()
``` |
Asynchronous method call in Python? | 1,239,035 | 92 | 2009-08-06T13:55:35Z | 36,272,211 | 12 | 2016-03-28T22:21:40Z | [
"python",
"asynchronous"
] | I was wondering if there's any library for asynchronous method calls in [Python](http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29). It would be great if you could do something like
```
@async
def longComputation():
<code>
token = longComputation()
token.registerCallback(callback_function)
# alt... | As of Python 3.5, you can use enhanced generators for async functions.
```
import asyncio
import datetime
```
**Enhanced generator syntax:**
```
@asyncio.coroutine
def display_date(loop):
end_time = loop.time() + 5.0
while True:
print(datetime.datetime.now())
if (loop.time() + 1.0) >= end_tim... |
is it ever useful to define a class method with a reference to self not called 'self' in Python? | 1,240,229 | 3 | 2009-08-06T17:10:36Z | 1,240,236 | 9 | 2009-08-06T17:12:11Z | [
"python",
"naming-conventions"
] | I'm teaching myself Python and I see the following in [Dive into Python](http://www.diveintopython.net/) [section 5.3](http://www.diveintopython.net/object_oriented_framework/defining_classes.html):
> By convention, the first argument of any Python class method (the reference to the current instance) is called `self`.... | No, unless you want to confuse every other programmer that looks at your code after you write it. `self` is not a keyword because it is an identifier. It *could* have been a keyword and the fact that it isn't one was a design decision. |
GTK: create a colored regular button | 1,241,020 | 5 | 2009-08-06T19:55:17Z | 1,241,609 | 14 | 2009-08-06T21:30:14Z | [
"python",
"button",
"gtk",
"colors",
"pygtk"
] | How do I do it? A lot of sites say I can just call .modify\_bg() on the button, but that doesn't do anything. I'm able to add an EventBox to the button, and add a label to that, and then change its colors, but it looks horrendous - there is a ton of gray space between the edge of the button that doesn't change. I just ... | Here's a little example:
```
import gtk
win = gtk.Window()
win.connect("destroy", gtk.main_quit)
btn = gtk.Button("test")
#make a gdk.color for red
map = btn.get_colormap()
color = map.alloc_color("red")
#copy the current style and replace the background
style = btn.get_style().copy()
style.bg[gtk.STATE_NORMAL] =... |
How to filter a dictionary by value? | 1,241,029 | 4 | 2009-08-06T19:56:16Z | 1,241,354 | 9 | 2009-08-06T20:49:46Z | [
"python",
"dictionary"
] | Newbie question here, so please bear with me.
Let's say I have a dictionary looking like this:
```
a = {"2323232838": ("first/dir", "hello.txt"),
"2323221383": ("second/dir", "foo.txt"),
"3434221": ("first/dir", "hello.txt"),
"32232334": ("first/dir", "hello.txt"),
"324234324": ("third/dir", "dog.... | The code below will result in two variables, `matches` and `remainders`. `matches` is an array of dictionaries, in which matching items from the original dictionary will have a corresponding element. `remainder` will contain, as in your example, a dictionary containing all the unmatched items.
Note that in your exampl... |
Copy constructor in python | 1,241,148 | 50 | 2009-08-06T20:16:48Z | 1,241,170 | 40 | 2009-08-06T20:21:34Z | [
"python",
"constructor",
"copy"
] | Is there a copy constructor in python ? If not what would I do to achieve something similar ?
The situation is that I am using a library and I have extended one of the classes there with extra functionality and I want to be able to convert the objects I get from the library to instances of my own class. | I think you want the [copy module](http://docs.python.org/library/copy.html)
```
import copy
x = copy.copy(y) # make a shallow copy of y
x = copy.deepcopy(y) # make a deep copy of y
```
you can control copying in much the same way as you control [pickle](http://docs.python.org/library/pickle.html#module-pi... |
Copy constructor in python | 1,241,148 | 50 | 2009-08-06T20:16:48Z | 1,241,241 | 10 | 2009-08-06T20:31:14Z | [
"python",
"constructor",
"copy"
] | Is there a copy constructor in python ? If not what would I do to achieve something similar ?
The situation is that I am using a library and I have extended one of the classes there with extra functionality and I want to be able to convert the objects I get from the library to instances of my own class. | For your situation, I would suggest writing a class method (or it could be a static method or a separate function) that takes as an argument an instance of the library's class and returns an instance of your class with all applicable attributes copied over. |
Copy constructor in python | 1,241,148 | 50 | 2009-08-06T20:16:48Z | 16,046,733 | 11 | 2013-04-16T20:43:33Z | [
"python",
"constructor",
"copy"
] | Is there a copy constructor in python ? If not what would I do to achieve something similar ?
The situation is that I am using a library and I have extended one of the classes there with extra functionality and I want to be able to convert the objects I get from the library to instances of my own class. | In python the copy constructor can be defined using default arguments. Lets say you want the normal constructor to run the function non\_copy\_constructor(self) and the copy constructor should run copy\_constructor(self,orig). Then you can do the following:
```
class Foo:
def __init__(self,orig=None):
if (... |
What is the recommended Python module for fast Fourier transforms (FFT)? | 1,241,797 | 4 | 2009-08-06T22:07:40Z | 1,241,961 | 8 | 2009-08-06T22:50:27Z | [
"python",
"benchmarking",
"fft"
] | Taking speed as an issue it may be better to choose another language, but what is your library/module/implementation of choice for doing a 1D fast Fourier transform (FFT) in Python? | I would recommend numpy library, I not sure if it's the fastest implementation that exist but but surely it's one of best scientific module on the "market". |
Multiple blocks of same name in Jinja2 | 1,242,239 | 22 | 2009-08-07T00:18:14Z | 1,245,030 | 44 | 2009-08-07T14:27:05Z | [
"python",
"html",
"templates",
"jinja2"
] | In [Jinja2](http://jinja.pocoo.org/), I have a base template like this:
```
<title>{% block title %}{% endblock %} - example.com</title>
[...]
<h1>
{% block title %}{% endblock %} - example.com
</h1>
```
Jinja2, then, fails with the following message:
```
lines = [self.message, ' ' + location]
: block 'title'... | As documented [here](http://jinja.pocoo.org/2/documentation/templates#child-template), defining a block creates a macro with the name of the block in the special "self" object:
```
<title>{% block title %}{% endblock %} - example.com</title>
[...]
<h1>
{{ self.title() }} - example.com
</h1>
``` |
why does this python program print True | 1,242,460 | 7 | 2009-08-07T01:35:47Z | 1,242,467 | 18 | 2009-08-07T01:37:55Z | [
"python"
] | ```
x=True
def stupid():
x=False
stupid()
print x
``` | You don't need to declare a function-local variable in Python. The "x=False" is referring to an x local to stupid(). If you really want to modify the global x inside stupid:
```
def stupid():
global x
x=False
``` |
why does this python program print True | 1,242,460 | 7 | 2009-08-07T01:35:47Z | 1,242,483 | 10 | 2009-08-07T01:40:10Z | [
"python"
] | ```
x=True
def stupid():
x=False
stupid()
print x
``` | To answer your next question, use `global`:
```
x=True
def stupid():
global x
x=False
stupid()
print x
``` |
subclassing int to attain a Hex representation | 1,242,589 | 2 | 2009-08-07T02:24:52Z | 1,242,640 | 7 | 2009-08-07T02:49:45Z | [
"python",
"hex",
"subclassing",
"representation"
] | Basically I want to have access to all standard python int operators, eg `__and__` and `__xor__` etc, specifically whenever the result is finally printed I want it represented in Hex format. (Kind of like putting my calculator into Hex mode)
```
class Hex(int):
def __repr__(self):
return "0x%x"%self
__str__=__... | You should define `__repr__` and `__str__` separately:
```
class Hex(int):
def __repr__(self):
return "Hex(0x%x)" % self
def __str__(self):
return "0x%x" % self
```
The `__repr__` function should (if possible) provide Python text that can be `eval()`uated to reconstruct the original object. On the other h... |
Beautiful Soup cannot find a CSS class if the object has other classes, too | 1,242,755 | 34 | 2009-08-07T03:34:19Z | 1,242,801 | 32 | 2009-08-07T03:49:51Z | [
"python",
"screen-scraping",
"beautifulsoup"
] | if a page has `<div class="class1">` and `<p class="class1">`, then `soup.findAll(True, 'class1')` will find them both.
If it has `<p class="class1 class2">`, though, it will not be found. How do I find all objects with a certain class, regardless of whether they have other classes, too? | Unfortunately, BeautifulSoup treats this as a class with a space in it `'class1 class2'` rather than two classes `['class1','class2']`. A workaround is to use a regular expression to search for the class instead of a string.
This works:
```
soup.findAll(True, {'class': re.compile(r'\bclass1\b')})
``` |
Beautiful Soup cannot find a CSS class if the object has other classes, too | 1,242,755 | 34 | 2009-08-07T03:34:19Z | 1,245,368 | 10 | 2009-08-07T15:18:07Z | [
"python",
"screen-scraping",
"beautifulsoup"
] | if a page has `<div class="class1">` and `<p class="class1">`, then `soup.findAll(True, 'class1')` will find them both.
If it has `<p class="class1 class2">`, though, it will not be found. How do I find all objects with a certain class, regardless of whether they have other classes, too? | You should use [lxml](http://lxml.de/). It works with multiple class values separated by spaces ('class1 class2').
Despite its name, lxml is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles "broken" HTML better than BeautifulSoup (their claim to fame). It has a compati... |
Beautiful Soup cannot find a CSS class if the object has other classes, too | 1,242,755 | 34 | 2009-08-07T03:34:19Z | 18,424,791 | 14 | 2013-08-25T01:28:49Z | [
"python",
"screen-scraping",
"beautifulsoup"
] | if a page has `<div class="class1">` and `<p class="class1">`, then `soup.findAll(True, 'class1')` will find them both.
If it has `<p class="class1 class2">`, though, it will not be found. How do I find all objects with a certain class, regardless of whether they have other classes, too? | Just in case anybody comes across this question. BeautifulSoup now supports this:
```
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.
In [1]: import bs4
In [2]: soup = bs4.BeautifulSoup('<div class="foo bar"></div>')
In [3]: so... |
Programmatically extract data from an Excel spreadsheet | 1,243,545 | 6 | 2009-08-07T08:13:54Z | 1,243,628 | 8 | 2009-08-07T08:38:03Z | [
"python",
"ruby",
"perl",
"excel",
"csv"
] | Is there a simple way, using some common Unix scripting language (Perl/Python/Ruby) or command line utility, to convert an Excel Spreadsheet file to CSV? Specifically, this one:
<http://www.econ.yale.edu/~shiller/data/ie_data.xls>
And specifically the third sheet of that spreadsheet (the first two being charts). | Maybe [xlrd](http://pypi.python.org/pypi/xlrd) will do the Job (in Python)
edit: I should really learn to read questions. But writing csv shouldn't be a huge problem so maybe you can actually use it. |
Programmatically extract data from an Excel spreadsheet | 1,243,545 | 6 | 2009-08-07T08:13:54Z | 1,243,763 | 14 | 2009-08-07T09:15:30Z | [
"python",
"ruby",
"perl",
"excel",
"csv"
] | Is there a simple way, using some common Unix scripting language (Perl/Python/Ruby) or command line utility, to convert an Excel Spreadsheet file to CSV? Specifically, this one:
<http://www.econ.yale.edu/~shiller/data/ie_data.xls>
And specifically the third sheet of that spreadsheet (the first two being charts). | There is a really good Perl library for xls reading: [Spreadsheet::ParseExcel](http://search.cpan.org/perldoc/Spreadsheet::ParseExcel). |
Disable console output from subprocess.Popen in Python | 1,244,723 | 8 | 2009-08-07T13:34:45Z | 1,244,757 | 7 | 2009-08-07T13:41:08Z | [
"python",
"console",
"subprocess",
"popen"
] | I run Python 2.5 on Windows, and somewhere in the code I have
```
subprocess.Popen("taskkill /PID " + str(p.pid))
```
to kill IE window by pid. The problem is that without setting up piping in Popen I still get output to console - SUCCESS: The process with PID 2068 has been terminated. I debugged it to CreateProcess ... | ```
fh = open("NUL","w")
subprocess.Popen("taskkill /PID " + str(p.pid), stdout = fh, stderr = fh)
fh.close()
``` |
Disable console output from subprocess.Popen in Python | 1,244,723 | 8 | 2009-08-07T13:34:45Z | 1,246,714 | 11 | 2009-08-07T19:58:22Z | [
"python",
"console",
"subprocess",
"popen"
] | I run Python 2.5 on Windows, and somewhere in the code I have
```
subprocess.Popen("taskkill /PID " + str(p.pid))
```
to kill IE window by pid. The problem is that without setting up piping in Popen I still get output to console - SUCCESS: The process with PID 2068 has been terminated. I debugged it to CreateProcess ... | ```
import os
from subprocess import check_call, STDOUT
DEVNULL = open(os.devnull, 'wb')
try:
check_call(("taskkill", "/PID", str(p.pid)), stdout=DEVNULL, stderr=STDOUT)
finally:
DEVNULL.close()
```
I always pass in tuples to subprocess as it saves me worrying about escaping. check\_call ensures (a) the subpr... |
Python library for converting files to MP3 and setting their quality | 1,246,131 | 8 | 2009-08-07T17:51:39Z | 12,391,523 | 12 | 2012-09-12T15:23:23Z | [
"python",
"audio",
"compression"
] | I'm trying to find a Python library that would take an audio file (e.g. .ogg, .wav) and convert it into mp3 for playback on a webpage.
Also, any thoughts on setting its quality for playback would be great.
Thank you. | I wrote [a library](http://pydub.com) designed to do that =D
```
from pydub import AudioSegment
AudioSegment.from_file("/input/file").export("/output/file", format="mp3")
```
Easy!
to specify a bitrate, just use the `bitrate` kwargâ¦
```
from pydub import AudioSegment
sound = AudioSegment.from_file("/input/file")
... |
convert string to dict using list comprehension in python | 1,246,444 | 15 | 2009-08-07T19:00:32Z | 1,246,470 | 27 | 2009-08-07T19:07:15Z | [
"python",
"string",
"dictionary",
"list-comprehension",
"generator-expression"
] | I have came across this problem a few times and can't seem to figure out a simple solution.
Say I have a string
```
string = "a=0 b=1 c=3"
```
I want to convert that into a dictionary with a, b and c being the key and 0, 1, and 3 being their respective values (converted to int). Obviously I can do this:
```
... | Do you mean this?
```
>>> dict( (n,int(v)) for n,v in (a.split('=') for a in string.split() ) )
{'a': 0, 'c': 3, 'b': 1}
``` |
Python List Comprehension Vs. Map | 1,247,486 | 376 | 2009-08-07T23:43:31Z | 1,247,490 | 360 | 2009-08-07T23:45:23Z | [
"python",
"list-comprehension",
"map-function"
] | Is there a reason to prefer using `map()` over list comprehension or vice versa? Is one generally more effecient or generally considered more pythonic than the other? | `map` may be microscopically faster in some cases (when you're NOT making a lambda for the purpose, but using the same function in map and a listcomp). List comprehensions may be faster in other cases and most (not all) pythonistas consider them more direct and clearer.
An example of the tiny speed advantage of map wh... |
Python List Comprehension Vs. Map | 1,247,486 | 376 | 2009-08-07T23:43:31Z | 1,247,531 | 14 | 2009-08-07T23:59:05Z | [
"python",
"list-comprehension",
"map-function"
] | Is there a reason to prefer using `map()` over list comprehension or vice versa? Is one generally more effecient or generally considered more pythonic than the other? | I find list comprehensions are generally more expressive of what I'm trying to do than `map` - they both get it done, but the former saves the mental load of trying to understand what could be a complex `lambda` expression.
There's also an interview out there somewhere (I can't find it offhand) where Guido lists `lamb... |
Python List Comprehension Vs. Map | 1,247,486 | 376 | 2009-08-07T23:43:31Z | 1,660,062 | 8 | 2009-11-02T08:42:48Z | [
"python",
"list-comprehension",
"map-function"
] | Is there a reason to prefer using `map()` over list comprehension or vice versa? Is one generally more effecient or generally considered more pythonic than the other? | Here is one possible case:
```
map(lambda op1,op2: op1*op2, list1, list2)
```
versus:
```
[op1*op2 for op1,op2 in zip(list1,list2)]
```
I am guessing the zip() is an unfortunate and unnecessary overhead you need to indulge in if you insist on using list comprehensions instead of the map. Would be great if someone c... |
Python List Comprehension Vs. Map | 1,247,486 | 376 | 2009-08-07T23:43:31Z | 6,407,222 | 244 | 2011-06-20T05:41:27Z | [
"python",
"list-comprehension",
"map-function"
] | Is there a reason to prefer using `map()` over list comprehension or vice versa? Is one generally more effecient or generally considered more pythonic than the other? | **Cases**
* **Common case**: Almost always, you will want to use a list comprehension in *python* because it will be more obvious what you're doing to novice programmers reading your code. (This does not apply to other languages, where other idioms may apply.) It will even be more obvious what you're doing to python p... |
Python List Comprehension Vs. Map | 1,247,486 | 376 | 2009-08-07T23:43:31Z | 13,483,314 | 46 | 2012-11-20T22:28:55Z | [
"python",
"list-comprehension",
"map-function"
] | Is there a reason to prefer using `map()` over list comprehension or vice versa? Is one generally more effecient or generally considered more pythonic than the other? | ## You should use `map` and `filter` instead of list comprehensions.
An **objective** reason why you should prefer them even though they're not "Pythonic" is this:
They require functions/lambdas as arguments, which **introduce a new scope**.
I've gotten bitten by this more than once:
```
for x, y in somePoints:
... |
Python List Comprehension Vs. Map | 1,247,486 | 376 | 2009-08-07T23:43:31Z | 19,117,067 | 23 | 2013-10-01T13:09:13Z | [
"python",
"list-comprehension",
"map-function"
] | Is there a reason to prefer using `map()` over list comprehension or vice versa? Is one generally more effecient or generally considered more pythonic than the other? | Actually, `map` and list comprehensions behave quite differently in the Python 3 language. Take a look at the following Python 3 program:
```
def square(x):
return x*x
squares = map(square, [1, 2, 3])
print(list(squares))
print(list(squares))
```
You might expect it to print the line "[1, 4, 9]" twice, but instea... |
Python List Comprehension Vs. Map | 1,247,486 | 376 | 2009-08-07T23:43:31Z | 24,108,573 | 8 | 2014-06-08T17:03:13Z | [
"python",
"list-comprehension",
"map-function"
] | Is there a reason to prefer using `map()` over list comprehension or vice versa? Is one generally more effecient or generally considered more pythonic than the other? | If you plan on writing any asynchronous, parallel, or distributed code, you will probably prefer `map` over a list comprehension -- as most asynchronous, parallel, or distributed packages provide a `map` function to overload python's `map`. Then by passing the appropriate `map` function to the rest of your code, you ma... |
Is this a good or bad 'simulation' for Monty Hall? How come? | 1,247,863 | 14 | 2009-08-08T03:13:17Z | 1,247,888 | 32 | 2009-08-08T03:28:15Z | [
"python",
"language-agnostic",
"probability"
] | Through trying to explain the [Monty Hall problem](http://en.wikipedia.org/wiki/Monty_Hall_problem) to a friend during class yesterday, we ended up coding it in Python to prove that if you always swap, you will win 2/3 times. We came up with this:
```
import random as r
#iterations = int(raw_input("How many iteration... | Your solution is fine, but if you want a stricter simulation of the problem as posed (and somewhat higher-quality Python;-), try:
```
import random
iterations = 100000
doors = ["goat"] * 2 + ["car"]
change_wins = 0
change_loses = 0
for i in xrange(iterations):
random.shuffle(doors)
# you pick door n:
n ... |
Coroutines for game design? | 1,247,894 | 16 | 2009-08-08T03:31:01Z | 1,247,985 | 9 | 2009-08-08T04:35:05Z | [
"python",
"coroutine"
] | I've heard that coroutines are a good way to structure games (e.g., [PEP 342](http://www.python.org/dev/peps/pep-0342/): "Coroutines are a natural way of expressing many algorithms, such as simulations, games...") but I'm having a hard time wrapping my head around how this would actually be done.
I see from this [arti... | Coroutines allow for creating large amounts of very-lightweight "microthreads" with cooperative multitasking (i.e. microthreads suspending themselves willfully to allow other microthreads to run). Read up in Dave Beazley's [article](http://www.dabeaz.com/coroutines/) on this subject.
Now, it's obvious how such microth... |
Coroutines for game design? | 1,247,894 | 16 | 2009-08-08T03:31:01Z | 1,247,990 | 7 | 2009-08-08T04:37:30Z | [
"python",
"coroutine"
] | I've heard that coroutines are a good way to structure games (e.g., [PEP 342](http://www.python.org/dev/peps/pep-0342/): "Coroutines are a natural way of expressing many algorithms, such as simulations, games...") but I'm having a hard time wrapping my head around how this would actually be done.
I see from this [arti... | One way coroutines can be used in games is as light weight threads in an actor like model, like in [Kamaelia](http://www.kamaelia.org/Home).
Each object in your game would be a Kamaelia 'component'. A component is an object that can pause execution by yielding when it's allowable to pause. These components also have a... |
Coroutines for game design? | 1,247,894 | 16 | 2009-08-08T03:31:01Z | 1,250,992 | 8 | 2009-08-09T09:11:34Z | [
"python",
"coroutine"
] | I've heard that coroutines are a good way to structure games (e.g., [PEP 342](http://www.python.org/dev/peps/pep-0342/): "Coroutines are a natural way of expressing many algorithms, such as simulations, games...") but I'm having a hard time wrapping my head around how this would actually be done.
I see from this [arti... | The most prominent case of coroutines are probally old graphical point&click adventure games, where they where used to script cutscenes and other animated sequences in the game. A simple code example would look like this:
```
# script_file.scr
bob.walkto(jane)
bob.lookat(jane)
bob.say("How are you?")
wait(2)
jane.say(... |
What does the "s!" operator in Perl do? | 1,248,812 | 4 | 2009-08-08T12:53:43Z | 1,248,825 | 15 | 2009-08-08T12:59:14Z | [
"python",
"regex",
"perl"
] | I have this Perl snippet from a script that I am translating into Python. I have no idea what the "s!" operator is doing; some sort of regex substitution. Unfortunately searching Google or Stackoverflow for operators like that doesn't yield many helpful results.
```
$var =~ s!<foo>.+?</foo>!!;
$var =~ s!;!/!g;
```
... | `s!foo!bar!` is the same as the more common `s/foo/bar/`, except that foo and bar can contain unescaped slashes without causing problems. What it does is, it replaces the first occurence of the regex foo with bar. The version with g replaces all occurences. |
What does the "s!" operator in Perl do? | 1,248,812 | 4 | 2009-08-08T12:53:43Z | 1,248,832 | 13 | 2009-08-08T13:01:40Z | [
"python",
"regex",
"perl"
] | I have this Perl snippet from a script that I am translating into Python. I have no idea what the "s!" operator is doing; some sort of regex substitution. Unfortunately searching Google or Stackoverflow for operators like that doesn't yield many helpful results.
```
$var =~ s!<foo>.+?</foo>!!;
$var =~ s!;!/!g;
```
... | It's doing exactly the same as `$var =~ s///`. i.e. performing a search and replace within the `$var` variable.
In Perl you can define the delimiting character following the `s`. Why ? So, for example, if you're matching '/', you can specify another delimiting character ('!' in this case) and not have to escape or bac... |
What does the "s!" operator in Perl do? | 1,248,812 | 4 | 2009-08-08T12:53:43Z | 1,248,841 | 10 | 2009-08-08T13:02:43Z | [
"python",
"regex",
"perl"
] | I have this Perl snippet from a script that I am translating into Python. I have no idea what the "s!" operator is doing; some sort of regex substitution. Unfortunately searching Google or Stackoverflow for operators like that doesn't yield many helpful results.
```
$var =~ s!<foo>.+?</foo>!!;
$var =~ s!;!/!g;
```
... | Perl lets you choose the delimiter for many of its constructs. This makes it easier to see what is going on in expressions like
```
$str =~ s{/foo/bar/baz/}{/quux/};
```
As you can see though, not all delimiters have the same effects. Bracketing characters (`<>`, `[]`, `{}`, and `()`) use different characters for the... |
Best practise when using httplib2.Http() object | 1,248,926 | 6 | 2009-08-08T13:53:34Z | 2,628,458 | 7 | 2010-04-13T09:38:57Z | [
"python",
"httplib2"
] | I'm writing a pythonic web API wrapper with a class like this
```
import httplib2
import urllib
class apiWrapper:
def __init__(self):
self.http = httplib2.Http()
def _http(self, url, method, dict):
'''
Im using this wrapper arround the http object
all the time inside the class
'''
... | Supplying 'connection': 'close' in your headers should according to the docs close the connection after a response is received.:
```
headers = {'connection': 'close'}
resp, content = h.request(url, headers=headers)
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.