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 |
|---|---|---|---|---|---|---|---|---|---|
Accessing dict keys like an attribute in Python? | 4,984,647 | 142 | 2011-02-13T14:23:18Z | 5,021,467 | 47 | 2011-02-16T19:59:50Z | [
"python",
"dictionary"
] | I find it more conveniant to access dict keys as `obj.foo` instead of `obj['foo']`, so I wrote this snippet:
```
class AttributeDict(dict):
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
```
However, I assume there must be some reason that... | From [This other SO question](http://stackoverflow.com/questions/5021041/are-there-any-gotchas-with-this-python-pattern) there's a great implementation example that simplifies your existing code. How about:
```
class AttributeDict(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
```
Much ... |
Accessing dict keys like an attribute in Python? | 4,984,647 | 142 | 2011-02-13T14:23:18Z | 13,485,972 | 14 | 2012-11-21T03:38:51Z | [
"python",
"dictionary"
] | I find it more conveniant to access dict keys as `obj.foo` instead of `obj['foo']`, so I wrote this snippet:
```
class AttributeDict(dict):
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
```
However, I assume there must be some reason that... | Caveat emptor: For some reasons classes like this seem to break the multiprocessing package. I just struggled with this bug for awhile before finding this SO:
[Finding exception in python multiprocessing](http://stackoverflow.com/questions/10819447/finding-exception-in-python-multiprocessing) |
Accessing dict keys like an attribute in Python? | 4,984,647 | 142 | 2011-02-13T14:23:18Z | 14,620,633 | 151 | 2013-01-31T07:33:21Z | [
"python",
"dictionary"
] | I find it more conveniant to access dict keys as `obj.foo` instead of `obj['foo']`, so I wrote this snippet:
```
class AttributeDict(dict):
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
```
However, I assume there must be some reason that... | The best way to do this is:
```
class AttrDict(dict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
self.__dict__ = self
```
Some pros:
* It actually works!
* No dictionary class methods are shadowed (e.g. `.keys()` work just fine)
* Attributes and items are... |
Accessing dict keys like an attribute in Python? | 4,984,647 | 142 | 2011-02-13T14:23:18Z | 24,017,468 | 8 | 2014-06-03T14:12:56Z | [
"python",
"dictionary"
] | I find it more conveniant to access dict keys as `obj.foo` instead of `obj['foo']`, so I wrote this snippet:
```
class AttributeDict(dict):
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
```
However, I assume there must be some reason that... | You can pull a convenient container class from the standard library:
```
from argparse import Namespace
```
to avoid having to copy around code bits. No standard dictionary access, but easy to get one back if you really want it. The code in argparse is simple,
```
class Namespace(_AttributeHolder):
"""Simple obj... |
Accessing dict keys like an attribute in Python? | 4,984,647 | 142 | 2011-02-13T14:23:18Z | 29,548,234 | 22 | 2015-04-09T20:21:58Z | [
"python",
"dictionary"
] | I find it more conveniant to access dict keys as `obj.foo` instead of `obj['foo']`, so I wrote this snippet:
```
class AttributeDict(dict):
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
```
However, I assume there must be some reason that... | # Wherein I Answer the Question That Was Asked
## Why doesn't Python offer it out of the box?
I suspect that it has to do with the [Zen of Python](https://www.python.org/dev/peps/pep-0020/): "There should be one -- and preferably only one -- obvious way to do it." This would create two obvious ways to access values f... |
Why circular referenced objects with __del__ defined are uncollectable in Python? | 4,984,849 | 5 | 2011-02-13T15:04:07Z | 4,984,934 | 7 | 2011-02-13T15:19:26Z | [
"python"
] | Will it cause memory leak if they cannot be cleaned by GC? | It's a standard issue with garbage collection.
It's not about memory leaks, but about the circular references themselves, and about other kinds of resources managed by those objects that may need cleanup. The references create a dependency - you can't delete the referrer until all objects it references are deleted, be... |
No module named _imagingft | 4,984,979 | 4 | 2011-02-13T15:28:22Z | 8,773,615 | 13 | 2012-01-07T22:26:32Z | [
"python",
"django"
] | I have this problem:
```
No module named _imagingft
```
I have installed PIL, but it still does not work. I use OSX.
I'm trying to install this module for [Django Simple Captcha](http://code.google.com/p/django-simple-captcha/). | Installing Pillow over existing PIL solved the issue for me:
```
$ sudo easy_install PIL
$ sudo easy_install Pillow
``` |
Build HTTP GET request with port number and parameters | 4,985,118 | 5 | 2011-02-13T15:49:00Z | 4,985,231 | 11 | 2011-02-13T16:11:32Z | [
"python",
"http",
"get",
"request"
] | I am trying to do a very simple thing, build an URL for a get request that contains a port number and some parameters, as it follows `http://localhost:8080/read?date=whatever`
I have tried several ways without success, it shouldn't be too difficult but i cannot come up with a solution.
I hope someone helps me, it wou... | The previous answer was not to the question you actually asked. Try this:
```
import urllib
myPort = "8080"
myParameters = { "date" : "whatever", "another_parameters" : "more_whatever" }
myURL = "http://localhost:%s/read?%s" % (myPort, urllib.urlencode(myParameters))
```
Basically, urllib has a function to do what ... |
enable pretty printing for gdb in eclipse cdt | 4,985,414 | 33 | 2011-02-13T16:42:05Z | 5,713,387 | 50 | 2011-04-19T08:07:01Z | [
"c++",
"python",
"gdb",
"eclipse-cdt",
"gdb-python"
] | I'm trying to add pretty printing for STL objects in eclipse cdt. I tried to follow the steps described here:
<http://sourceware.org/gdb/wiki/STLSupport>
I checked out the python folder, but I can't seem to get this done...
I created a gdbinit and selected for my debug configuration, but whenever I try to start debu... | This is the solution that works for me.
Download ( <http://www.gnu.org/software/gdb/download/>) and install latest gdb (i.e. with --prefix $HOME). It supports python scripting.
Get python pretty printers by executing
> svn co svn://gcc.gnu.org/svn/gcc/trunk/libstdc++-v3/python
in a directory of your choice (i.e. $(... |
enable pretty printing for gdb in eclipse cdt | 4,985,414 | 33 | 2011-02-13T16:42:05Z | 9,537,550 | 9 | 2012-03-02T17:17:43Z | [
"c++",
"python",
"gdb",
"eclipse-cdt",
"gdb-python"
] | I'm trying to add pretty printing for STL objects in eclipse cdt. I tried to follow the steps described here:
<http://sourceware.org/gdb/wiki/STLSupport>
I checked out the python folder, but I can't seem to get this done...
I created a gdbinit and selected for my debug configuration, but whenever I try to start debu... | I know this does not answer the original question, but I thought it might be useful for those who debug in Eclipse on **Windows / MinGW**. The procedure for Windows is similar:
1) Get Python 2.7.x from <http://python.org/download/>
2) Create `.gdbinit` somewhere containing something like this:
```
python
import sys
... |
SqlAlchemy - Filtering by field defined as a ForeignKey | 4,985,762 | 6 | 2011-02-13T17:43:30Z | 4,985,898 | 9 | 2011-02-13T18:09:06Z | [
"python",
"sqlalchemy",
"relational-database",
"foreign-key-relationship"
] | I am trying to get instances of a class filtered by a field which is a foreign key but when I try to do that, I always get all the entries in the database, instead of the ones that match the criterion.
Let's say I have a couple of classes using declarative base in a simple relationship N:1. I have that modeled like:
... | For a simple query, you can just query directly:
```
session.query(WhateverClass).filter(WhateverClass._containerClassId == 5).all()
```
For more complex relationships, you need a join:
```
session.query(WhateverClass).join(ContainerClass).filter(ContainerClass.id == 5).all()
``` |
Alternative to virsh (libvirt) | 4,986,076 | 7 | 2011-02-13T18:43:09Z | 4,986,646 | 13 | 2011-02-13T20:25:21Z | [
"python",
"list",
"virtual-machine",
"libvirt"
] | I am using virsh list to display the list of vms running on the computer. I want the information printed in the process in the form of a 2d array.
One way to go about this is to have the output, use tokenizer and store it in the array. But is there some other way where I can get directly this into the form of an array... | There are indeed [libvirt Python API bindings](http://libvirt.org/python.html).
```
import libvirt
conn = libvirt.openReadOnly(None) # $LIBVIRT_DEFAULT_URI, or give a URI here
assert conn, 'Failed to open connection'
names = conn.listDefinedDomains()
domains = map(conn.lookupByName, names)
ids = conn.listDomainsID... |
Why won't my script write to a file? | 4,986,463 | 2 | 2011-02-13T19:50:18Z | 4,986,475 | 7 | 2011-02-13T19:53:38Z | [
"python",
"linux",
"file",
"unix"
] | ```
import time
import traceback
import sys
import tools
from BeautifulSoup import BeautifulSoup
f = open("randomwords.txt","w")
while 1:
try:
page = tools.download("http://wordnik.com/random")
soup = BeautifulSoup(page)
si = soup.find("h1")
w = si.string
print w
f.w... | You can never leave the while loop, hence the `f.close()` call will never be called and the stream buffer to the file will never be flushed.
Let me explain a little bit further, in your exception catch statement you've included `continue` so there's no "exit" to the loop condition. Perhaps you should add some sort of ... |
Taking a screenshot with Pyglet [Fix'd] | 4,986,662 | 6 | 2011-02-13T20:27:21Z | 5,094,663 | 8 | 2011-02-23T17:39:30Z | [
"python",
"events",
"screenshot",
"pyglet"
] | In the pyglet docs, I found:
> The following example shows how to
> grab a screenshot of your application
> window:
> `pyglet.image.get_buffer_manager().get_color_buffer().save('screenshot.png')`
However when using this, everything will stop until I click the mouse. Is there another way to get the screen contents in ... | Okay, here is a complete working example in pyglet. It shows the text "hello world" taking a random walk around the window and dumps the screenshot (using the exact same line of code you posted) every time you press a key.
```
import pyglet, random
window = pyglet.window.Window()
label = pyglet.text.Label('Hello, wo... |
Step by step setting up python with pip and virtualenv? | 4,986,896 | 4 | 2011-02-13T21:11:23Z | 4,987,346 | 8 | 2011-02-13T22:29:38Z | [
"python"
] | Are there any good step by step tutorials on setting up a Mac to use python, pip and virtualenv setup? | Download and install the [Python 2.7.1 Mac OS X 64-bit/32-bit x86-64/i386 Installer (for Mac OS X 10.6)](http://python.org/download/) or [Python 2.7.1 Mac OS X 32-bit i386/PPC Installer (for Mac OS X 10.3 through 10.6)](http://python.org/download/).
## Instructions for installing virtualenv and pip on OS X
This is ho... |
Is ipython a replacement or it works side by side with regular python? | 4,986,938 | 4 | 2011-02-13T21:19:30Z | 4,986,950 | 8 | 2011-02-13T21:20:57Z | [
"python"
] | Is ipython just a better shell environment that uses the same libs/packages that the regular python interpreter will use? | > Is ipython just a better shell environment that uses the same libs/packages that the regular python interpreter will use?
Yes. It is an advanced interactive shell and an environment for parallel computing (but most people only use it as an interactive shell). |
What is the most efficient way to traverse a tree in Python? | 4,986,988 | 5 | 2011-02-13T21:26:49Z | 4,987,080 | 7 | 2011-02-13T21:41:13Z | [
"python",
"tree",
"traversal"
] | Assuming I have a list of objects that have the following fields
**parent**
**value**
and this defines a tree structure, similar to a directory tree.
I want to traverse the list in a pre-order fashion. What's the most efficient way?
Normally, in other (more imperative) languages I would iterate the values, finding... | I would first create a more suitable data structure -- capturing the link from a parent to its children:
```
children = {}
for obj in tree:
children.setdefault(obj.parent, []).append(obj)
def preorder(root, children):
yield root.value
for child in children.get(root, []):
for value in preorder(chil... |
Python PIL image reproduction | 4,987,070 | 2 | 2011-02-13T21:39:27Z | 4,987,120 | 9 | 2011-02-13T21:47:17Z | [
"python",
"image",
"image-processing",
"python-imaging-library"
] | I am new to PIL and Python and I have a question related to the API.
I have an Image
```
img = Image.new('RGB', (1, 2))
```
And I have a list of tuples
```
x = [(255, 255, 255), (255, 255, 255)]
```
I do `img.putdata(x)`
and `img.save('C:\\somename.jpeg')`
Later on when I reload the Image and do
```
img2 = Imag... | jpeg is a lossy compression format and doesn't guarantee pixel by pixel reproduction. Try saving the image in a lossless format. |
Python sending command over a socket | 4,987,077 | 4 | 2011-02-13T21:40:44Z | 4,987,117 | 7 | 2011-02-13T21:47:03Z | [
"python",
"client",
"subprocess",
"execution"
] | I'm having a bit of trouble. I want to create a simple program that connects to the server and executes a command using subprocess then returns the result to the client. It's simple but I can't get it to work. Right now this is what I have:
client:
```
import sys, socket, subprocess
conn = socket.socket(socket.AF_INET... | Danger, Will Robinson!!!
Do you really want to send commands in clear text without authentication over the network? It is very, very dangerous.
Do it over SSH with [paramiko](http://www.lag.net/paramiko/).
> Alright I've heard this answer too many times. I don't want to use SSH I'm just building it to learn more abo... |
virtualenv --no-site-packages is not working for me | 4,987,230 | 7 | 2011-02-13T22:08:45Z | 4,990,348 | 9 | 2011-02-14T09:03:54Z | [
"python",
"virtualenv"
] | ```
virtualenv --no-site-packages v1
cd v1\Scripts
activate.bat
python -c "import django" # - no problem here
```
Why does it see the Django package??? It should give me an import error, right? | Just unset `PYTHONPATH` environment variable. The idea of virtualenv is that you can create your own environment (fully isolated or extending the default one) so you don't have to mess with that.
As someone noticed there's already been [a similar question on SO](http://stackoverflow.com/questions/2961103/virtualenv-on... |
How do I check if a string is unicode or ascii? | 4,987,327 | 123 | 2011-02-13T22:27:03Z | 4,987,367 | 71 | 2011-02-13T22:33:39Z | [
"python",
"unicode",
"encoding",
"utf-8"
] | What do I have to do in Python to figure out which encoding? | Just do
```
type(s)
```
One will say `unicode`, the other will say `str`.
You can handle them separately using `isinstance`, e.g.
```
if isinstance(s, str):
print 's is a string object'
elif isinstance(s, unicode):
print 's is a unicode object'
```
Or do you mean you have a `str`, and you are trying to fig... |
How do I check if a string is unicode or ascii? | 4,987,327 | 123 | 2011-02-13T22:27:03Z | 4,987,414 | 168 | 2011-02-13T22:40:50Z | [
"python",
"unicode",
"encoding",
"utf-8"
] | What do I have to do in Python to figure out which encoding? | In Python 3, all strings are sequences of Unicode characters. There is a `bytes` type that holds raw bytes.
In Python 2, a string may be of type `str` or of type `unicode`. You can tell which using code something like this:
```
def whatisthis(s):
if isinstance(s, str):
print "ordinary string"
elif isi... |
How do I check if a string is unicode or ascii? | 4,987,327 | 123 | 2011-02-13T22:27:03Z | 10,686,911 | 27 | 2012-05-21T14:12:19Z | [
"python",
"unicode",
"encoding",
"utf-8"
] | What do I have to do in Python to figure out which encoding? | Unicode is not an encoding - to quote Kumar McMillan:
> If ASCII, UTF-8, and other byte strings are "text" ...
>
> ...then Unicode is "text-ness";
>
> it is the abstract form of text
Have a read of McMillan's [Unicode In Python, Completely Demystified](http://farmdev.com/talks/unicode/) talk from PyCon 2008, it expla... |
How do I check if a string is unicode or ascii? | 4,987,327 | 123 | 2011-02-13T22:27:03Z | 11,952,359 | 15 | 2012-08-14T12:33:05Z | [
"python",
"unicode",
"encoding",
"utf-8"
] | What do I have to do in Python to figure out which encoding? | If your code needs to be compatible with **both** Python 2 and Python 3, you can't directly use things like `isinstance(s,bytes)` or `isinstance(s,unicode)` without wrapping them in either try/except or a python version test, because `bytes` is undefined in Python 2 and `unicode` is undefined in Python 3.
There are so... |
How do I check if a string is unicode or ascii? | 4,987,327 | 123 | 2011-02-13T22:27:03Z | 18,706,449 | 20 | 2013-09-09T20:24:54Z | [
"python",
"unicode",
"encoding",
"utf-8"
] | What do I have to do in Python to figure out which encoding? | In python 3.x all strings are sequences of Unicode characters. and doing the isinstance check for str (which means unicode string by default) should suffice.
```
isinstance(x, str)
```
With regards to python 2.x,
Most people seem to be using an if statement that has two checks. one for str and one for unicode.
If yo... |
Error: No module named staticfiles | 4,987,333 | 20 | 2011-02-13T22:27:57Z | 4,987,398 | 30 | 2011-02-13T22:38:32Z | [
"python",
"django",
"deployment",
"nginx"
] | I'm newbie with django, I'm trying to deploy my project on a production server but I'm getting this error:
```
Error: No module named staticfiles
```
When trying to start the server:
```
python manage.py runfcgi host=127.0.0.1 port=8081 --settings=settings
```
with the fastCGI + nginx
Any idea?
Thanks! | You're probably using older version of Django. staticfiles app has been available from version 1.3 only. |
Inside a decorator-class, access instance of the class which contains the decorated method | 4,987,471 | 8 | 2011-02-13T22:50:01Z | 4,987,488 | 11 | 2011-02-13T22:56:31Z | [
"python",
"decorator"
] | I have the following decorator, which saves a configuration file after a method decorated with `@saveconfig` is called:
```
class saveconfig(object):
def __init__(self, f):
self.f = f
def __call__(self, *args):
self.f(object, *args)
# Here i want to access "cfg" defined in pbtools
... | You have to make your decorator class behave as a [descriptor](http://docs.python.org/reference/datamodel.html#implementing-descriptors) to be able to access the instance:
```
class saveconfig(object):
def __init__(self, f):
self.f = f
def __get__(self, instance, owner):
def wrapper(*args):
... |
Python correctness (i.e., lint) analyzing for Notepad++ | 4,987,920 | 10 | 2011-02-14T00:32:35Z | 6,273,211 | 11 | 2011-06-08T01:03:57Z | [
"python",
"ide",
"notepad++",
"pylint",
"pychecker"
] | Does anyone know of anything like [pylint](http://www.logilab.org/857) or [pychecker](http://pychecker.sourceforge.net/) for notepad++? Or perhaps how to use pylint in notepad++. | If you install the [Python Script plugin](http://npppythonscript.sourceforge.net/docs/latest/index.html), then you can add a new script with the following lines to get pretty good results:
```
console.show()
console.clear()
console.run('cmd.exe /c '
+ 'C:\\Python26\\Scripts\\pylint.bat --reports=n -f parse... |
Shortest way to slice even/odd lines from a python array? | 4,988,002 | 37 | 2011-02-14T00:55:29Z | 4,988,012 | 83 | 2011-02-14T00:57:27Z | [
"python",
"arrays"
] | Or, a more general question would be, how to slice an array to get every n-th line, so for even/odd you'd want to skip one line, but in the general case you'd want to get every n-th lines, skipping n-1 lines. | Assuming you are talking about a *list*, you specify the step in the slice (and start index). The syntax is `list[start:end:step]`.
You probably know the normal list access to get an item, e.g. `l[2]` to get the third item. Giving two numbers and a colon in between, you can specify a *range* that you want to get from ... |
Installed pip, but can't find where the virtualenvwrapper_bashrc | 4,988,235 | 3 | 2011-02-14T02:03:21Z | 4,988,250 | 10 | 2011-02-14T02:05:53Z | [
"python",
"pip"
] | How can I find out where the virtualenvwrapper\_bashrc file is?
I'm looking in:
```
/System/Library/Frameworks/Python.framework/Versions/2.6/bin
```
But I don't see it? | You say that you installed `pip`, but you don't say whether or not you installed `virtualenvwrapper`, which is neither included with `pip` nor `virtualenv`.
If you have installed `virtualenvwrapper` using
```
pip install virtualenvwrapper
```
or something similar, then you can use the following to find where it is l... |
Trying to get Scrapy into a project to run Crawl command | 4,988,297 | 6 | 2011-02-14T02:18:03Z | 5,019,817 | 7 | 2011-02-16T17:26:12Z | [
"python",
"scrapy",
"web-crawler"
] | I'm new to Python and Scrapy and I'm walking through the Scrapy tutorial. I've been able to create my project by using DOS interface and typing:
```
scrapy startproject dmoz
```
The tutorial later refers to the Crawl command:
```
scrapy crawl dmoz.org
```
But each time I try to run that I get a message that this is... | You have to execute it in your 'startproject' folder. You will have another commands if it finds your scrapy.cfg file. You can see the diference here:
```
$ scrapy startproject bar
$ cd bar/
$ ls
bar scrapy.cfg
$ scrapy
Scrapy 0.12.0.2536 - project: bar
Usage:
scrapy <command> [options] [args]
Available commands:... |
python string u"%(word)s" | 4,988,419 | 3 | 2011-02-14T02:44:51Z | 4,988,431 | 7 | 2011-02-14T02:48:49Z | [
"python",
"string",
"syntax"
] | I'm a new user of Python, and I don't know some parts when I read the code. So I asked here.
```
cmd = u"sudo umount %(mountpoint)s >>%(log)s 2>&1"
```
I know that `%(word)` is used to replace the word latter use such as `cmd % {'word':'new word'}`, but I don't down why there is a trailing `s`. and I don't know the '... | The beginning `u` means "Unicode" (i.e. it's a Unicode string). The `s` after each formatting code means to interpret the value as a string, as opposed to `d` for decimal, etc.
See the documentation at <http://docs.python.org/library/stdtypes.html#string-formatting-operations> for all the details. |
can't instantiate child classes of unittest.Testcase in python | 4,988,468 | 4 | 2011-02-14T02:57:22Z | 4,989,251 | 8 | 2011-02-14T05:54:15Z | [
"python",
"unit-testing"
] | i'm iterating over a text file.
each line in the file text file is the name of a test.
i am trying to instantiate the test class but i keep getting this error:
```
ValueError: no such test method in <class 'login_to_blog'>: runTest
```
the code where i'm doing that is here:
```
test_name = line.replace("\n", "... | Looking at the [PyUnit Suite Documentation](http://pyunit.sourceforge.net/pyunit.html#SUITES), it says:
> When creating an instance we must specify the test method it is to run. We do this by passing the method name in the constructor:
```
defaultSizeTestCase = WidgetTestCase("testDefaultSize")
resizeTestCase... |
Python: find regexp in a file | 4,989,198 | 13 | 2011-02-14T05:44:32Z | 4,989,323 | 29 | 2011-02-14T06:08:59Z | [
"python",
"regex"
] | Have:
```
f = open(...)
r = re.compile(...)
```
Need:
Find the position (start and end) of a first matching regexp in a big file?
(starting from `current_pos=...`)
How can I do this?
---
I want to have this function:
```
def find_first_regex_in_file(f, regexp, start_pos=0):
f.seek(start_pos)
....... | One way to search through big files is to use the [`mmap`](http://docs.python.org/library/mmap.html) library to map the file into a big memory chunk. Then you can search through it without having to explicitly read it.
For example, something like:
```
size = os.stat(fn).st_size
f = open(fn)
data = mmap.mmap(f.fileno(... |
When is it better to use zip instead of izip? | 4,989,763 | 56 | 2011-02-14T07:30:47Z | 4,989,783 | 26 | 2011-02-14T07:34:12Z | [
"python",
"python-2.7",
"itertools"
] | When is it better to use [`zip`](https://docs.python.org/2/library/functions.html#zip) instead of [`itertools.izip`](https://docs.python.org/2/library/itertools.html#itertools.izip)? | When you know you'll want the full list of items constructed (for instance, for passing to a function that would modify that list in-place). Or when you want to force the arguments you're passing to `zip()` to be completely evaluated at that specific point. |
When is it better to use zip instead of izip? | 4,989,763 | 56 | 2011-02-14T07:30:47Z | 4,989,890 | 68 | 2011-02-14T07:52:45Z | [
"python",
"python-2.7",
"itertools"
] | When is it better to use [`zip`](https://docs.python.org/2/library/functions.html#zip) instead of [`itertools.izip`](https://docs.python.org/2/library/itertools.html#itertools.izip)? | `zip` computes all the list at once, `izip` computes the elements only when requested.
One important difference is that 'zip' returns an actual list, 'izip' returns an 'izip object', which is not a list and does not support list-specific features (such as indexing):
```
>>> l1 = [1, 2, 3, 4, 5, 6]
>>> l2 = [2, 3, 4, ... |
Python argument interpreter | 4,990,183 | 2 | 2011-02-14T08:41:56Z | 4,990,188 | 9 | 2011-02-14T08:43:15Z | [
"python",
"input",
"arguments"
] | Is there a correct way to read the arguments to a python application?
Example:
```
python game.py -server 127.0.0.1 -nick TheKiller1337
```
Is there a correct way of interpreting these argument?
As it is now I have a while-loop with some ifs. But it is getting rather large. Should I do a general class for argument r... | Use [argparse](http://docs.python.org/library/argparse.html), [optparse](http://docs.python.org/library/optparse.html) or [getopt](http://docs.python.org/library/getopt.html).
All three are in the standard library.
I recommend argparse. It is the newest of the three, and is IMO the easiest to use. It was introduced i... |
Python: about catching ANY exception | 4,990,718 | 239 | 2011-02-14T09:46:58Z | 4,990,739 | 184 | 2011-02-14T09:49:45Z | [
"python"
] | How can I write a `try`/`except` block that catches all exceptions? | You can but you shouldn't:
```
try:
do_something()
except:
print "Caught it!"
```
However, this will also catch exceptions like `KeyboardInterrupt` and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example [from the docs](http://docs.python.org/tutorial/... |
Python: about catching ANY exception | 4,990,718 | 239 | 2011-02-14T09:46:58Z | 4,992,124 | 291 | 2011-02-14T12:26:25Z | [
"python"
] | How can I write a `try`/`except` block that catches all exceptions? | Apart from a bare `except:` clause (which as others have said you shouldn't use), you can simply catch [`Exception`](https://docs.python.org/2/library/exceptions.html#exceptions.Exception):
```
import traceback
import logging
try:
whatever()
except Exception as e:
logging.error(traceback.format_exc())
# L... |
Python: about catching ANY exception | 4,990,718 | 239 | 2011-02-14T09:46:58Z | 4,994,509 | 15 | 2011-02-14T16:21:52Z | [
"python"
] | How can I write a `try`/`except` block that catches all exceptions? | Very simple example, similar to the one found here:
<http://docs.python.org/tutorial/errors.html#defining-clean-up-actions>
If you're attempting to catch ALL exceptions, then put all your code within the "try:" statement, in place of 'print "Performing an action which may throw an exception."'.
```
try:
print "P... |
Python: about catching ANY exception | 4,990,718 | 239 | 2011-02-14T09:46:58Z | 17,642,893 | 51 | 2013-07-14T19:27:56Z | [
"python"
] | How can I write a `try`/`except` block that catches all exceptions? | You can do this to handle general exceptions
```
try:
a = 2/0
except Exception as e:
print e.__doc__
print e.message
``` |
Python: about catching ANY exception | 4,990,718 | 239 | 2011-02-14T09:46:58Z | 31,609,619 | 12 | 2015-07-24T11:39:16Z | [
"python"
] | How can I write a `try`/`except` block that catches all exceptions? | To catch all possible exceptions, catch `BaseException`. It's on top of the Exception hierarchy:
Python 3:
<https://docs.python.org/3.5/library/exceptions.html#exception-hierarchy>
Python 2.7:
<https://docs.python.org/2.7/library/exceptions.html#exception-hierarchy>
```
try:
something()
except BaseException as e... |
Strange error about invalid syntax | 4,991,051 | 2 | 2011-02-14T10:26:46Z | 7,770,007 | 10 | 2011-10-14T15:35:17Z | [
"python"
] | I am getting invalid syntax error in my python script for this statement
```
44 f = open(filename, 'r')
45 return
return
^
SyntaxError: invalid syntax
```
I am not sure what exactly is wrong here? I am a python newbie and so will greatly appreciate if someone can please help.
I am using version 2.3.4 | I had the same problem. Here was my code:
```
def gccontent(genomefile):
nbases = 0
totalbases = 0
GC = 0
for line in genomefile.xreadlines():
nbases += count(seq, 'N')
totalbases += len(line)
GC += count(line, 'G' or 'C')
gcpercent = (float(GC)/(totalbases - nbases)*100
... |
Changing the color of the offset in scientific notation in matplotlib | 4,991,178 | 6 | 2011-02-14T10:41:01Z | 4,994,683 | 10 | 2011-02-14T16:38:52Z | [
"python",
"colors",
"matplotlib"
] | I am plotting some curves using twin-axis and also scientific notation. I have set some color to the label but the setting don't seem to affect the power indicator of the scientific notation of its axis. Is there any trick?
[Example](http://imageupload.org/?di=1212976802234)
Here is my code:
```
fig = pylab.figure()... | It's probably just an oversight that `tick_params` doesn't already do this, but you can simply set it manually.
For example, just add these two lines to your example code:
```
ax1.yaxis.get_offset_text().set_color(plot_ax1.get_color())
ax2.yaxis.get_offset_text().set_color(plot_ax2.get_color())
```
As a more complet... |
Why does refs increase 2 for every new object in Python? | 4,991,744 | 5 | 2011-02-14T11:44:35Z | 4,992,078 | 8 | 2011-02-14T12:20:56Z | [
"python",
"cpython",
"python-internals"
] | It is a little weird to me that the refs number in the interactive environment increases 2 after a new object is defined. I created only one object, isn't it?
```
>>> v
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'v' is not defined
[41830 refs]
>>> v = "v"
[41832 refs]
``` | Your assignment worked by creating an entry in the `globals()` dictionary that has `v` as a key and `"v"` as a value. That's two references (one for the key and one for the value) although in this case they probably both refer to the same string `"v"`. |
python, numpy boolean array: negation in where statement | 4,992,040 | 13 | 2011-02-14T12:16:27Z | 4,992,085 | 22 | 2011-02-14T12:21:29Z | [
"python",
"numpy"
] | with:
```
import numpy as np
array = get_array()
```
I need to do the following thing:
```
for i in range(len(array)):
if random.uniform(0, 1) < prob:
array[i] = not array[i]
```
with array being a numpy.array.
I wish I could do something similar to:
```
array = np.where(np.random.rand(len(array)) < p... | I suggest using
```
array ^= numpy.random.rand(len(array)) < prob
```
This is probably the most efficient way of getting the desired result. It will modify the array in place, using "xor" to invert the entries which the random condition evaluates to `True` for.
> Why can I take the value of array but not its negatio... |
running several system commands in parallel | 4,992,400 | 18 | 2011-02-14T12:59:11Z | 4,992,640 | 20 | 2011-02-14T13:23:43Z | [
"python"
] | I write a simple script that executes a system command on a sequence of files.
To speed things up, I'd like to run them in parallel, but not all at once - i need to control maximum number of simultaneously running commands.
What whould be the easiest way to approach this ? | If you are calling subprocesses anyway, I don't see the need to use a thread pool. A basic implementation using the `subprocess` module would be
```
import subprocess
import os
import time
files = <list of file names>
command = "/bin/touch"
processes = set()
max_processes = 5
for name in files:
processes.add(sub... |
running several system commands in parallel | 4,992,400 | 18 | 2011-02-14T12:59:11Z | 12,085,254 | 9 | 2012-08-23T05:29:37Z | [
"python"
] | I write a simple script that executes a system command on a sequence of files.
To speed things up, I'd like to run them in parallel, but not all at once - i need to control maximum number of simultaneously running commands.
What whould be the easiest way to approach this ? | The answer from Sven Marnach is almost right, but there is a problem. If one of the last max\_processes processes ends, the main program will try to start another process, and the for looping will end. This will close the main process, which can in turn close the child processes. For me, this behavior happened with the... |
How to read the date/time field from the csv file and plot a graph accordingly in python | 4,992,697 | 4 | 2011-02-14T13:30:11Z | 4,993,072 | 8 | 2011-02-14T14:05:51Z | [
"python",
"csv",
"matplotlib"
] | Im importing records from a CSV file using python csv module .
The date/Time field expects the date to be in a specific format, but
different spreadsheet programs default to different types of formats
and I dont want the user to have to change their down format.I want to
find a way to either detect the format the stri... | [dateutil](http://niemeyer.net/python-dateutil) can parse date strings in a variety of formats, without you having to specify in advance what format the date string is in:
```
In [8]: import dateutil.parser as parser
In [9]: parser.parse('Jan 1')
Out[9]: datetime.datetime(2011, 1, 1, 0, 0)
In [10]: parser.parse('1 J... |
how to traverse through dict? | 4,992,739 | 13 | 2011-02-14T13:33:22Z | 4,992,759 | 9 | 2011-02-14T13:35:03Z | [
"python"
] | ```
records = {'foo':foo, 'bar':bar, 'baz':baz}
```
I want to change the values to `0` if it is `None`. How can I do this?
eg:
```
records = {'foo':None, 'bar':None, 'baz':1}
```
I want to change `foo` and `bar` to `0`.
Final dict:
```
records = {'foo':0, 'bar':0, 'baz':1}
``` | Try
```
for key, value in records.iteritems():
if value is None:
records[key] = 0
``` |
how to traverse through dict? | 4,992,739 | 13 | 2011-02-14T13:33:22Z | 4,992,811 | 18 | 2011-02-14T13:40:22Z | [
"python"
] | ```
records = {'foo':foo, 'bar':bar, 'baz':baz}
```
I want to change the values to `0` if it is `None`. How can I do this?
eg:
```
records = {'foo':None, 'bar':None, 'baz':1}
```
I want to change `foo` and `bar` to `0`.
Final dict:
```
records = {'foo':0, 'bar':0, 'baz':1}
``` | ```
for k in records:
if records[k] is None:
records[k] = 0
``` |
how to traverse through dict? | 4,992,739 | 13 | 2011-02-14T13:33:22Z | 4,992,948 | 12 | 2011-02-14T13:53:12Z | [
"python"
] | ```
records = {'foo':foo, 'bar':bar, 'baz':baz}
```
I want to change the values to `0` if it is `None`. How can I do this?
eg:
```
records = {'foo':None, 'bar':None, 'baz':1}
```
I want to change `foo` and `bar` to `0`.
Final dict:
```
records = {'foo':0, 'bar':0, 'baz':1}
``` | Another way
```
records.update((k, 0) for k,v in records.iteritems() if v is None)
```
Example
```
>>> records
{'bar': None, 'baz': 1, 'foo': None}
>>> records.update((k, 0) for k,v in records.iteritems() if v is None)
>>> records
{'bar': 0, 'baz': 1, 'foo': 0}
``` |
PyQt --> connect() --> TypeError: arguments did not match any overloaded call | 4,992,968 | 4 | 2011-02-14T13:54:35Z | 4,993,777 | 10 | 2011-02-14T15:13:05Z | [
"python",
"pyqt",
"connect"
] | I have problems with connect() from PyQt4. For example here is .UI converted via pyuic4.
```
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName(_fromUtf8("... | The error is on the double-commented line:
```
## self.connect(self.btnClearText, QtCore.SIGNAL('clicked()'), self.label.setText('ABC'))
```
It looks like you want the text of the label set to `ABC` whenever the button is clicked. However, the above line of code will not achieve this. The problem is that the t... |
how to run python script without typing 'python ...' | 4,993,621 | 25 | 2011-02-14T14:57:42Z | 4,993,648 | 68 | 2011-02-14T15:00:22Z | [
"python",
"bash",
"shell"
] | I want to run a python script without explicitly having to call "python" every time in my shell. I've tried to add the shebang #!/path/to/python but this does not seem to work. Does anyone know a work around this? Many thanks. | You've got to add the shebang:
```
#!/usr/bin/env python
```
Then make the script executable:
```
chmod +x foo
```
Then you can run it like any other executable:
```
./foo
```
And a note from Homer6: if you're editing the file from windows and invoking it on linux, you may run into the cryptic "No such file or di... |
PyObjC tutorial without Xcode | 4,994,058 | 8 | 2011-02-14T15:39:10Z | 5,072,734 | 9 | 2011-02-22T00:13:15Z | [
"python",
"osx",
"wxpython",
"pyobjc"
] | I'm writing a small cross-platform wxPython app, however on every platform I need to use some platform-specific API. On Mac OS it can be done using PyObjC.
I'm searching for tutorial on how to use PyObjC. However, all I found so far were tutorials with Xcode. I want my app to be able to run on mac/win/lin, without cha... | You can import the Foundation and AppKit modules, then subclass NSApplication. But maybe this isn't what you're looking for, if your pyobjc code isn't the entry point for your code. Could give more specifics about what you're trying to do with pyobjc?
Here's a quick example using pyobjc to make a simple status bar app... |
One line ftp server in python | 4,994,638 | 57 | 2011-02-14T16:34:27Z | 4,994,745 | 15 | 2011-02-14T16:45:31Z | [
"python",
"ftp",
"ftp-server"
] | Is it possible to have a one line command in python to do a simple ftp server? I'd like to be able to do this as quick and temporary way to transfer files to a linux box without having to install a ftp server. Preferably a way using built in python libraries so there's nothing extra to install. | Why don't you instead use a one-line **HTTP** server?
```
python -m SimpleHTTPServer 8000
```
will serve the contents of the current working directory over HTTP on port 8000.
If you use Python 3, you should instead write
```
python3 -m http.server 8000
```
See the [SimpleHTTPServer](http://docs.python.org/library/... |
One line ftp server in python | 4,994,638 | 57 | 2011-02-14T16:34:27Z | 4,994,862 | 80 | 2011-02-14T16:57:14Z | [
"python",
"ftp",
"ftp-server"
] | Is it possible to have a one line command in python to do a simple ftp server? I'd like to be able to do this as quick and temporary way to transfer files to a linux box without having to install a ftp server. Preferably a way using built in python libraries so there's nothing extra to install. | Obligatory [Twisted](https://twistedmatrix.com/trac/) example:
```
twistd -n ftp
```
And probably useful:
```
twistd ftp --help
Usage: twistd [options] ftp [options].
WARNING: This FTP server is probably INSECURE do not use it.
Options:
-p, --port= set the port number [default: 2121]
-r, --root= ... |
One line ftp server in python | 4,994,638 | 57 | 2011-02-14T16:34:27Z | 7,303,734 | 43 | 2011-09-05T03:46:22Z | [
"python",
"ftp",
"ftp-server"
] | Is it possible to have a one line command in python to do a simple ftp server? I'd like to be able to do this as quick and temporary way to transfer files to a linux box without having to install a ftp server. Preferably a way using built in python libraries so there's nothing extra to install. | Check out [pyftpdlib](https://github.com/giampaolo/pyftpdlib) from Giampaolo Rodola. It is one of the very best ftp servers out there for python. It's used in google's chromium (their browser) and bazaar (a version control system). It is the most complete implementation on Python for [RFC-959](http://www.faqs.org/rfcs/... |
One line ftp server in python | 4,994,638 | 57 | 2011-02-14T16:34:27Z | 27,331,584 | 13 | 2014-12-06T12:15:46Z | [
"python",
"ftp",
"ftp-server"
] | Is it possible to have a one line command in python to do a simple ftp server? I'd like to be able to do this as quick and temporary way to transfer files to a linux box without having to install a ftp server. Preferably a way using built in python libraries so there's nothing extra to install. | The answers above were all assuming your Python distribution would have some third-party libraries in order to achieve the "one liner python ftpd" goal, but that is not the case of what @zio was asking, also, SimpleHTTPServer involves web broswer for downloading files, it's not quick enough.
Python can't do ftpd by it... |
Encoding for Multilingual .py Files | 4,994,899 | 11 | 2011-02-14T17:00:10Z | 4,995,172 | 13 | 2011-02-14T17:25:47Z | [
"python",
"unicode",
"encoding",
"nlp"
] | I am writing a .py file that contains strings from multiple charactersets, including English, Spanish, and Russian. For example, I have something like:
```
string_en = "The quick brown fox jumped over the lazy dog."
string_es = "El veloz murciélago hindú comÃa feliz cardillo y kiwi."
string_ru = "Ð ÑаÑаÑ
Ñ... | There are two aspects to proper encoding of strings in your use case:
1. For Python to understand that you are using UTF-8 encoding, you must include in the first or second line of your code, a line that looks like `# coding=utf-8`. See [PEP 0263](http://www.python.org/dev/peps/pep-0263/) for details.
2. Your editor a... |
Only extracting text from this element, not its children | 4,995,116 | 16 | 2011-02-14T17:21:19Z | 4,995,480 | 17 | 2011-02-14T17:51:32Z | [
"python",
"parsing",
"text",
"beautifulsoup"
] | I want to extract only the text from the top-most element of my soup; however soup.text gives the text of all the child elements as well:
I have
```
import BeautifulSoup
soup=BeautifulSoup.BeautifulSoup('<html>yes<b>no</b></html>')
print soup.text
```
The output to this is `yesno`. I want simply 'yes'.
What's the b... | what about `.find(text=True)`?
```
>>> BeautifulSoup.BeautifulSOAP('<html>yes<b>no</b></html>').find(text=True)
u'yes'
>>> BeautifulSoup.BeautifulSOAP('<html><b>no</b>yes</html>').find(text=True)
u'no'
```
**EDIT:**
I think that I've understood what you want now. Try this:
```
>>> BeautifulSoup.BeautifulSOAP('<html... |
In Python, how do I know when a process is finished? | 4,995,419 | 18 | 2011-02-14T17:46:17Z | 4,999,697 | 7 | 2011-02-15T03:45:16Z | [
"python",
"multithreading",
"user-interface",
"parallel-processing",
"multiprocessing"
] | From within a Python GUI (PyGTK) I start a process (using multiprocessing). The process takes a long time (~20 minutes) to finish. When the process is finished I would like to clean it up (extract the results and join the process). How do I know when the process has finished?
My colleague suggested a busy loop within ... | I think as a part of making python multi-platform, simple things like SIGCHLD must be done yourself. Agreed, this is a little more work when all you want to do is know when the child is done, but it really isn't THAT painful. Consider the following that uses a child process to do the work, two multiprocessing.Event ins... |
How to create a spinning command line cursor using python? | 4,995,733 | 24 | 2011-02-14T18:17:09Z | 4,995,775 | 8 | 2011-02-14T18:22:02Z | [
"python",
"command-line-interface",
"progress"
] | Is there a way to print a spinning cursor in a terminal using Python? | A solution:
```
import sys
import time
print "processing...\\",
syms = ['\\', '|', '/', '-']
bs = '\b'
for _ in range(10):
for sym in syms:
sys.stdout.write("\b%s" % sym)
sys.stdout.flush()
time.sleep(.5)
```
The key is to use the backspace character '\b' and flush stdout. |
How to create a spinning command line cursor using python? | 4,995,733 | 24 | 2011-02-14T18:17:09Z | 4,995,896 | 31 | 2011-02-14T18:33:30Z | [
"python",
"command-line-interface",
"progress"
] | Is there a way to print a spinning cursor in a terminal using Python? | Something like this, assuming your terminal handles \b
```
import sys
import time
def spinning_cursor():
while True:
for cursor in '|/-\\':
yield cursor
spinner = spinning_cursor()
for _ in range(50):
sys.stdout.write(spinner.next())
sys.stdout.flush()
time.sleep(0.1)
sys.stdo... |
Python split string on regex | 4,995,892 | 18 | 2011-02-14T18:33:15Z | 4,996,043 | 21 | 2011-02-14T18:48:42Z | [
"python",
"regex"
] | I'm trying to split a string using a regular expression.
```
Friday 1Friday 11 JAN 11
```
The output I want to achieve is
```
['Friday 1', 'Friday 11', ' JAN 11']
```
My snippet so far is not producing the desired results:
```
>>> import re
>>> p = re.compile(r'(Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Satu... | The problem is the capturing parentheses. This syntax: `(?:...)` makes them non-capturing. Try:
```
p = re.compile(r'((?:Friday|Saturday)\s*\d{1,2})')
``` |
How do I change the file creation date of a Windows file from Python? | 4,996,405 | 14 | 2011-02-14T19:30:53Z | 4,996,407 | 22 | 2011-02-14T19:31:26Z | [
"python",
"windows",
"file",
"date",
"time"
] | How do I change the file creation date of a Windows file from Python? | [Yak shaving](http://www.catb.org/jargon/html/Y/yak-shaving.html) for the win.
```
import pywintypes, win32file, win32con
def changeFileCreationTime(fname, newtime):
wintime = pywintypes.Time(newtime)
winfile = win32file.CreateFile(
fname, win32con.GENERIC_WRITE,
win32con.FILE_SHARE_READ | win3... |
Idiomatic Python for generating a new object from within a class | 4,996,565 | 7 | 2011-02-14T19:50:58Z | 4,996,681 | 14 | 2011-02-14T20:02:44Z | [
"python"
] | I have a method on one of my objects that returns a new instance of that same class. I'm trying to figure out the most idiomatic way to write this method such that it generates a new object of the same type without duplicating code.
Since this method uses data from the instance, my first pass is:
```
class Foo(object... | If you want to make it more flexible for subclassing, you can simply use the [`self.__class__`](http://docs.python.org/library/stdtypes.html#instance.__class__) special attribute:
```
class Foo(object):
def __init__(self, data):
self.data = data
def get_new(self):
data = # Do interesting thing... |
Access Python Development Server from External IP | 4,997,293 | 25 | 2011-02-14T21:08:53Z | 4,997,322 | 51 | 2011-02-14T21:11:25Z | [
"python",
"django",
"networking",
"xampp"
] | I am learning Django and have deployed apps on my iMac locally. I want to show the apps from external IPs over the internet. I did add an exception to the firewall for port 8000, and ran the python dev server over 8000. Able to access at localhost, but not over the net. However, when I tried XAMPP (Apache) over the sam... | ```
python manage.py runserver 0.0.0.0:8000
```
This will make it listen to any address. Quite useful when you want to develop over ssh from a machine that you cannot install stuff on. |
A way to pass milions of items in python to C program many times in rapid succesion | 4,997,831 | 5 | 2011-02-14T22:06:32Z | 4,998,211 | 7 | 2011-02-14T22:50:19Z | [
"python",
"c",
"shared-libraries",
"ctypes",
"extend"
] | I've wrote a python script that need to pass millions of items to a C program and receive its output many times in a short period (pass from 1 up to 10 millions of vertices data (integer index and 2 float coords) rapidly 500 times, and each time the python script call the C program, i need to store the returned values ... | Using `ctypes` or Cython to wrap your C functions is definitely the way to go. That way, you won't even need to copy the data between the C and Python code -- both the C and the Python part run within the same process and access the same data. Let's stick with `ctypes`, since this is what you suggested. Additionally, u... |
Emitting namespace specifications with ElementTree in Python | 4,997,848 | 18 | 2011-02-14T22:08:23Z | 4,998,124 | 7 | 2011-02-14T22:39:39Z | [
"python",
"xml",
"elementtree"
] | I am trying to emit an XML file with element-tree that contains an XML declaration and namespaces. Here is my sample code:
```
from xml.etree import ElementTree as ET
ET.register_namespace('com',"http://www.company.com") #some name
# build a tree structure
root = ET.Element("STUFF")
body = ET.SubElement(root, "MORE_S... | I've never been able to get the `<?xml` tag out of the element tree libraries programatically so I'd suggest you try something like this.
```
from xml.etree import ElementTree as ET
root = ET.Element("STUFF")
root.set('com','http://www.company.com')
body = ET.SubElement(root, "MORE_STUFF")
body.text = "STUFF EVERYWHER... |
Emitting namespace specifications with ElementTree in Python | 4,997,848 | 18 | 2011-02-14T22:08:23Z | 4,999,510 | 18 | 2011-02-15T03:00:26Z | [
"python",
"xml",
"elementtree"
] | I am trying to emit an XML file with element-tree that contains an XML declaration and namespaces. Here is my sample code:
```
from xml.etree import ElementTree as ET
ET.register_namespace('com',"http://www.company.com") #some name
# build a tree structure
root = ET.Element("STUFF")
body = ET.SubElement(root, "MORE_S... | Although the [docs](http://effbot.org/zone/elementtree-13-intro.htm) say otherwise, I only was able to get an `<?xml>` declaration by specifying both the xml\_declaration and the encoding.
You have to declare nodes in the namespace you've registered to get the namespace on the nodes in the file. Here's a fixed version... |
Python Dijkstra Algorithm | 4,997,851 | 3 | 2011-02-14T22:08:44Z | 16,117,378 | 7 | 2013-04-20T06:20:57Z | [
"python",
"dijkstra"
] | I am trying to write Dijkstra's Algorithm, however I am struggling on how to 'say' certain things in code.
To visualize, here are the columns I want represented using arrays:
```
max_nodes
A B C Length Predecessor Visited/Unvisited
A 0 1 2 -1 ... | I also used a dictionary to store the network.
# create a network dictionary (user provided)
```
net = {'0':{'1':100, '2':300},
'1':{'3':500, '4':500, '5':100},
'2':{'4':100, '5':100},
'3':{'5':20},
'4':{'5':20},
'5':{}
}
```
# shortest path algorithm (user needs to specify ... |
Shear a numpy array | 4,998,587 | 7 | 2011-02-14T23:36:57Z | 4,998,741 | 7 | 2011-02-15T00:02:36Z | [
"python",
"optimization",
"numpy",
"premature-optimization"
] | I'd like to 'shear' a numpy array. I'm not sure I'm using the term 'shear' correctly; by shear, I mean something like:
Shift the first column by 0 places
Shift the second column by 1 place
Shift the third colum by 2 places
etc...
So this array:
```
array([[11, 12, 13],
[17, 18, 19],
[35, 36, 37]]... | numpy [roll](http://docs.scipy.org/doc/numpy/reference/generated/numpy.roll.html) does this. For example, if you original array is x then
```
for i in range(x.shape[1]):
x[:,i] = np.roll(x[:,i], i)
```
produces
```
[[11 36 19]
[17 12 37]
[35 18 13]]
``` |
assert error when installing virtualenv with different python | 4,998,969 | 12 | 2011-02-15T00:55:38Z | 5,001,555 | 34 | 2011-02-15T09:00:57Z | [
"python",
"virtualenv"
] | My server has Python2.5 I wanna be jump to newest Python (2.7.x in my case). I compiled python from source, I downloaded newest virtualenv (1.5.1).
Now basically what im trying to do:
```
./packages/virtualenv/virtualenv.py --python=packages/Python-2.7/python env/
```
Typing:
```
./packages/virtualenv/virtualenv.py... | After reading and messing with [this](http://stackoverflow.com/questions/2278028/how-do-i-work-around-this-problem-creating-a-virtualenv-environment-with-a-custom).
I found that this error might be related with lack of `--prefix` while runing `./configure` for python. So I've run `./configure --prefix=/Path/To/Where/I... |
assert error when installing virtualenv with different python | 4,998,969 | 12 | 2011-02-15T00:55:38Z | 28,327,825 | 10 | 2015-02-04T17:39:39Z | [
"python",
"virtualenv"
] | My server has Python2.5 I wanna be jump to newest Python (2.7.x in my case). I compiled python from source, I downloaded newest virtualenv (1.5.1).
Now basically what im trying to do:
```
./packages/virtualenv/virtualenv.py --python=packages/Python-2.7/python env/
```
Typing:
```
./packages/virtualenv/virtualenv.py... | I don't have enough rep to add this as a comment and this question is 3 years old, but this might be useful to someone. In Windows, you have to path out to **python.exe**, but it seems that in Linux/OS X you just path to the folder. Example:
**Windows:**
```
virtualenv -p <PATH TO PYTHON.EXE> venv
```
Creates a virt... |
How to use variables already defined in ConfigParser | 4,999,190 | 8 | 2011-02-15T01:45:19Z | 4,999,244 | 17 | 2011-02-15T01:57:50Z | [
"python",
"configparser"
] | I'm using ConfigParser in Python
config.ini is
```
[general]
name: my_name
base_dir: /home/myhome/exp
exe_dir: ${base_dir}/bin
```
Here I want `exp_dir` becomes `/home/myhome/exp/bin` not `${base_dir}/bin`.
It means `${base_dir}` would be substituted to `/home/myhome/exp automatically`. | You can use [ConfigParser](http://docs.python.org/library/configparser.html) interpolation
> On top of the core functionality,
> SafeConfigParser supports
> interpolation. This means values can
> contain format strings which refer to
> other values in the same section, or
> values in a special DEFAULT section.
> Addit... |
Python Random Access File | 4,999,340 | 7 | 2011-02-15T02:18:30Z | 4,999,741 | 8 | 2011-02-15T03:58:01Z | [
"python",
"file",
"file-io",
"io",
"random-access"
] | Is there a Python file type for accessing random lines without traversing the whole file? I need to search within a large file, reading the whole thing into memory wouldn't be possible.
Any types or methods would be appreciated. | This seems like just the sort of thing [`mmap`](http://docs.python.org/library/mmap.html) was designed for. A `mmap` object creates a string-like interface to a file:
```
>>> f = open("bonnie.txt", "wb")
>>> f.write("My Bonnie lies over the ocean.")
>>> f.close()
>>> f.open("bonnie.txt", "r+b")
>>> mm = mmap(f.fileno(... |
cx_freeze python single file? | 4,999,567 | 20 | 2011-02-15T03:13:51Z | 5,497,896 | 9 | 2011-03-31T09:42:31Z | [
"python",
"cx-freeze"
] | I've been using cx\_freeze for a while now and there is one thing I've really wanted to do: put ALL of the files into ONE executable that I can distribute. It's not really user friendly to send around a folder filled with 30 files, all in the same directory. How can I accomplish this?
Thanks. | It is not supported in cx\_freeze. There was discussion about it on mailing list. As I recall, the author stated that others (PyInstaller, Py2Exe) use some dirty hacks to achieve that. Some anti-virus programs can consider that behavior as a virus also.
I used PyInstaller for some time, but went back to cx\_freeze bec... |
Django ORM way of going through multiple Many-to-Many relationship | 4,999,577 | 6 | 2011-02-15T03:15:48Z | 4,999,679 | 7 | 2011-02-15T03:41:22Z | [
"python",
"django"
] | Dear people trying to help others,
I am trying to figure out how to get Django to do a join for me without writing custom SQL.
Let's say I have the following models
```
class Parent(models.Model):
name = models.CharField()
children = models.ManyToManyField(Child, through="Parent_Child", related_name="parents")... | Simply write something like:
```
Toy.objects.filter(toy_owners__parents=parent)
``` |
Why is Jython much slower than CPython, despite the JVM's advances? | 5,000,360 | 27 | 2011-02-15T05:55:45Z | 5,000,542 | 16 | 2011-02-15T06:29:27Z | [
"python",
"jvm",
"jython"
] | No flame wars please. I am admittedly no fan of Java, but I consider the JVM to be a fairly decent and well-optimized virtual machine. It's JIT-enabled and very close to the common denominator of the prevalent CPU architectures. I'd assume that the CPython runtime would be farther from the metal than a corresponding JV... | Keep in mind that IronPython was started by one of the original Jython devs (Jim Huginin) in an attempt to prove that the .NET CLR was a poor platform for dynamic languages. He ended up proving himself wrong and the core of IronPython eventually became the .NET Dynamic Language Runtime (making other dynamic language im... |
I don't understand Jinja2 Call Blocks | 5,000,469 | 6 | 2011-02-15T06:16:13Z | 5,000,717 | 9 | 2011-02-15T06:58:35Z | [
"python",
"jinja2"
] | I understand the concept, but I don't understand the syntax.
I'm going to use the [example](http://jinja.pocoo.org/docs/templates/#macros) used on their site
```
{% macro render_dialog(title, class='dialog') -%}
<div class="{{ class }}">
<h2>{{ title }}</h2>
<div class="contents">
{{ caller() }}
<... | This is the output:
```
<div class="dialog">
<h2>Hello World</h2>
<div class="contents">
This is a simple dialog rendered by using a macro and
a call block.
</div>
</div>
```
So when we call render\_dialog we pass 'Hello World' as title, when it reach `caller()` it passes the contents of the `cal... |
Can I deploy Python .pyc files only to Google App Engine? | 5,002,150 | 2 | 2011-02-15T10:00:47Z | 5,002,914 | 7 | 2011-02-15T11:14:31Z | [
"python",
"django",
"google-app-engine",
"pyc"
] | I'm working on a project utilizing Django on Google App Engine. I've been asked if some of the code can be deployed as compiled only.
So I guess the question is can I upload a .pyc file only that contains the piece of code in question? I've done a basic test with a views.pyc file in an application and things don't wor... | No, you can't - you can only upload sourcecode. There's no good reason to do this, though: your code will be bytecode-compiled on the servers when needed, and nobody is able to access your code in any case. |
Best Python clustering library to use for product data analysis | 5,002,783 | 7 | 2011-02-15T10:57:54Z | 5,223,171 | 7 | 2011-03-07T17:46:00Z | [
"python",
"cluster-analysis"
] | I have a collection of alphanumeric product codes of various products. Similar products have no intrinsic similarity in their codes, ie product code "A123" might mean "Harry Potter Volume 1 DVD" and "B123" might mean "Kellogs Corn Flakes". I also do not actually have the description or identify of the product. All I ha... | What you have is a bipartite graph. As an initial stab, it sounds like you are going to treat neighbour lists as zero-one vectors between which you define some kind of similarity/correlation. This could be a normalised Hamming distance for example. Depending on which way you do that you will obtain a graph on a single ... |
how to process image with opencv in python? | 5,002,922 | 5 | 2011-02-15T11:16:05Z | 8,455,705 | 8 | 2011-12-10T09:57:29Z | [
"python",
"image-processing",
"opencv"
] | I want to use edge detection algorithms from opencv library.
Here is a piece of python code:
```
from opencv.cv import *
from opencv.highgui import *
img = cvLoadImage ('xxx.jpg')
cvNamedWindow ('img')
cvShowImage ('img', img)
cvWaitKey ()
canny = cvCreateImage (cvSize (img.width, img.height), 8, 3)
cvCanny (img, ca... | For other folks interested in the same type of problem I recommend checking out <http://simplecv.org>
Here is a bit of code I wrote that does line detection on an image acquired from a webcam. It will even display the image over http. 
```
import SimpleCV
import t... |
reportlab: setting colspan for td in rml | 5,002,944 | 4 | 2011-02-15T11:18:25Z | 8,361,654 | 8 | 2011-12-02T19:39:32Z | [
"python",
"reportlab",
"rml"
] | I can't find any option, that would allow to set `colspan` for `td` element in `rml`. Is that somehow possible? | Gordon's suggestion of the `blockSpan` element worked for me. Here's an example of how to use it:
```
<?xml version="1.0"?>
<document filename="test.pdf">
<template pageSize="(612,792)" title="Test" author="Don Kirkby">
<pageTemplate id="first">
<frame id="first" x1="10.0" y1="10.0" width="592" height="772... |
How can I speed up an animation? | 5,003,094 | 13 | 2011-02-15T11:32:45Z | 5,471,487 | 7 | 2011-03-29T11:03:57Z | [
"python",
"animation"
] | I'm trying to create a Matplotlib animation of my paw data, where you can see the pressure distribution on [the entire pressure plate over time](http://i.stack.imgur.com/ct8ub.gif) (256x64 sensors for 250 frames).
I found a [working example on Matplotlib's own site](http://matplotlib.sourceforge.net/examples/animation... | I found [Joe Kington's answer that mentioned using Glumpy](http://stackoverflow.com/questions/3886281/display-array-as-raster-image-in-python/3886301#3886301) instead. At first I couldn't get it to work on my own data, but [with some help on chat](http://chat.stackexchange.com/transcript/message/750451#750451) we manag... |
How to get path of a python module ( not sys.executable ) | 5,003,226 | 4 | 2011-02-15T11:46:35Z | 5,003,468 | 11 | 2011-02-15T12:10:59Z | [
"python",
"path",
"pyqt",
"qwebkit"
] | I need to get Path for PyQt library in python program. Program is run as a script from another application, therefore my
```
sys.executable = 'D:/program files/visum/exe/visum115.exe
```
and I need my actual python path (and path for PyQt library module)
```
Path = C:\Python25\Lib\site-packages\PyQt4\plugins
```
im... | you can try to load the module and after check for it's **\_\_*file*\_\_** attribute to get the path of the .pyc file.
for example like this:
```
import MODULE, os
path = os.path.dirname(MODULE.__file__)
```
Regards,
HTH! |
Can anyone summarize the noticeable difference between list, tuple, dictionary in Python? | 5,003,229 | 2 | 2011-02-15T11:47:06Z | 5,003,264 | 8 | 2011-02-15T11:49:54Z | [
"python",
"list",
"dictionary",
"tuples"
] | A little bit confusion about some data structure in Python.
Could any expert give some rules of thumb in order to help me get out of this mess? | They are all covered in:
[Python - Data Structures](http://docs.python.org/tutorial/datastructures.html)
* List - when you have data that has some order
* Tuple - when ordered data is to be immutable
* Dictionary - when data is related by key - value pairs |
Python CSV DictReader with UTF-8 data | 5,004,687 | 19 | 2011-02-15T14:11:40Z | 5,005,573 | 31 | 2011-02-15T15:24:45Z | [
"python",
"unicode",
"csv"
] | AFAIK, the Python (v2.6) csv module can't handle unicode data by default, correct? In the Python docs there's an [example](http://docs.python.org/library/csv.html#examples) on how to read from a UTF-8 encoded file. But this example only returns the CSV rows as a list.
I'd like to access the row columns by name as it is... | Actually, I came up with an answer myself (sorry for replying to my own question):
```
def UnicodeDictReader(utf8_data, **kwargs):
csv_reader = csv.DictReader(utf8_data, **kwargs)
for row in csv_reader:
yield {key: unicode(value, 'utf-8') for key, value in row.iteritems()}
``` |
need the average from a list of timedelta objects | 5,006,258 | 12 | 2011-02-15T16:17:50Z | 5,006,385 | 24 | 2011-02-15T16:27:44Z | [
"python",
"datetime",
"timedelta"
] | I have created a list of timedelta objects and i need to get the average of this list. when i try to do
```
return (sum(delta_list)/(len(delta_list)-1))
```
i get TypeError: unsupported operand type(s) for +: 'int' and 'datetime.timedelta'
i am new at working with pythons datetime classes. I also would like to know ... | `sum` wants a starting value, which is `0` by default, but `0` can't be added to a `timedelta` so you get the error.
You just have to give `sum` a `timedelta()` as the start value:
```
# this is the average
return sum(delta_list, timedelta()) / len(delta_list)
```
To print it out you can do this:
```
print str(some... |
What is the equivalent of a Python docstring in Ruby? | 5,006,698 | 21 | 2011-02-15T16:51:09Z | 5,006,786 | 11 | 2011-02-15T16:58:23Z | [
"python",
"ruby-on-rails",
"ruby"
] | In Python, you can access an object's docstring by using `obj.__doc__`. What is the equivalent action in Ruby? | Ruby does not have a Python `__doc__` equivalent. They often use [Rdoc Format](http://c2.com/cgi/wiki?RdocFormat) for documentation. |
How do I determine if a Python sqlite UPDATE worked? | 5,006,835 | 11 | 2011-02-15T17:01:44Z | 5,006,914 | 23 | 2011-02-15T17:08:43Z | [
"python",
"sqlite3"
] | I'm using sqlite3 in Python. I want to know if my UPDATE statement worked or not without doing another database query:
```
c.execute('update students set gpa=3.5 where stuid=123')
```
If there isn't a student with stuid 123 then obviously the update fails. | [`cursor.rowcount`](http://docs.python.org/library/sqlite3.html#sqlite3.Cursor.rowcount) will be 1 if the update was successful (affecting 1 row) or 0 if it failed. |
Rendering Plaintext as HTML maintaining whitespace â without <pre> | 5,007,574 | 7 | 2011-02-15T18:05:09Z | 5,007,620 | 12 | 2011-02-15T18:09:32Z | [
"javascript",
"python",
"html",
"algorithm",
"plaintext"
] | Given any arbitrary text file full of printable characters, how can this be converted to HTML that would be rendered exactly the same (with the following requirements)?
* Does not rely on any but the default HTML whitespace rules
+ No `<pre>` tag
+ No CSS `white-space` rules
* `<p>` tags are fine, but not required... | The solution to do that while still allowing the browser to **wrap long lines** is to replace each sequence of two spaces with a space and a non break space.
The browser will correctly render all spaces (normal and non break ones), while still wrapping long lines (due to normal spaces).
Javascript:
```
text = html_e... |
Rendering Plaintext as HTML maintaining whitespace â without <pre> | 5,007,574 | 7 | 2011-02-15T18:05:09Z | 5,047,731 | 8 | 2011-02-18T23:42:04Z | [
"javascript",
"python",
"html",
"algorithm",
"plaintext"
] | Given any arbitrary text file full of printable characters, how can this be converted to HTML that would be rendered exactly the same (with the following requirements)?
* Does not rely on any but the default HTML whitespace rules
+ No `<pre>` tag
+ No CSS `white-space` rules
* `<p>` tags are fine, but not required... | Use a [zero-width space](http://www.fileformat.info/info/unicode/char/200b/index.htm) (`​`) to preserve whitespace and allow the text to wrap. The basic idea is to pair each space or sequence of spaces with a zero-width space. Then replace each space with a non-breaking space. You'll also want to encode html and ... |
Convert a python 'type' object to a string | 5,008,828 | 62 | 2011-02-15T19:58:04Z | 5,008,854 | 93 | 2011-02-15T20:01:11Z | [
"python",
"reflection"
] | I'm wondering how to convert a python 'type' object into a string using python's reflective capabilities.
For example, I'd like to print the type of an object
```
print "My type is " + type(someObject) # (which obviously doesn't work like this)
```
**EDIT:** Btw, thanks guys, I was just looking for plain printing of... | ```
print type(someObject).__name__
```
If that doesn't suit you, use this:
```
print some_instance.__class__.__name__
```
Example:
```
class A:
pass
print type(A())
# prints <type 'instance'>
print A().__class__.__name__
# prints A
```
Also, it seems there are differences with `type()` when using new-style cl... |
How do I reverse an itertools.chain object? | 5,008,921 | 8 | 2011-02-15T20:07:20Z | 5,008,968 | 9 | 2011-02-15T20:13:02Z | [
"python",
"generator",
"itertools"
] | My function creates a chain of generators:
```
def bar(num):
import itertools
some_sequence = (x*1.5 for x in range(num))
some_other_sequence = (x*2.6 for x in range(num))
chained = itertools.chain(some_sequence, some_other_sequence)
return chained
```
My function sometimes needs to return `chaine... | ```
if num < 0:
lst = list(chained)
lst.reverse()
return lst
else:
return chained
```
`reversed()` needs an actual sequence, because it iterates it backwards by index, and that wouldn't work for a generator (which only has the notion of "next" item).
Since you will need to unroll the whole generator a... |
How do I reverse an itertools.chain object? | 5,008,921 | 8 | 2011-02-15T20:07:20Z | 5,009,050 | 7 | 2011-02-15T20:20:10Z | [
"python",
"generator",
"itertools"
] | My function creates a chain of generators:
```
def bar(num):
import itertools
some_sequence = (x*1.5 for x in range(num))
some_other_sequence = (x*2.6 for x in range(num))
chained = itertools.chain(some_sequence, some_other_sequence)
return chained
```
My function sometimes needs to return `chaine... | You cannot reverse generators by definition. The interface of a generator is the iterator, which is a container that supports only forward iteration. When you want to reverse a iterator, you have to collect all it's items first and reverse them after that.
Use lists instead or generate the sequences backwards from the... |
Plot/scatter position and marker size in the same coordinates | 5,009,316 | 9 | 2011-02-15T20:48:22Z | 5,009,578 | 11 | 2011-02-15T21:14:51Z | [
"python",
"graphics",
"plot",
"matplotlib"
] | I am trying to programmatically display various types of diagrams in pylab. pylab's scatter function displays markers at different co-ordinates in temrs of its axis, but the marker sizes are in terms of pixels. This makes sense for everyday graph plots. However, I want to give the co-ordinates and marker sizes in the s... | The `pylab.scatter` function takes a value size based on the size in points^2. This size will be independent of the axes, as is the nature of a scatter plot (it doesn't make sense if you narrow in on a region in a scatter plot that the points get bigger).
If you want to say draw circles that are a given size, you shou... |
Python's 'in' operator equivalent to C# | 5,009,882 | 12 | 2011-02-15T21:42:23Z | 5,009,899 | 21 | 2011-02-15T21:43:39Z | [
"c#",
"python",
"operators"
] | With Python, I can use 'in' operator for set operation as follows :
```
x = ['a','b','c']
if 'a' in x:
do something
```
What's the equivalent in C#? | Most collections declare a `Contains` method (e.g. through the `ICollection<T>` interface), but there's always the more general-purpose LINQ [**`Enumerable.Contains`**](http://msdn.microsoft.com/en-us/library/bb352880.aspx) method:
```
char[] x = { 'a', 'b', 'c' };
if(x.Contains('a'))
{
...
}
```
If you think... |
MySQL: Get column name or alias from query | 5,010,042 | 22 | 2011-02-15T22:01:17Z | 5,058,950 | 88 | 2011-02-20T18:13:48Z | [
"python",
"mysql",
"mysql-python"
] | I'm not asking for the SHOW COLUMNS command.
I want to create an application that works similiarly to heidisql, where you can specify an SQL query and when you execute it ... you get a result set with rows and columns representing your query result. The column names in the result set should match your selected columns... | cursor.description will give you a tuple of tuples where [0] for each is the column header.
```
num_fields = len(cursor.description)
field_names = [i[0] for i in cursor.description]
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.