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 can I modify a Python traceback object when raising an exception? | 1,603,940 | 11 | 2009-10-21T22:08:06Z | 13,898,994 | 9 | 2012-12-16T05:50:38Z | [
"python",
"traceback"
] | I'm working on a Python library used by third-party developers to write extensions for our core application.
I'd like to know if it's possible to modify the traceback when raising exceptions, so the last stack frame is the call to the library function in the developer's code, rather than the line in the library that r... | You can remove the top of the traceback easily with by raising with the tb\_next element of the traceback:
```
except:
ei = sys.exc_info()
raise ei[0], ei[1], ei[2].tb_next
```
tb\_next is a read\_only attribute, so I don't know of a way to remove stuff from the bottom. You might be able to screw with the pro... |
Python SSH / SFTP Module? | 1,603,984 | 11 | 2009-10-21T22:17:15Z | 1,604,000 | 13 | 2009-10-21T22:22:51Z | [
"python",
"ssh",
"sftp"
] | I've been looking around for a module which allows me to do SSH / SFTP functions in python without using POPEN to do it manually. Is there anything like this? I haven't found any real information on this, thanks! | You're probably looking for the excellent paramiko library:
<http://www.paramiko.org/> |
Object oriented design? | 1,604,391 | 5 | 2009-10-22T00:25:16Z | 1,604,427 | 7 | 2009-10-22T00:38:02Z | [
"python",
"oop"
] | I'm trying to learn object oriented programming, but am having a hard time overcoming my structured programming background (mainly C, but many others over time). I thought I'd write a simple check register program as an exercise. I put something together pretty quickly (python is a great language), with my data in some... | You don't have to throw out structured programming to do object-oriented programming. The code is still structured, it just belongs to the objects rather than being separate from them.
In classical programming, code is the driving force that operates on data, leading to a dichotomy (and the possibility that code can o... |
Two's Complement in Python | 1,604,464 | 28 | 2009-10-22T00:53:12Z | 1,605,553 | 13 | 2009-10-22T07:30:14Z | [
"python",
"bit-manipulation",
"twos-complement"
] | Is there a built in function in python which will convert a binary string, for example '111111111111', to the [two's complement integer](http://en.wikipedia.org/wiki/Two%27s_complement) -1? | It's not built in, but if you want unusual length numbers then you could use the [bitstring](http://python-bitstring.googlecode.com) module.
```
>>> from bitstring import Bits
>>> a = Bits(bin='111111111111')
>>> a.int
-1
```
The same object can equivalently be created in several ways, including
```
>>> b = Bits(int... |
Two's Complement in Python | 1,604,464 | 28 | 2009-10-22T00:53:12Z | 9,147,327 | 40 | 2012-02-05T06:14:32Z | [
"python",
"bit-manipulation",
"twos-complement"
] | Is there a built in function in python which will convert a binary string, for example '111111111111', to the [two's complement integer](http://en.wikipedia.org/wiki/Two%27s_complement) -1? | DANGER: gnibbler's answer (currently the highest ranked) isn't correct.
Sadly, I can't figure out how to add a comment to it.
Two's compliment subtracts off `(1<<bits)` if the highest bit is 1. Taking 8 bits for example, this gives a range of 127 to -128.
A function for two's compliment of an int...
```
def twos_c... |
Making a Windows .exe with gui2exe does not work because of missing MSVCP90.dll | 1,605,006 | 9 | 2009-10-22T04:20:01Z | 1,605,012 | 8 | 2009-10-22T04:21:42Z | [
"python",
"dll",
"wxwidgets",
"py2exe",
"gui2exe"
] | I'm trying to compile my python script into a single .exe using gui2exe (which uses py2exe to create a .exe). My program is using wxWidgets and everytime I try to compile it I get the following error message:
> error MSVCP90.dll: No such file or directory.
I have already downloaded and installed the VC++ redistributa... | Yes you should have it. You have to exclude it from py2exe.
```
options = {
'py2exe': {
'dll_excludes': [
'MSVCP90.dll'
]
}
}
setup(windows=["main.py"], options=options)
``` |
How can I grab the color of a pixel on my desktop? (Linux) | 1,605,350 | 7 | 2009-10-22T06:25:24Z | 1,605,380 | 7 | 2009-10-22T06:37:29Z | [
"python",
"linux",
"shell",
"imagemagick",
"image"
] | I want to grab the color of a pixel with known coordinates on my Linux desktop.
Until now, I've used `"import -window SomeWindow -crop 1x1+X+Y /tmp/grab.jpg"`
then extracting the pixel value using Python and [PIL](http://en.wikipedia.org/wiki/Python%5FImaging%5FLibrary).
This does the job, but since import grabs the ... | This does the trick, but requires python-gtk:
```
import gtk.gdk
import sys
def PixelAt(x, y):
w = gtk.gdk.get_default_root_window()
sz = w.get_size()
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
pixel_array = pb.... |
django syncdb and an updated model | 1,605,662 | 83 | 2009-10-22T08:04:52Z | 1,605,673 | 99 | 2009-10-22T08:09:17Z | [
"python",
"django",
"django-models"
] | I have recently updated my model, added a BooleanField to it however when I do `python manage.py syncdb`, it doesn't add the new field to the database for the model. How can I fix this ? | ## From Django 1.7 onwards
Django has built in support for migrations - take a look at [the documentation](https://docs.djangoproject.com/en/dev/topics/migrations/).
## For Django 1.6 and earlier
Django doesn't support migrations out of the box. There is a pluggable app for Django that does exactly that though, and ... |
django syncdb and an updated model | 1,605,662 | 83 | 2009-10-22T08:04:52Z | 1,605,680 | 13 | 2009-10-22T08:11:31Z | [
"python",
"django",
"django-models"
] | I have recently updated my model, added a BooleanField to it however when I do `python manage.py syncdb`, it doesn't add the new field to the database for the model. How can I fix this ? | Django currently does not do this automatically. Your options are:
1. Drop the table from the database, then recreate it in new form using syncdb.
2. Print out SQL for the database using `python manage.py sql (appname)`, find the added line for the field and add it manually using `alter table` SQL command. (This will ... |
django syncdb and an updated model | 1,605,662 | 83 | 2009-10-22T08:04:52Z | 1,605,694 | 11 | 2009-10-22T08:15:01Z | [
"python",
"django",
"django-models"
] | I have recently updated my model, added a BooleanField to it however when I do `python manage.py syncdb`, it doesn't add the new field to the database for the model. How can I fix this ? | Follow these steps:
1. Export your data to a fixture using the [dumpdata](http://docs.djangoproject.com/en/dev/ref/django-admin/?from=olddocs#dumpdata) management command
2. Drop the table
3. Run syncdb
4. Reload your data from the fixture using the [loaddata](http://docs.djangoproject.com/en/dev/ref/django-admin/?fro... |
django syncdb and an updated model | 1,605,662 | 83 | 2009-10-22T08:04:52Z | 6,127,375 | 8 | 2011-05-25T15:57:56Z | [
"python",
"django",
"django-models"
] | I have recently updated my model, added a BooleanField to it however when I do `python manage.py syncdb`, it doesn't add the new field to the database for the model. How can I fix this ? | As suggested in top answer, I tried using [South](http://south.aeracode.org/), and after an hour of frustration with [obscure migration errors](http://stackoverflow.com/questions/4840102/how-come-my-south-migrations-doesnt-work-for-django) decided to go with [Django Evolution](http://code.google.com/p/django-evolution/... |
How to modify the Python 'default' dictionary so that it always returns a default value | 1,605,750 | 3 | 2009-10-22T08:27:22Z | 1,605,802 | 9 | 2009-10-22T08:37:59Z | [
"python",
"dictionary",
"python-2.4"
] | I'm using all of them to print the names of assigned IANA values in a packet. So all of the dictionaries have the same default value "RESERVED".
I don't want to use `d.get(key,default)` but access dictionaries by `d[key]` so that if the key is not in d, it returns the default (that is same for all dictionaries).
I do... | If you can migrate to Python 2.5, there is the *defaultdict* class, as shown [here](http://docs.python.org/library/collections.html#collections.defaultdict). You can pass it an initializer that returns what you want. Otherwise, you'll have to roll your own implementation of it, I fear. |
Adding docstrings to namedtuples? | 1,606,436 | 39 | 2009-10-22T10:55:53Z | 1,606,478 | 31 | 2009-10-22T11:03:35Z | [
"python",
"docstring",
"namedtuple"
] | Is it possible to add a documentation string to a namedtuple in an easy manner?
I tried
```
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
"""
A point in 2D space
"""
# Yet another test
"""
A(nother) point in 2D space
"""
Point2 = namedtuple("Point2", ["x", "y"])
print Point.__doc__ # ... | You can achieve this by creating a simple, empty wrapper class around the returned value from `namedtuple`. Contents of a file I created (`nt.py`):
```
from collections import namedtuple
Point_ = namedtuple("Point", ["x", "y"])
class Point(Point_):
""" A point in 2d space """
pass
```
Then in the Python REP... |
Adding docstrings to namedtuples? | 1,606,436 | 39 | 2009-10-22T10:55:53Z | 15,667,772 | 34 | 2013-03-27T19:30:28Z | [
"python",
"docstring",
"namedtuple"
] | Is it possible to add a documentation string to a namedtuple in an easy manner?
I tried
```
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
"""
A point in 2D space
"""
# Yet another test
"""
A(nother) point in 2D space
"""
Point2 = namedtuple("Point2", ["x", "y"])
print Point.__doc__ # ... | Came across this old question via Google while wondering the same thing.
Just wanted to point out that you can tidy it up even more by calling namedtuple() right from the class declaration:
```
from collections import namedtuple
class Point(namedtuple('Point', 'x y')):
"""Here is the docstring."""
``` |
Adding docstrings to namedtuples? | 1,606,436 | 39 | 2009-10-22T10:55:53Z | 20,388,499 | 30 | 2013-12-04T23:43:06Z | [
"python",
"docstring",
"namedtuple"
] | Is it possible to add a documentation string to a namedtuple in an easy manner?
I tried
```
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
"""
A point in 2D space
"""
# Yet another test
"""
A(nother) point in 2D space
"""
Point2 = namedtuple("Point2", ["x", "y"])
print Point.__doc__ # ... | In Python 3, no wrapper is needed, as the `__doc__` attributes of types is writable.
```
from collections import namedtuple
Point = namedtuple('Point', 'x y')
Point.__doc__ = '''\
A 2-dimensional coordinate
x - the abscissa
y - the ordinate'''
```
This closely corresponds to a standard class definition, where the d... |
Adding docstrings to namedtuples? | 1,606,436 | 39 | 2009-10-22T10:55:53Z | 28,568,351 | 10 | 2015-02-17T18:19:22Z | [
"python",
"docstring",
"namedtuple"
] | Is it possible to add a documentation string to a namedtuple in an easy manner?
I tried
```
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
"""
A point in 2D space
"""
# Yet another test
"""
A(nother) point in 2D space
"""
Point2 = namedtuple("Point2", ["x", "y"])
print Point.__doc__ # ... | > # Is it possible to add a documentation string to a namedtuple in an easy manner?
# Python 3
In Python 3, you can easily alter the doc on your namedtuple:
```
NT = collections.namedtuple('NT', 'foo bar')
NT.__doc__ = """:param str foo: foo name
:param list bar: List of bars to bar"""
```
Which allows us to view ... |
How to use PIL to resize and apply rotation EXIF information to the file? | 1,606,587 | 20 | 2009-10-22T11:28:40Z | 1,608,846 | 14 | 2009-10-22T17:47:02Z | [
"python",
"jpeg",
"python-imaging-library",
"rotation",
"exif"
] | I am trying to use Python to resize picture.
With my camera, files are all written is landscape way.
The exif information handle a tag to ask the image viewer to rotate in a way or another.
Since most of the browser doesn't understand this information, I want to rotate the image using this EXIF information and keeping... | I finally used [pyexiv2](http://tilloy.net/dev/pyexiv2/), but it is a bit tricky to install on other platforms than GNU.
```
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2009 Rémy HUBSCHER <[email protected]> - http://www.trunat.fr/portfolio/python.html
# This program is free software; you can red... |
catching stdout in realtime from subprocess | 1,606,795 | 39 | 2009-10-22T12:14:43Z | 1,606,870 | 51 | 2009-10-22T12:29:06Z | [
"python",
"subprocess",
"stdout"
] | I have read tons of posts but still can't seem to figure it out.
I want to subprocess.Popen() rsync.exe in windows, and print the stdout in python.
My code works, but it doesn't catch the progress until a file is done transfered! I want to print the progress for each file in realtime.
Using python 3.1 now since I he... | Some rules of thumb for `subprocess`.
* **Never** use `shell=True`. It needlessy invokes an extra shell process to call your program.
* When calling processes, arguments are passed around as lists. `sys.argv` in python is a list, and so is `argv` in C. So you pass a **list** to `Popen` to call subprocesses, not a stri... |
Python: How do I make a subclass from a superclass? | 1,607,612 | 26 | 2009-10-22T14:26:22Z | 1,607,631 | 17 | 2009-10-22T14:28:46Z | [
"python",
"class"
] | In Python, how do you make a subclass from a superclass? | ```
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
# <the rest of your custom initialization code goes here>
```
The [section on inheritance](http://docs.python.org/2/tutorial/classes.html) in the python documentation explains it in more detail |
Python: How do I make a subclass from a superclass? | 1,607,612 | 26 | 2009-10-22T14:26:22Z | 1,607,708 | 29 | 2009-10-22T14:39:05Z | [
"python",
"class"
] | In Python, how do you make a subclass from a superclass? | A heroic little example:
```
class SuperHero(object): #superclass, inherits from default object
def getName(self):
raise NotImplementedError #you want to override this on the child classes
class SuperMan(SuperHero): #subclass, inherits from SuperHero
def getName(self):
return "Clark Kent"
cla... |
Python: How do I make a subclass from a superclass? | 1,607,612 | 26 | 2009-10-22T14:26:22Z | 1,608,905 | 38 | 2009-10-22T17:54:40Z | [
"python",
"class"
] | In Python, how do you make a subclass from a superclass? | The use of "super" (see [Python Built-in](http://docs.python.org/2/library/functions.html#super), super) may be a slightly better method of calling the parent for initialization:
```
# Initialize using Parent
#
class MySubClass(MySuperClass):
def __init__(self):
MySuperClass.__init__(self)
# Better initia... |
How to create a file one directory up? | 1,607,751 | 9 | 2009-10-22T14:44:02Z | 1,607,764 | 19 | 2009-10-22T14:45:46Z | [
"python",
"io"
] | How can I create a file in python one directory up, without using the full path?
I would like a way that worked both for windows and linux.
Thanks. | Use `os.pardir` (which is probably always `".."`)
```
import os
fobj = open(os.path.join(os.pardir, "filename"), "w")
``` |
Counting booleans in dictionary | 1,608,040 | 5 | 2009-10-22T15:29:33Z | 1,608,053 | 15 | 2009-10-22T15:31:02Z | [
"python",
"dictionary"
] | I have a python dictionary object that contains a boolean for every key, e.g.:
```
d = {'client1': True, 'client2': False}
```
What is the easiest and most concise way to count the number of True values in the dictionary? | For clarity:
```
num_true = sum(1 for condition in d.values() if condition)
```
For conciseness (this works because True is a subclass of int with a value 1):
```
num_true = sum(d.values())
``` |
Site wide caching with Django - problems with password protected pages on logout | 1,608,521 | 5 | 2009-10-22T16:47:13Z | 1,609,360 | 7 | 2009-10-22T19:11:59Z | [
"python",
"django",
"memcached"
] | I've recently implemented sitewide caching using [memcached](http://en.wikipedia.org/wiki/Memcached) on my Django application, I've set the [TTL](http://en.wikipedia.org/wiki/Time%5Fto%5Flive) to about 500 seconds, and implement per view caches on other parts of the web application.
The problem I have is that when a u... | I ran into similar issues. The standard Django way is to disable cache for authenticated users.
```
#settings.py
CACHE_MIDDLEWARE_ANONYMOUS_ONLY=True
```
It works fine if different users see different pages (example: their user name on them) and you can't have one version for them.
But if there are only 2 versions o... |
Whats new in Python 3.x? | 1,608,731 | 4 | 2009-10-22T17:27:54Z | 1,608,827 | 8 | 2009-10-22T17:45:07Z | [
"python"
] | <http://docs.python.org/3.0/whatsnew/3.0.html> says it lists whats *new*, but in my opinion, it only lists *differences*, so has does anybody know of any *completely new* Python features, introduced in release 3.x?
To Avoid Confusion, I will define a completely new feature as something that has never been used in any ... | Many of the completely new features introduced in 3.0 were also backported to 2.6, a deliberate choice. However, this was not practical in all cases, so some of the new features remained Python 3 - only.
How metaclasses work, is probably the biggest single new feature. The syntax is clearly better than `2.*`'s `__meta... |
Types that define `__eq__` are unhashable in Python 3.x? | 1,608,842 | 28 | 2009-10-22T17:46:31Z | 1,608,882 | 33 | 2009-10-22T17:51:11Z | [
"python",
"hash",
"python-3.x"
] | I had a strange bug when porting a feature to the Python 3.1 fork of my program. I narrowed it down to the following hypothesis:
In contrast to Python 2.x, in Python 3.x if an object has a `.__eq__` method it is automatically unhashable.
Is this true?
Here's what happens in Python 3.1:
```
>>> class O(object):
... | Yes, if you define `__eq__`, the default `__hash__` (namely, hashing the address of the object in memory) goes away. This is important because hashing needs to be consistent with equality: equal objects need to hash the same.
The solution is simple: just define `__hash__` along with defining `__eq__`. |
Types that define `__eq__` are unhashable in Python 3.x? | 1,608,842 | 28 | 2009-10-22T17:46:31Z | 1,608,907 | 11 | 2009-10-22T17:54:53Z | [
"python",
"hash",
"python-3.x"
] | I had a strange bug when porting a feature to the Python 3.1 fork of my program. I narrowed it down to the following hypothesis:
In contrast to Python 2.x, in Python 3.x if an object has a `.__eq__` method it is automatically unhashable.
Is this true?
Here's what happens in Python 3.1:
```
>>> class O(object):
... | This paragraph from <http://docs.python.org/3.1/reference/datamodel.html#object.%5F%5Fhash%5F%5F>
> If a class that overrides `__eq__()`
> needs to retain the implementation of
> `__hash__()` from a parent class, the interpreter must be told this
> explicitly by setting `__hash__ =
> <ParentClass>.__hash__`. Otherwise... |
How to make a private download area with django? | 1,609,273 | 9 | 2009-10-22T18:54:28Z | 1,609,799 | 8 | 2009-10-22T20:37:20Z | [
"python",
"django",
"authentication",
"download"
] | I would like to implement a private download area on a website powered by django. The user would have to be logged in with the appropriate rights in order to be able to get some static files.
What would you recommend for writing this feature. Any tips or tricks?
Thanks in advance
Update:
Maybe because of my bad engl... | So, searching I found [this](http://groups.google.com/group/django-users/browse%5Fthread/thread/92a97bee7ab168b5) discussion thread.
There were three things said you might be interested in.
First there is the mod\_python [method](http://docs.djangoproject.com/en/dev/howto/apache-auth/)
Then there is the mod\_wsgi [... |
I need __closure__ | 1,609,716 | 7 | 2009-10-22T20:18:19Z | 1,609,739 | 7 | 2009-10-22T20:23:27Z | [
"python",
"python-3.x"
] | I just checked out this very interesting mindmap:
<http://www.mindmeister.com/10510492/python-underscore>
And I was wondering what some of the new ones mean, like `__code__` and `__closure__`. I googled around but nothing concrete. Does anyone know? | From [What's New in Python 3.0](http://docs.python.org/dev/3.0/whatsnew/3.0.html)
The function attributes named `func_X` have been renamed to use the `__X__` form, freeing up these names in the function attribute namespace for user-defined attributes. To wit, `func_closure`, `func_code`, `func_defaults`, `func_dict`, ... |
How do I unindent using IDLE (Python gui) | 1,610,305 | 4 | 2009-10-22T22:18:38Z | 1,610,340 | 14 | 2009-10-22T22:25:08Z | [
"python",
"user-interface"
] | I want to write the following statment in IDLE (Python GUI)
```
>>> if x == 0:
... x = 0
... print('Negative changed to zero')
... elif x == 0:
```
How can I get the unindention for the elif statment ?
Some additional facts:
1. I tried backspace and shift + tab, that doesn't help.
2. Runing on Windows.
T... | ctrl+[ should do the trick. |
confused __iter__ | 1,610,371 | 15 | 2009-10-22T22:30:55Z | 1,610,437 | 19 | 2009-10-22T22:47:28Z | [
"python",
"iterator"
] | i am a reading the chapter on operator over flow and am very confused how `__iter__` works. I have gone to several websites to find different examples but still dont quite understand how it works. I am wondering if someone has a really simple approach to on how to understand this function. Main problem on `def__iter__(... | As simply as I can put it:
`__iter__` defines a method on a class which will return an iterator (an object that successively yields the next item contained by your object).
The iterator object that `__iter__()` returns can be pretty much any object, as long as it defines a `next()` method.
The `next` method will be ... |
when to use an alternative Python distribution? | 1,610,822 | 5 | 2009-10-23T00:34:22Z | 1,610,844 | 8 | 2009-10-23T00:40:53Z | [
"python",
"distribution",
"cpython",
"pypy"
] | I have been programming in Python for a few years now and have always used CPython without thinking about it. The books and documentation I have read always refer to CPython too.
When does it make sense to use an alternative distribution (PyPy, Stackless, etc)?
Thanks! | If you need native interfacing with the JVM, use [Jython](http://www.jython.org/).
When you need native interfacing with the .Net platform, or want to use Winforms, use [IronPython](http://www.codeplex.com/IronPython).
If you need the latest version, cross-OS support, make use of existing C-based modules existing onl... |
Collate output in Python logging MemoryHandler with SMTPHandler | 1,610,845 | 8 | 2009-10-23T00:40:58Z | 1,611,958 | 11 | 2009-10-23T07:55:13Z | [
"python",
"logging"
] | I have the logging module MemoryHandler set up to queue debug and error messages for the SMTPHandler target. What I want is for an email to be sent when the process errors that contains all debug statements up to that point (one per line). What I get instead is a separate email for every debug message.
This seems like... | You might want to use or adapt the `BufferingSMTPHandler` which is in [this test script](https://gist.github.com/1379446).
In general, you don't need to add a handler to a logger if it's the target of a MemoryHandler handler which has been added to a logger. If you set the level of a handler, that will affect what the... |
Python: static variable decorator | 1,611,019 | 2 | 2009-10-23T01:51:09Z | 1,611,144 | 8 | 2009-10-23T02:37:47Z | [
"python",
"variables",
"static",
"namespaces",
"decorator"
] | I'd like to create a decorator like below, but I can't seem to think of an implementation that works. I'm starting to think it's not possible, but thought I would ask you guys first.
I realize there's various other ways to create static variables in Python, but I find those ways ugly. I'd really like to use the below ... | By the time your decorator gets the function object `f`, it's already been compiled -- specifically, it's been compiled with the knowledge that `x` is local (because it's assigned with the `+=` assignment), the normal optimization (in `2.*` you can defeat the optimization, at a staggering price in performance, by start... |
Can I get the exception from the finally block in python? | 1,611,561 | 23 | 2009-10-23T05:37:44Z | 1,611,572 | 54 | 2009-10-23T05:43:41Z | [
"python",
"error-handling"
] | I have a `try`/`finally` clause in my script. Is it possible to get the exact error message from within the `finally` clause? | No, at `finally` time `sys.exc_info` is all-None, whether there has been an exception
or not. Use:
```
try:
whatever
except:
here sys.exc_info is valid
to re-raise the exception, use a bare `raise`
else:
here you know there was no exception
finally:
and here you can do exception-independent finalization
``` |
Can I get the exception from the finally block in python? | 1,611,561 | 23 | 2009-10-23T05:37:44Z | 1,611,606 | 7 | 2009-10-23T05:56:35Z | [
"python",
"error-handling"
] | I have a `try`/`finally` clause in my script. Is it possible to get the exact error message from within the `finally` clause? | The `finally` block will be executed regardless of whether an exception was thrown or not, so as Josh points out, you very likely don't want to be handling it there.
If you really do need the value of an exception that was raised, then you should catch the exception in an `except` block, and either handle it appropria... |
In what version of Python was set initialisation syntax added | 1,611,625 | 3 | 2009-10-23T06:07:10Z | 1,611,646 | 10 | 2009-10-23T06:15:04Z | [
"python"
] | I only just noticed this feature today!
```
s={1,2,3} #Set initialisation
t={x for x in s if x!=3} #Set comprehension
t=={1,2}
```
What version is it in? I also noticed that it has set comprehension. Was this added in the same version?
**Resources**
* [Sets in Python 2.4 Docs](http://docs.python.org/library/stdtype... | The `sets` module was added in Python 2.3, but the built-in set type was added to the language in 2.4, with essentially the same interface. (As of 2.6, the `sets` module has been deprecated.)
So you can use sets as far back as 2.3, as long as you
```
import sets
```
But you will get a `DeprecationWarning` if you try... |
Using non-hashable Python objects as keys in dictionaries | 1,611,797 | 3 | 2009-10-23T07:02:31Z | 1,611,827 | 8 | 2009-10-23T07:11:32Z | [
"python"
] | Python doesn't allow non-hashable objects to be used as keys in other dictionaries. As pointed out by Andrey Vlasovskikh, there is a nice workaround for the special case of using non-nested dictionaries as keys:
```
frozenset(a.items())#Can be put in the dictionary instead
```
Is there a method of using arbitrary obj... | Don't. I agree with Andreys comment on the previous question that is doesn't make sense to have dictionaries as keys, and especially not nested ones. Your data-model is obviously quite complex, and dictionaries are probably not the right answer. You should try some OO instead. |
Preserve case in ConfigParser? | 1,611,799 | 43 | 2009-10-23T07:03:53Z | 1,611,877 | 51 | 2009-10-23T07:33:21Z | [
"python",
"configuration-files",
"python-2.x",
"configparser"
] | I have tried to use Python's [ConfigParser](http://docs.python.org/library/configparser.html) module to save settings. For my app it's important that I preserve the case of each name in my sections. The docs mention that passing str() to [ConfigParser.optionxform()](http://docs.python.org/library/configparser.html#Conf... | The documentation is confusing. What they mean is this:
```
import ConfigParser, os
def get_config():
config = ConfigParser.ConfigParser()
config.optionxform=str
try:
config.read(os.path.expanduser('~/.myrc'))
return config
except Exception, e:
log.error(e)
c = get_config()
p... |
Preserve case in ConfigParser? | 1,611,799 | 43 | 2009-10-23T07:03:53Z | 23,836,686 | 10 | 2014-05-23T19:02:38Z | [
"python",
"configuration-files",
"python-2.x",
"configparser"
] | I have tried to use Python's [ConfigParser](http://docs.python.org/library/configparser.html) module to save settings. For my app it's important that I preserve the case of each name in my sections. The docs mention that passing str() to [ConfigParser.optionxform()](http://docs.python.org/library/configparser.html#Conf... | For me worked to set optionxform immediately after creating the object
```
config = ConfigParser.RawConfigParser()
config.optionxform = str
``` |
Including non-Python files with setup.py | 1,612,733 | 67 | 2009-10-23T11:04:57Z | 1,857,436 | 69 | 2009-12-07T02:20:16Z | [
"python",
"distutils"
] | How do I make `setup.py` include a file that isn't part of the code? (Specifically, it's a license file, but it could be any other thing.)
I want to be able to control the location of the file. In the original source folder, the file is in the root of the package. (i.e. on the same level as the topmost `__init__.py`.)... | Probably the best way to do this is to use the setuptools package\_data directive. This does mean using [setuptools](http://peak.telecommunity.com/DevCenter/setuptools) (or [distribute](http://pypi.python.org/pypi/distribute/)) instead of distutils, but this is a very seamless "upgrade".
Here's a full (but untested) e... |
Including non-Python files with setup.py | 1,612,733 | 67 | 2009-10-23T11:04:57Z | 3,042,436 | 28 | 2010-06-15T04:00:06Z | [
"python",
"distutils"
] | How do I make `setup.py` include a file that isn't part of the code? (Specifically, it's a license file, but it could be any other thing.)
I want to be able to control the location of the file. In the original source folder, the file is in the root of the package. (i.e. on the same level as the topmost `__init__.py`.)... | **To accomplish what you're describing will take two steps...**
* The file needs to be added to the source tarball
* setup.py needs to be modified to install the data file to the source path
**Step 1: To add the file to the source tarball, include it in the MANIFEST**
Create a [MANIFEST](http://docs.python.org/distu... |
Parsing XML - right scripting languages / packages for the job? | 1,613,042 | 9 | 2009-10-23T12:13:34Z | 1,613,053 | 10 | 2009-10-23T12:15:56Z | [
"python",
"xml",
"ruby",
"perl"
] | I know that any language is capable of parsing XML; I'm really just looking for advantages or drawbacks that you may have come across in your own experiences. Perl would be my standard go to here, but I'm open to suggestions.
Thanks!
UPDATE: I ended up going with XML::Simple which did a nice job, but I have one piece... | [XML::Twig](http://search.cpan.org/perldoc?XML%3A%3ATwig) is very nice, especially because itâs not as awfully verbose as some of the other options. |
Parsing XML - right scripting languages / packages for the job? | 1,613,042 | 9 | 2009-10-23T12:13:34Z | 1,613,055 | 10 | 2009-10-23T12:16:29Z | [
"python",
"xml",
"ruby",
"perl"
] | I know that any language is capable of parsing XML; I'm really just looking for advantages or drawbacks that you may have come across in your own experiences. Perl would be my standard go to here, but I'm open to suggestions.
Thanks!
UPDATE: I ended up going with XML::Simple which did a nice job, but I have one piece... | If you are using Perl then I would recommend [XML::Simple](https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5363190.html):
> As more and more Web sites begin using
> XML for their content, it's
> increasingly important for Web
> developers to know how to parse XML
> data and convert... |
Parsing XML - right scripting languages / packages for the job? | 1,613,042 | 9 | 2009-10-23T12:13:34Z | 1,613,059 | 7 | 2009-10-23T12:17:16Z | [
"python",
"xml",
"ruby",
"perl"
] | I know that any language is capable of parsing XML; I'm really just looking for advantages or drawbacks that you may have come across in your own experiences. Perl would be my standard go to here, but I'm open to suggestions.
Thanks!
UPDATE: I ended up going with XML::Simple which did a nice job, but I have one piece... | For pure XML parsing, I wouldn't use Java, C#, C++, C, etc. They tend to overcomplicate things, as in you want a banana and get the gorilla with it as well.
Higher-level and interpreted languages such as Perl, PHP, Python, Groovy are more suitable. Perl is included in virtually every Linux distro, as is PHP for the mo... |
NumPy: Comparing Elements in Two Arrays | 1,613,249 | 30 | 2009-10-23T12:57:26Z | 1,614,065 | 15 | 2009-10-23T15:03:24Z | [
"python",
"numpy"
] | Anyone ever come up to this problem? Let's say you have two arrays like the following
```
a = array([1,2,3,4,5,6])
b = array([1,4,5])
```
Is there a way to compare what elements in a exist in b? For example,
```
c = a == b # Wishful example here
print c
array([1,4,5])
# Or even better
array([True, False, False, True... | Use np.intersect1d.
```
#!/usr/bin/env python
import numpy as np
a = np.array([1,2,3,4,5,6])
b = np.array([1,4,5])
c=np.intersect1d(a,b)
print(c)
# [1 4 5]
```
Note that np.intersect1d gives the wrong answer if a or b have nonunique elements. In that case use
np.intersect1d\_nu.
There is also np.setdiff1d, setxor1d,... |
NumPy: Comparing Elements in Two Arrays | 1,613,249 | 30 | 2009-10-23T12:57:26Z | 4,381,711 | 34 | 2010-12-07T21:19:57Z | [
"python",
"numpy"
] | Anyone ever come up to this problem? Let's say you have two arrays like the following
```
a = array([1,2,3,4,5,6])
b = array([1,4,5])
```
Is there a way to compare what elements in a exist in b? For example,
```
c = a == b # Wishful example here
print c
array([1,4,5])
# Or even better
array([True, False, False, True... | Actually, there's an even simpler solution than any of these:
```
import numpy as np
a = array([1,2,3,4,5,6])
b = array([1,4,5])
c = np.in1d(a,b)
```
The resulting c is then:
```
array([ True, False, False, True, True, False], dtype=bool)
``` |
In python, how can I do a non-blocking system call? | 1,613,713 | 8 | 2009-10-23T14:09:03Z | 1,613,741 | 10 | 2009-10-23T14:13:23Z | [
"python"
] | In Python, is it possible to do a non-blocking system call without forking off a thread? i.e., can I avoid:
```
import thread
thread.start_new_thread(os.system,('cmd',))
``` | Use the [subprocess](http://docs.python.org/library/subprocess.html) module (Popen) and have the result written to a file. You can either "wait" for the subprocess to terminate or proceed with other business and poll for the result in the file etc. |
How to make Python speak | 1,614,059 | 34 | 2009-10-23T15:02:10Z | 1,614,098 | 9 | 2009-10-23T15:08:45Z | [
"python",
"text-to-speech"
] | How could I make Python say some text?
I could use Festival with subprocess but I won't be able to control it (or maybe in interactive mode, but it won't be clean).
Is there a Python TTS library? Like an API for Festival, eSpeak, ... ? | A simple Google led me to [pyTTS](http://sourceforge.net/projects/uncassist/files/), and a few [documents about it](http://mindtrove.info/articles/synthesizing-speech-with-pytts/). It looks unmaintained and specific to Microsoft's speech engine, however.
On at least Mac OS X, you can use `subprocess` to call out to th... |
How to make Python speak | 1,614,059 | 34 | 2009-10-23T15:02:10Z | 1,827,700 | 25 | 2009-12-01T17:30:43Z | [
"python",
"text-to-speech"
] | How could I make Python say some text?
I could use Festival with subprocess but I won't be able to control it (or maybe in interactive mode, but it won't be clean).
Is there a Python TTS library? Like an API for Festival, eSpeak, ... ? | **Please note that this only work with python 2.x**
You should try using the PyTTSx package since PyTTS is outdated. PyTTSx works with the lastest python version.
<http://pypi.python.org/pypi/pyttsx/1.0> -> The package
Hope it helps |
How to make Python speak | 1,614,059 | 34 | 2009-10-23T15:02:10Z | 18,428,496 | 13 | 2013-08-25T11:27:23Z | [
"python",
"text-to-speech"
] | How could I make Python say some text?
I could use Festival with subprocess but I won't be able to control it (or maybe in interactive mode, but it won't be clean).
Is there a Python TTS library? Like an API for Festival, eSpeak, ... ? | A bit cheesy, but if you use a mac you can pass a terminal command to the console from python.
Try typing the following in the terminal:
```
$ say 'hello world'
```
And there will be a voice from the mac that will speak that. From python such a thing is relatively easy:
```
import os
os.system("echo 'hello world'")... |
How to make Python speak | 1,614,059 | 34 | 2009-10-23T15:02:10Z | 24,100,605 | 10 | 2014-06-07T19:00:41Z | [
"python",
"text-to-speech"
] | How could I make Python say some text?
I could use Festival with subprocess but I won't be able to control it (or maybe in interactive mode, but it won't be clean).
Is there a Python TTS library? Like an API for Festival, eSpeak, ... ? | The [python-espeak](https://launchpad.net/python-espeak) package is available in Debian, Ubuntu, Redhat, and other Linux distributions. It has recent updates, and works fine.
```
from espeak import espeak
espeak.synth("Hello world.")
```
Jonathan Leaders notes that it also works on Windows, and you can install the mb... |
In Python, how to I convert all items in a list to floats? | 1,614,236 | 63 | 2009-10-23T15:33:00Z | 1,614,247 | 139 | 2009-10-23T15:34:28Z | [
"python"
] | I have a script which reads a text file, and pulls decimal numbers out of it as strings, and places them into a list.
So I have this list: `['0.49', '0.54', '0.54', '0.54', '0.54', '0.54', '0.55', '0.54', '0.54', '0.54', '0.55', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54']`
How do I convert... | ```
[float(i) for i in lst]
```
to be precise, it creates a new list with float values. Unlike the `map` approach it will work in py3k. |
In Python, how to I convert all items in a list to floats? | 1,614,236 | 63 | 2009-10-23T15:33:00Z | 1,614,249 | 44 | 2009-10-23T15:34:32Z | [
"python"
] | I have a script which reads a text file, and pulls decimal numbers out of it as strings, and places them into a list.
So I have this list: `['0.49', '0.54', '0.54', '0.54', '0.54', '0.54', '0.55', '0.54', '0.54', '0.54', '0.55', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54']`
How do I convert... | `map(float, mylist)` should do it.
(In Python 3, map ceases to return a list object, so if you want a new list and not just something to iterate over, you either need `list(map(float, mylist)` - or use SilentGhost's answer which arguably is more pythonic.) |
ImportError: No module named Foundation | 1,614,648 | 13 | 2009-10-23T16:46:08Z | 18,043,508 | 14 | 2013-08-04T13:35:44Z | [
"python",
"xcode",
"osx-snow-leopard",
"pyobjc"
] | I am trying to follow the instructions for the accepted answer to "PyObjC development with Xcode 3.2". I will repost them here since I don't have enough rep to comment on the actual question:
---
Here's what I have done to get PyObjC working in Snow Leopard:
* Using the Finder, I went to `Go > Connect to Server...` ... | I had the same problem. Mine was caused I think by using [homebrew](http://brew.sh) to install my own Python to tinker with.
Because I was worried about mixing python versions, rather than creating the link as described above, I installed a new pyobjc using:
```
$ pip install pyobjc
```
For interest, from (<http://p... |
What is causing "unbound method __init__() must be called with instance as first argument" from this Python code? | 1,615,148 | 6 | 2009-10-23T18:24:04Z | 1,615,165 | 8 | 2009-10-23T18:29:06Z | [
"python",
"init"
] | I have this class:
```
from threading import Thread
import time
class Timer(Thread):
def __init__(self, interval, function, *args, **kwargs):
Thread.__init__()
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.start... | This is a frequently asked question at SO, but the answer, in brief, is that the way you call your superclass's constructor is like:
```
super(Timer,self).__init__()
``` |
What is causing "unbound method __init__() must be called with instance as first argument" from this Python code? | 1,615,148 | 6 | 2009-10-23T18:24:04Z | 1,615,169 | 13 | 2009-10-23T18:29:40Z | [
"python",
"init"
] | I have this class:
```
from threading import Thread
import time
class Timer(Thread):
def __init__(self, interval, function, *args, **kwargs):
Thread.__init__()
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.start... | You are doing:
```
Thread.__init__()
```
Use:
```
Thread.__init__(self)
```
Or, rather, use `super()` |
In Python, can I print 3 lists in order by index number? | 1,615,289 | 6 | 2009-10-23T18:53:32Z | 1,615,300 | 7 | 2009-10-23T18:55:53Z | [
"python",
"list"
] | So I have three lists:
```
['this', 'is', 'the', 'first', 'list']
[1, 2, 3, 4, 5]
[0.01, 0.2, 0.3, 0.04, 0.05]
```
Is there a way that would allow me to print the values in these lists in order by index?
e.g.
```
this, 1, 0.01 (all items at list[0])
is, 2, 0.2 (all items at list[1])
the, 3, 0.3 (all items at list[2... | What you are probably looking for is called `zip`:
```
>>> x = ['this', 'is', 'the', 'first', 'list']
>>> y = [1, 2, 3, 4, 5]
>>> z = [0.01, 0.2, 0.3, 0.04, 0.05]
>>> zip(x,y,z)
[('this', 1, 0.01), ('is', 2, 0.20000000000000001), ('the', 3, 0.29999999999999999), ('first', 4, 0.040000000000000001), ('list', 5, 0.050000... |
Pasting multiple lines into IDLE | 1,615,379 | 16 | 2009-10-23T19:15:46Z | 1,615,535 | 15 | 2009-10-23T19:48:47Z | [
"python",
"python-idle"
] | Is there a way to paste a block of code into IDLE? Pasting line by line works, but sometimes I'd like to paste many lines at once. When I try, IDLE reads the first line and ignores the rest.
```
>>> a = 1
b = 2
c = 3
>>>
>>> a
1
>>> b
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
... | Probably not the most beautiful procedure, but this works:
```
cmds = '''
```
paste your commands, followed by `'''`:
```
a = 1
b = 2
c = 3
'''
```
Then `exec(cmds)` will execute them.
Or more directly,
```
exec('''
```
then paste your commands, followed by `''')`:
```
a = 1
b = 2
c = 3
''')
```
It's just a tr... |
Python dictionary creation error | 1,615,501 | 5 | 2009-10-23T19:42:16Z | 1,615,546 | 13 | 2009-10-23T19:50:10Z | [
"python",
"python-2.5"
] | I am trying to create a Python dictionary from a stored list. This first method works
```
>>> myList = []
>>> myList.append('Prop1')
>>> myList.append('Prop2')
>>> myDict = dict([myList])
```
However, the following method does not work
```
>>> myList2 = ['Prop1','Prop2','Prop3','Prop4']
>>> myDict2 = dict([myList2])... | You're doing it wrong.
The `dict()` constructor doesn't take a list of items (much less a list containing a single list of items), it takes an iterable of 2-element iterables. So if you changed your code to be:
```
myList = []
myList.append(["mykey1", "myvalue1"])
myList.append(["mykey2", "myvalue2"])
myDict = dict(m... |
How to use C++ classes with ctypes? | 1,615,813 | 30 | 2009-10-23T20:51:00Z | 1,616,143 | 25 | 2009-10-23T21:59:45Z | [
"c++",
"python",
"ctypes"
] | I'm just getting started with ctypes and would like to use a C++ class that I have exported in a dll file from within python using ctypes.
So lets say my C++ code looks something like this:
```
class MyClass {
public:
int test();
...
```
I would know create a .dll file that contains this class and then load the... | The short story is that there is no standard binary interface for C++ in the way that there is for C. Different compilers output different binaries for the same C++ dynamic libraries, due to name mangling and different ways to handle the stack between library function calls.
So, unfortunately, there really isn't a por... |
How to use C++ classes with ctypes? | 1,615,813 | 30 | 2009-10-23T20:51:00Z | 7,061,012 | 26 | 2011-08-15T01:44:32Z | [
"c++",
"python",
"ctypes"
] | I'm just getting started with ctypes and would like to use a C++ class that I have exported in a dll file from within python using ctypes.
So lets say my C++ code looks something like this:
```
class MyClass {
public:
int test();
...
```
I would know create a .dll file that contains this class and then load the... | Besides Boost.Python(which is probably a more friendly solution for larger projects that require one-to-one mapping of C++ classes to python classes), you could provide on the C++ side a C interface. It's one solution of many so it has its own trade offs, but I will present it for the benefit of those who aren't famili... |
PIL Best Way To Replace Color? | 1,616,767 | 11 | 2009-10-24T02:42:12Z | 1,617,909 | 20 | 2009-10-24T12:36:50Z | [
"python",
"image",
"replace",
"colors",
"python-imaging-library"
] | I am trying to remove a certain color from my image however it's not working as well as I'd hoped. I tried to do the same thing as seen here <http://stackoverflow.com/questions/765736/using-pil-to-make-all-white-pixels-transparent> however the image quality is a bit lossy so it leaves a little ghost of odd colored pixe... | The best way to do it is to use the "color to alpha" algorithm used in [Gimp](http://www.gimp.org/tutorials/Changing%5FBackground%5FColor%5F1/) to replace a color. It will work perfectly in your case. I reimplemented this algorithm using PIL for an open source python photo processor [phatch](http://photobatch.wikidot.c... |
PIL Best Way To Replace Color? | 1,616,767 | 11 | 2009-10-24T02:42:12Z | 3,169,874 | 7 | 2010-07-03T00:55:01Z | [
"python",
"image",
"replace",
"colors",
"python-imaging-library"
] | I am trying to remove a certain color from my image however it's not working as well as I'd hoped. I tried to do the same thing as seen here <http://stackoverflow.com/questions/765736/using-pil-to-make-all-white-pixels-transparent> however the image quality is a bit lossy so it leaves a little ghost of odd colored pixe... | Using numpy and PIL:
This loads the image into a numpy array of shape `(W,H,3)`, where `W` is the
width and `H` is the height. The third axis of the array represents the 3 color
channels, `R,G,B`.
```
import Image
import numpy as np
orig_color = (255,255,255)
replacement_color = (0,0,0)
img = Image.open(filename).co... |
PIL Best Way To Replace Color? | 1,616,767 | 11 | 2009-10-24T02:42:12Z | 3,850,345 | 8 | 2010-10-03T15:24:43Z | [
"python",
"image",
"replace",
"colors",
"python-imaging-library"
] | I am trying to remove a certain color from my image however it's not working as well as I'd hoped. I tried to do the same thing as seen here <http://stackoverflow.com/questions/765736/using-pil-to-make-all-white-pixels-transparent> however the image quality is a bit lossy so it leaves a little ghost of odd colored pixe... | ```
#!/usr/bin/python
from PIL import Image
import sys
img = Image.open(sys.argv[1])
img = img.convert("RGBA")
pixdata = img.load()
# Clean the background noise, if color != white, then set to black.
# change with your color
for y in xrange(img.size[1]):
for x in xrange(img.size[0]):
if pixdata[x, y] == ... |
IN clause with integers in sqlalchemy/psycopg2 | 1,617,076 | 7 | 2009-10-24T05:43:24Z | 13,941,863 | 7 | 2012-12-18T21:34:55Z | [
"python",
"sql",
"postgresql"
] | Just a beginner with the python/postgres combo so forgive me if this is trivial. I'm executing a raw SQL query with sqlalchemy along the lines of:
```
SELECT * FROM table WHERE pk_table_id IN ()
```
For the example below I tried `self.ids` as a tuple containing string or integers as well as an array containing string... | You can use the [cur.mogrify](http://initd.org/psycopg/docs/usage.html#adapt-tuple) method:
```
cur = my_connection.cursor()
cur.execute(cur.mogrify('SELECT * FROM public.table WHERE pk_table_id IN %s', (tuple(self.ids),)))
``` |
OrderedDict for older versions of python | 1,617,078 | 52 | 2009-10-24T05:44:33Z | 1,617,087 | 21 | 2009-10-24T05:49:26Z | [
"python"
] | Ordered dictionaries are extremely useful structures, but unfortunately these are quite recent only working in versions from [3.1](http://docs.python.org/dev/py3k/library/collections.html#ordereddict-objects) and [2.7](http://docs.python.org/dev/whatsnew/2.7.html#pep-372-adding-an-ordered-dictionary-to-collections). Ho... | According to the [documentation](http://docs.python.org/dev/py3k/library/collections.html#collections.OrderedDict), for Python versions 2.4 or later [this code](http://code.activestate.com/recipes/576693/) should be used. There is also some [code from Raymond Hettinger](http://code.activestate.com/recipes/576669/), one... |
OrderedDict for older versions of python | 1,617,078 | 52 | 2009-10-24T05:44:33Z | 6,852,800 | 56 | 2011-07-28T00:20:51Z | [
"python"
] | Ordered dictionaries are extremely useful structures, but unfortunately these are quite recent only working in versions from [3.1](http://docs.python.org/dev/py3k/library/collections.html#ordereddict-objects) and [2.7](http://docs.python.org/dev/whatsnew/2.7.html#pep-372-adding-an-ordered-dictionary-to-collections). Ho... | I installed ordereddict on python 2.6 with pip
```
pip install ordereddict
``` |
Finding a print statement in Python | 1,617,494 | 9 | 2009-10-24T09:36:07Z | 1,620,686 | 19 | 2009-10-25T11:38:30Z | [
"python"
] | Sometimes I leave debugging printing statements in my project and it is difficult to find it. Is there any way to find out what line is printing something in particular?
**Sidenote**
It appears that searching smart can solve the majority of cases. In Pydev (and other IDEs) there is a Search function which allows sear... | You asked about static solutions. Here's a dynamic one. Suppose you run the code and see an errant print or write to sys.stdout, and want to know where it comes from. You can replace sys.stdout and let the exception traceback help you:
```
>>> import sys
>>> def go():
... sys.stdout = None
... print "Hello!"
...
... |
Python's MySqlDB not getting updated row | 1,617,637 | 10 | 2009-10-24T10:43:14Z | 1,617,662 | 15 | 2009-10-24T10:56:58Z | [
"python",
"mysql"
] | I have a script that waits until some row in a db is updated:
```
con = MySQLdb.connect(server, user, pwd, db)
```
When the script starts the row's value is `"running"`, and it waits for the value to become `"finished"`
```
while(True):
sql = '''select value from table where some_condition'''
cur = self.getC... | This is an InnoDB table, right? InnoDB is transactional storage engine. Setting autocommit to true will probably fix this behavior for you.
```
conn.autocommit(True)
```
Alternatively, you could change the transaction isolation level. You can read more about this here:
<http://dev.mysql.com/doc/refman/5.0/en/set-tran... |
Pyserial problem with Arduino - works with the Python shell but not in a program | 1,618,141 | 9 | 2009-10-24T14:26:54Z | 4,941,880 | 7 | 2011-02-09T06:16:15Z | [
"python",
"serial-port",
"arduino"
] | All right, so I am positive my Arduino circuit is correct and the code for it. I know this because when I use the serial monitor built into the Arduino IDE and send 'H' an LED lights up, when I send 'L' that LED turns off.
Now I made a Python program
```
import serial
ser = serial.Serial("COM4",9600)
ser.write("H")
`... | When you open the serial port, this causes the Arduino to reset. Since the Arduino takes some time to bootup, all the input goes to the bitbucket (or probably to the bootloader which does god knows what with it). If you insert a sleep, you wait for the Arduino to come up so your serial code. This is why it works intera... |
Disable link to edit object in django's admin (display list only)? | 1,618,728 | 29 | 2009-10-24T18:42:22Z | 1,982,474 | 51 | 2009-12-30T21:02:14Z | [
"python",
"django",
"django-admin",
"modeladmin"
] | In Django's admin, I want *disable* the links provided on the "select item to change" page so that users cannot go anywhere to edit the item. (I am going to limit what the users can do with this list to a set of drop down actions - no actual editing of fields).
I see that Django has the ability to [choose which fields... | I wanted a Log viewer as a list only.
I got it working like this:
```
class LogEntryAdmin(ModelAdmin):
actions = None
list_display = (
'action_time', 'user',
'content_type', 'object_repr',
'change_message')
search_fields = ['=user__username', ]
fieldsets = [
(None, {'... |
Disable link to edit object in django's admin (display list only)? | 1,618,728 | 29 | 2009-10-24T18:42:22Z | 5,837,386 | 16 | 2011-04-29T21:04:02Z | [
"python",
"django",
"django-admin",
"modeladmin"
] | In Django's admin, I want *disable* the links provided on the "select item to change" page so that users cannot go anywhere to edit the item. (I am going to limit what the users can do with this list to a set of drop down actions - no actual editing of fields).
I see that Django has the ability to [choose which fields... | As user, omat, mentioned in a comment above, any attempt to simply remove the links does not prevent users from still accessing the change page manually. However, that, too, is easy enough to remedy:
```
class MyModelAdmin(admin.ModelAdmin)
# Other stuff here
def change_view(self, request, obj=None):
f... |
Disable link to edit object in django's admin (display list only)? | 1,618,728 | 29 | 2009-10-24T18:42:22Z | 26,514,914 | 10 | 2014-10-22T18:50:37Z | [
"python",
"django",
"django-admin",
"modeladmin"
] | In Django's admin, I want *disable* the links provided on the "select item to change" page so that users cannot go anywhere to edit the item. (I am going to limit what the users can do with this list to a set of drop down actions - no actual editing of fields).
I see that Django has the ability to [choose which fields... | Doing this properly requires two steps:
* Hide the edit link, so nobody stumbles on the detail page (change view) by mistake.
* Modify the change view to redirect back to the list view.
The second part is important: if you don't do this then people will still be able to access the change view by entering a URL direct... |
detect new or modified files with python | 1,618,853 | 6 | 2009-10-24T19:34:34Z | 1,618,871 | 13 | 2009-10-24T19:41:57Z | [
"python",
"linux",
"file",
"filesystems"
] | I'm trying to detect when a new file is created a directory or when an existing file is modified in a directory.
I tried searching for a script that would do this (preferably in python or bash) but came up short. My environment is linux with Python 2.6
[Related Question](http://stackoverflow.com/questions/415856/how-... | You can use `gio` which is the Filesystem part of GLib (In GLib's python bindings)
```
import gio
def directory_changed(monitor, file1, file2, evt_type):
if (evt_type in (gio.FILE_MONITOR_EVENT_CREATED,
gio.FILE_MONITOR_EVENT_DELETED)):
print "Changed:", file1, file2, evt_type
gfile = gio.File(".")
... |
Python zlib output, how to recover out of mysql utf-8 table? | 1,618,926 | 7 | 2009-10-24T20:03:38Z | 1,618,942 | 7 | 2009-10-24T20:11:57Z | [
"python",
"mysql",
"unicode",
"utf-8",
"zlib"
] | In python, I compressed a string using zlib, and then inserted it into a mysql column that is of type blob, using the utf-8 encoding. The string comes back as utf-8, but it's not clear how to get it back into a format where I can decompress it. Here is some pseduo-output:
valueInserted = zlib.compress('a')
= 'x\x9cK\x... | Unicode is designed to be compatible with latin-1, so try:
```
>>> import zlib
>>> u = zlib.compress("test").decode('latin1')
>>> u
u'x\x9c+I-.\x01\x00\x04]\x01\xc1'
```
And then
```
>>> zlib.decompress(u.encode('latin1'))
'test'
```
*EDIT:* Fixed typo, latin-1 isn't designed to be compatible with unicode, it's the... |
How to start a long-running process from a Django view? | 1,619,397 | 12 | 2009-10-24T22:42:11Z | 1,619,426 | 10 | 2009-10-24T22:57:01Z | [
"python",
"django",
"long-running-processes"
] | I need to run a process that might take hours to complete from a Django view. I don't need to know the state or communicate with it but I need that view to redirect away right after starting the process.
I've tried using `subprocess.Popen`, using it within a new `threading.Thread`, `multiprocessing.Process`. However, ... | I don't know if this will be suitable for your case, nevertheless here is what I do: I use a task queue (via a django model); when the view is called, it enters a new record in the tasks and redirects happily. Tasks in turn are executed by cron on a regular basis independently from django.
Edit: cron calls the relevan... |
How to extract the member from single-member set in python? | 1,619,514 | 30 | 2009-10-24T23:41:50Z | 1,619,539 | 42 | 2009-10-24T23:54:15Z | [
"python",
"set"
] | I recently encountered a scenario in which if a set only contained a single element, I wanted to do something with that element. To get the element, I settled on this approach:
```
element = list(myset)[0]
```
But this isn't very satisfying, as it creates an unnecessary list. It could also be done with iteration, but... | tuple unpacking works.
```
(element,) = myset
```
(By the way, python-dev has explored but rejected the addition of myset.get() to return an arbitrary element from a set. [Discussion here](http://mail.python.org/pipermail/python-dev/2009-October/093227.html), Guido van Rossum answers [1](http://mail.python.org/piperm... |
How to extract the member from single-member set in python? | 1,619,514 | 30 | 2009-10-24T23:41:50Z | 1,620,320 | 17 | 2009-10-25T08:05:16Z | [
"python",
"set"
] | I recently encountered a scenario in which if a set only contained a single element, I wanted to do something with that element. To get the element, I settled on this approach:
```
element = list(myset)[0]
```
But this isn't very satisfying, as it creates an unnecessary list. It could also be done with iteration, but... | Between making a tuple and making an iterator, it's almost a wash, but iteration wins by a nose...:
```
$ python2.6 -mtimeit -s'x=set([1])' 'a=tuple(x)[0]'
1000000 loops, best of 3: 0.465 usec per loop
$ python2.6 -mtimeit -s'x=set([1])' 'a=tuple(x)[0]'
1000000 loops, best of 3: 0.465 usec per loop
$ python2.6 -mtimei... |
How to extract the member from single-member set in python? | 1,619,514 | 30 | 2009-10-24T23:41:50Z | 4,486,544 | 9 | 2010-12-20T02:59:07Z | [
"python",
"set"
] | I recently encountered a scenario in which if a set only contained a single element, I wanted to do something with that element. To get the element, I settled on this approach:
```
element = list(myset)[0]
```
But this isn't very satisfying, as it creates an unnecessary list. It could also be done with iteration, but... | I reckon [kaizer.se's answer](http://stackoverflow.com/questions/1619514/how-to-extract-the-member-from-single-member-set-in-python/1619539#1619539) is great. But if your set *might* contain more than one element, and you want a not-so-arbitrary element, you might want to use [`min`](http://docs.python.org/library/func... |
Using Python Regular Expression in Django | 1,619,554 | 8 | 2009-10-25T00:08:20Z | 1,619,583 | 17 | 2009-10-25T00:20:42Z | [
"python",
"regex",
"django",
"django-urls"
] | I have an web address:
<http://www.example.com/org/companyA>
I want to be able to pass CompanyA to a view using regular expressions.
This is what I have:
```
(r'^org/?P<company_name>\w+/$',"orgman.views.orgman")
```
and it doesn't match.
Ideally all URL's that look like example.com/org/X would pass x to the view.... | You need to wrap the group name in parentheses. The syntax for named groups is `(?P<name>regex)`, not `?P<name>regex`. Also, if you don't want to require a trailing slash, you should make it optional.
It's easy to test regular expression matching with the Python interpreter, for example:
```
>>> import re
>>> re.matc... |
Problems using PyQt's Resource System | 1,619,574 | 4 | 2009-10-25T00:18:55Z | 1,658,244 | 16 | 2009-11-01T20:39:50Z | [
"python",
"pyqt",
"pyqt4"
] | I am trying to use PyQt's Resource System but it appears I have no clue what I am doing! I already have to application created, along with its GUI I am just trying to import some images to use with the program.
I used the QtDesigner to create the resource file and I compiled it using pyrcc4.exe. But when I attempt to ... | pyrcc generates Python 2.x code by default.
Try regenerating your resource files using pyrcc with flag '-py3' |
In Django, how to clear all the memcached keys and values? | 1,620,072 | 14 | 2009-10-25T05:11:27Z | 1,620,084 | 31 | 2009-10-25T05:31:07Z | [
"python",
"django",
"caching",
"memcached"
] | I don't want to restart the memcached server! | ```
from django.core.cache import cache
cache._cache.flush_all()
```
Also see this ticket, it has a patch (that I haven't tested) to flush any type of cache backend: <http://code.djangoproject.com/ticket/11503> |
str.format(list) with negative index doesn't work in Python | 1,620,237 | 8 | 2009-10-25T07:16:17Z | 1,620,294 | 11 | 2009-10-25T07:51:08Z | [
"python",
"string",
"formatting"
] | I use a negative index in replacement fields to output a formatted list,but it raises a TypeError.The codes are as follows:
```
>>> a=[1,2,3]
>>> a[2]
3
>>> a[-1]
3
>>> 'The last:{0[2]}'.format(a)
'The last:3'
>>> 'The last:{0[-1]}'.format(a)
Traceback (most recent call last):
File "", line 1, in
TypeError: list in... | It's what I would call a design glitch in the format string specs. Per [the docs](http://docs.python.org/library/string.html#format-string-syntax),
```
element_index ::= integer | index_string
```
but, alas, `-1` is not "an integer" -- it's an expression. The unary-minus operator doesn't even have particularly h... |
Python: advantages and disvantages of _mysql vs MySQLdb? | 1,620,575 | 9 | 2009-10-25T10:37:00Z | 1,620,609 | 13 | 2009-10-25T10:49:40Z | [
"python",
"mysql"
] | Two libraries for Mysql.
I've always used \_mysql because it's simpler.
Can anyone tell me the difference, and why I should use which one in certain occasions? | MySQLdb uses DB-API (described in [PEP 249](http://www.python.org/dev/peps/pep-0249/)) which should be preferred, since it's common to all database drivers. IMHO there is no advantage in going low-level with `_mysql`. I'd rather think of using higher level libraries, like [SQLAlchemy](http://sqlalchemy.org), instead. |
Python: advantages and disvantages of _mysql vs MySQLdb? | 1,620,575 | 9 | 2009-10-25T10:37:00Z | 1,666,697 | 8 | 2009-11-03T11:15:41Z | [
"python",
"mysql"
] | Two libraries for Mysql.
I've always used \_mysql because it's simpler.
Can anyone tell me the difference, and why I should use which one in certain occasions? | Alternatively, you can use [MySQL Connector/Python](https://launchpad.net/myconnpy):
> MySQL Connector/Python is implementing the MySQL Client/Server protocol completely in Python. This means you don't have to compile anything or MySQL doesn't even have to be installed on the machine. |
Send and receive messages via (libpurple) messenger protocols | 1,620,793 | 4 | 2009-10-25T12:36:26Z | 1,652,156 | 11 | 2009-10-30T20:35:44Z | [
"php",
"python",
"libpurple"
] | I had an idea that would require me be able to send and receive messages via the standard messenger protocols such as msn, icq, aim, skype, etc...
I am currently only familiar with PHP and Python and would thus enjoy a library which I can access from said languages. I have found phurple (<http://sourceforge.net/projec... | Here is how to connect to the Pidgin DBus server.
```
#!/usr/bin/env python
import dbus
bus = dbus.SessionBus()
if "im.pidgin.purple.PurpleService" in bus.list_names():
purple = bus.get_object("im.pidgin.purple.PurpleService",
"/im/pidgin/purple/PurpleObject",
"im.pidgin.purple.PurpleInte... |
Determining neighbours of cell two dimensional list | 1,620,940 | 4 | 2009-10-25T13:36:41Z | 1,621,118 | 9 | 2009-10-25T15:03:58Z | [
"python",
"matrix"
] | I have a list of lists, something like
`[[1, 2, 3,],[4, 5, 6,],[7, 8, 9]]`.
Represented graphically as:
```
1 2 3
4 5 6
7 8 9
```
I'm looking for an elegant approach to checking the value of neighbours of a cell, horizontally, vertically and diagonally. For instance, the neighbours of [0][2] are [0][1], [1][1] and ... | ```
# Size of "board"
X = 10
Y = 10
neighbors = lambda x, y : [(x2, y2) for x2 in range(x-1, x+2)
for y2 in range(y-1, y+2)
if (-1 < x <= X and
-1 < y <= Y and
(x != x2 or y != y2) and
... |
dynamically adding functions to a Python module | 1,621,350 | 6 | 2009-10-25T16:40:50Z | 1,621,382 | 10 | 2009-10-25T16:51:37Z | [
"python",
"metaprogramming",
"decorator"
] | Our framework requires wrapping certain functions in some ugly boilerplate code:
```
def prefix_myname_suffix(obj):
def actual():
print 'hello world'
obj.register(actual)
return obj
```
I figured this might be simplified with a decorator:
```
@register
def myname():
print 'hello world'
```
H... | use either
```
current_module.new_name = func
```
or
```
setattr(current_module, new_name, func)
``` |
How can I strip comments and doc strings from python source code? | 1,621,521 | 4 | 2009-10-25T17:43:25Z | 1,621,551 | 8 | 2009-10-25T17:54:03Z | [
"python",
"comments",
"code-formatting"
] | Is there a program which I can run like this:
```
py2py.py < orig.py > smaller.py
```
Where orig.py contains python source code with comments and doc strings, and smaller.py contains identical, runnable source code but without the comments and doc strings?
Code which originally looked like this:
```
#/usr/bin/pytho... | [This Python minifier](https://pypi.python.org/pypi/pyminifier) looks like it does what you need. |
Is there a way to split a string by every nth separator in Python? | 1,621,906 | 7 | 2009-10-25T19:56:34Z | 1,621,952 | 25 | 2009-10-25T20:13:39Z | [
"python",
"string",
"split"
] | For example, if I had the following string:
"this-is-a-string"
Could I split it by every 2nd "-" rather than every "-" so that it returns two values ("this-is" and "a-string") rather than returning four? | Hereâs another solution:
```
span = 2
words = "this-is-a-string".split("-")
print ["-".join(words[i:i+span]) for i in range(0, len(words), span)]
``` |
Is there a way to split a string by every nth separator in Python? | 1,621,906 | 7 | 2009-10-25T19:56:34Z | 1,621,957 | 9 | 2009-10-25T20:14:56Z | [
"python",
"string",
"split"
] | For example, if I had the following string:
"this-is-a-string"
Could I split it by every 2nd "-" rather than every "-" so that it returns two values ("this-is" and "a-string") rather than returning four? | Regular expressions handle this easily:
```
import re
s = "aaaa-aa-bbbb-bb-c-ccccc-d-ddddd"
print re.findall("[^-]+-[^-]+", s)
```
Output:
```
['aaaa-aa', 'bbbb-bb', 'c-ccccc', 'd-ddddd']
```
Update for Nick D:
```
n = 3
print re.findall("-".join(["[^-]+"] * n), s)
```
Output:
```
['aaaa-aa-bbbb', 'bb-c-ccccc']
... |
Is there a way to split a string by every nth separator in Python? | 1,621,906 | 7 | 2009-10-25T19:56:34Z | 1,621,986 | 16 | 2009-10-25T20:27:23Z | [
"python",
"string",
"split"
] | For example, if I had the following string:
"this-is-a-string"
Could I split it by every 2nd "-" rather than every "-" so that it returns two values ("this-is" and "a-string") rather than returning four? | ```
>>> s="a-b-c-d-e-f-g-h-i-j-k-l" # use zip(*[i]*n)
>>> i=iter(s.split('-')) # for the nth case
>>> map("-".join,zip(i,i))
['a-b', 'c-d', 'e-f', 'g-h', 'i-j', 'k-l']
>>> i=iter(s.split('-'))
>>> map("-".join,zip(*[i]*3))
['a-b-c', 'd-e-f', 'g-h-i', 'j-k-l']
>>> i=iter(s.split('-'))
>>>... |
Find Monday's date with Python | 1,622,038 | 33 | 2009-10-25T20:53:47Z | 1,622,052 | 86 | 2009-10-25T21:02:20Z | [
"python",
"django"
] | How do I find the previous Monday's date, based off of the current date using Python? I thought maybe I could use: `datetime.weekday()` to do it, but I am getting stuck.
I basically want to find today's date and Mondays date to construct a date range query in django using: `created__range=(start_date, end_date)`. | ```
>>> import datetime
>>> today = datetime.date.today()
>>> today + datetime.timedelta(days=-today.weekday(), weeks=1)
datetime.date(2009, 10, 26)
```
*Some words of explanation:*
Take todays date. Subtract the number of days which already passed this week (this gets you 'last' monday). Add one week.
**Edit**: The... |
Find Monday's date with Python | 1,622,038 | 33 | 2009-10-25T20:53:47Z | 1,622,130 | 7 | 2009-10-25T21:28:28Z | [
"python",
"django"
] | How do I find the previous Monday's date, based off of the current date using Python? I thought maybe I could use: `datetime.weekday()` to do it, but I am getting stuck.
I basically want to find today's date and Mondays date to construct a date range query in django using: `created__range=(start_date, end_date)`. | Note: The OP says in the comments, "*I was looking for the past Monday*". I take this to mean we are looking for the last Monday that occurred strictly before today.
The calculation is a little difficult to get right using only the `datetime` module (especially given the above interpretation of "past Monday" and if yo... |
Find Monday's date with Python | 1,622,038 | 33 | 2009-10-25T20:53:47Z | 1,622,263 | 24 | 2009-10-25T22:12:27Z | [
"python",
"django"
] | How do I find the previous Monday's date, based off of the current date using Python? I thought maybe I could use: `datetime.weekday()` to do it, but I am getting stuck.
I basically want to find today's date and Mondays date to construct a date range query in django using: `created__range=(start_date, end_date)`. | ChristopheD's post is close to what you want. I don't have enough rep to make a comment :(
Instead of (which actually gives you the next upcoming monday):
```
>>> today + datetime.timedelta(days=-today.weekday(), weeks=1)
datetime.date(2009, 10, 26)
```
I would say:
```
>>> last_monday = today - datetime.timedelta(... |
Find Monday's date with Python | 1,622,038 | 33 | 2009-10-25T20:53:47Z | 9,317,560 | 15 | 2012-02-16T19:13:25Z | [
"python",
"django"
] | How do I find the previous Monday's date, based off of the current date using Python? I thought maybe I could use: `datetime.weekday()` to do it, but I am getting stuck.
I basically want to find today's date and Mondays date to construct a date range query in django using: `created__range=(start_date, end_date)`. | I think the easiest way is using [python-dateutil](https://dateutil.readthedocs.org/en/latest) like this:
```
from datetime import date
from dateutil.relativedelta import relativedelta, MO
today = date.today()
last_monday = today + relativedelta(weekday=MO(-1))
print last_monday
``` |
Twisted: source IP address for outbound connections | 1,622,454 | 3 | 2009-10-25T23:21:51Z | 1,758,184 | 8 | 2009-11-18T18:46:04Z | [
"python",
"linux",
"networking",
"network-programming",
"twisted"
] | I'm in the process of implementing a service -- written in Python with the Twisted framework, running on Debian GNU/Linux -- that checks the availability of SIP servers. For this I use the OPTIONS method (a SIP protocol feature), as this seems to be a commonplace practice. In order to construct correct and RFC complian... | For the sake of completeness I answer my own question:
Make sure you use connect() on the transport before trying to determine the host's source IP address. The following excerpt shows the relevant part of a protocol implementation:
```
class FooBarProtocol(protocol.DatagramProtocol):
def startProtocol(self):
... |
what exactly is a "register machine"? | 1,622,530 | 20 | 2009-10-25T23:54:04Z | 1,622,542 | 18 | 2009-10-25T23:58:22Z | [
"python",
"language-design",
"language-theory",
"language-implementation"
] | From <http://code.google.com/p/unladen-swallow/wiki/ProjectPlan> I quote:
"Using a JIT will also allow us to move Python from a stack-based machine to a register machine, which has been shown to improve performance in other similar languages (Ierusalimschy et al, 2005; Shi et al, 2005)."
In college I built a simple c... | A register machine is a hardware or software unit that when working with data takes it from memory, puts it in a location where it can work with it quickly, and then returns the result.
For example a regular CPU is a register machine. Since the ALU (the unit that works with numbers in a CPU) can only work with numbers... |
what exactly is a "register machine"? | 1,622,530 | 20 | 2009-10-25T23:54:04Z | 1,622,590 | 10 | 2009-10-26T00:22:01Z | [
"python",
"language-design",
"language-theory",
"language-implementation"
] | From <http://code.google.com/p/unladen-swallow/wiki/ProjectPlan> I quote:
"Using a JIT will also allow us to move Python from a stack-based machine to a register machine, which has been shown to improve performance in other similar languages (Ierusalimschy et al, 2005; Shi et al, 2005)."
In college I built a simple c... | A register machine almost always has a stack, also.
But a stack machine rarely has architecturally visible registers, or it may only have one or two.
A register machine may have some stack ops and may even have a stack addressing mode.
The difference is one of orientation. The register machine will mostly have instr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.