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 |
|---|---|---|---|---|---|---|---|---|---|
Readably print out a python dict() sorted by key | 1,479,649 | 46 | 2009-09-25T21:22:11Z | 1,479,691 | 12 | 2009-09-25T21:31:31Z | [
"python"
] | I would like to print a python dictionary to a file using PrettyPrinter (for human readability) but have the dictionary be sorted by key in the output file to further improve readability. So:
```
mydict = {'a':1, 'b':2, 'c':3}
pprint(mydict)
```
currently prints to
```
{'b':2,
'c':3,
'a':1}
```
I would like to Pr... | The Python `pprint` module actually *already* sorts dictionaries by key. In versions prior to Python 2.5, the sorting was only triggered on dictionaries whose pretty-printed representation spanned multiple lines, but in 2.5.X and 2.6.X, *all* dictionaries are sorted.
Generally, though, if you're writing data structure... |
Readably print out a python dict() sorted by key | 1,479,649 | 46 | 2009-09-25T21:22:11Z | 1,479,748 | 53 | 2009-09-25T21:55:27Z | [
"python"
] | I would like to print a python dictionary to a file using PrettyPrinter (for human readability) but have the dictionary be sorted by key in the output file to further improve readability. So:
```
mydict = {'a':1, 'b':2, 'c':3}
pprint(mydict)
```
currently prints to
```
{'b':2,
'c':3,
'a':1}
```
I would like to Pr... | Actually pprint seems to sort the keys for you under python2.5
```
>>> from pprint import pprint
>>> mydict = {'a':1, 'b':2, 'c':3}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3}
>>> mydict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
>>> pprint(mydict)
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
>>> d = dict(zip("kjihgfedcba",ran... |
Readably print out a python dict() sorted by key | 1,479,649 | 46 | 2009-09-25T21:22:11Z | 11,789,032 | 11 | 2012-08-03T03:51:19Z | [
"python"
] | I would like to print a python dictionary to a file using PrettyPrinter (for human readability) but have the dictionary be sorted by key in the output file to further improve readability. So:
```
mydict = {'a':1, 'b':2, 'c':3}
pprint(mydict)
```
currently prints to
```
{'b':2,
'c':3,
'a':1}
```
I would like to Pr... | I wrote the following function to print dicts, lists, and tuples in a more readable format:
```
def printplus(obj):
"""
Pretty-prints the object passed in.
"""
# Dict
if isinstance(obj, dict):
for k, v in sorted(obj.items()):
print u'{0}: {1}'.format(k, v)
# List or tuple ... |
Readably print out a python dict() sorted by key | 1,479,649 | 46 | 2009-09-25T21:22:11Z | 18,219,242 | 8 | 2013-08-13T21:07:44Z | [
"python"
] | I would like to print a python dictionary to a file using PrettyPrinter (for human readability) but have the dictionary be sorted by key in the output file to further improve readability. So:
```
mydict = {'a':1, 'b':2, 'c':3}
pprint(mydict)
```
currently prints to
```
{'b':2,
'c':3,
'a':1}
```
I would like to Pr... | An easy way to print the sorted contents of the dictionary, in Python 3:
```
>>> dict_example = {'c': 1, 'b': 2, 'a': 3}
>>> for key, value in sorted(dict_example.items()):
... print("{} : {}".format(key, value))
...
a : 3
b : 2
c : 1
```
The expression `dict_example.items()` returns tuples, which can then be sort... |
"Too many values to unpack" Exception | 1,479,776 | 52 | 2009-09-25T22:04:27Z | 1,479,796 | 116 | 2009-09-25T22:13:22Z | [
"python",
"django"
] | I'm working on a project in Django and I've just started trying to extend the User model in order to make user profiles.
Unfortunately, I've run into a problem: Every time I try to get the user's profile inside of a template (`user.get_template.lastIP`, for example), I get the following error:
```
Environment:
Reque... | That exception means that you are trying to unpack a tuple, but the tuple has too many values with respect to the number of target variables. For example: this work, and prints 1, then 2, then 3
```
def returnATupleWithThreeValues():
return (1,2,3)
a,b,c = returnATupleWithThreeValues()
print a
print b
print c
```
... |
"Too many values to unpack" Exception | 1,479,776 | 52 | 2009-09-25T22:04:27Z | 1,481,134 | 8 | 2009-09-26T12:43:50Z | [
"python",
"django"
] | I'm working on a project in Django and I've just started trying to extend the User model in order to make user profiles.
Unfortunately, I've run into a problem: Every time I try to get the user's profile inside of a template (`user.get_template.lastIP`, for example), I get the following error:
```
Environment:
Reque... | This problem looked familiar so I thought I'd see if I could replicate from the limited amount of information.
A quick search turned up an entry in James Bennett's blog [here](http://www.b-list.org/weblog/2006/jun/06/django-tips-extending-user-model/) which mentions that when working with the UserProfile to extend the... |
"Too many values to unpack" Exception | 1,479,776 | 52 | 2009-09-25T22:04:27Z | 1,899,737 | 11 | 2009-12-14T08:51:12Z | [
"python",
"django"
] | I'm working on a project in Django and I've just started trying to extend the User model in order to make user profiles.
Unfortunately, I've run into a problem: Every time I try to get the user's profile inside of a template (`user.get_template.lastIP`, for example), I get the following error:
```
Environment:
Reque... | try unpacking in one variable,
python will handle it as a list,
then unpack from the list |
Case-insensitive comparison of sets in Python | 1,479,979 | 4 | 2009-09-25T23:35:12Z | 1,480,291 | 8 | 2009-09-26T02:46:07Z | [
"python",
"django",
"compare"
] | I have two sets (although I can do lists, or whatever):
```
a = frozenset(('Today','I','am','fine'))
b = frozenset(('hello','how','are','you','today'))
```
I want to get:
```
frozenset(['Today'])
```
or at least:
```
frozenset(['today'])
```
The second option is doable if I lowercase everything I presume, but I'm... | Here's version that works for any pair of iterables:
```
def intersection(iterableA, iterableB, key=lambda x: x):
"""Return the intersection of two iterables with respect to `key` function.
"""
def unify(iterable):
d = {}
for item in iterable:
d.setdefault(key(item), []).append... |
how to submit query to .aspx page in python | 1,480,356 | 16 | 2009-09-26T03:27:22Z | 1,480,696 | 19 | 2009-09-26T07:37:23Z | [
"asp.net",
"python",
"asp.net-ajax"
] | I need to scrape query results from an .aspx web page.
<http://legistar.council.nyc.gov/Legislation.aspx>
The url is static, so how do I submit a query to this page and get the results? Assume we need to select "all years" and "all types" from the respective dropdown menus.
Somebody out there must know how to do thi... | As an overview, you will need to perform four main tasks:
* to submit request(s) to the web site,
* to retrieve the response(s) from the site
* to parse these responses
* to have some logic to iterate in the tasks above, with parameters associated with the navigation (to "next" pages in the results list)
The http req... |
Efficient method to determine location on a grid(array) | 1,480,406 | 2 | 2009-09-26T03:58:50Z | 1,480,473 | 7 | 2009-09-26T05:11:18Z | [
"python",
"arrays",
"list",
"performance"
] | I am representing a grid with a 2D list in python. I would like to pick a point (x,y) in the list and determine it's location...right edge, top left corner, somewhere in the middle...
Currently I am checking like so:
```
# left column, not a corner
if x == 0 and y != 0 and y != self.dim_y - 1:
... | ```
def location(x,y,dim_x,dim_y):
index = 1*(y==0) + 2*(y==dim_y-1) + 3*(x==0) + 6*(x==dim_x-1)
return ["interior","top","bottom","left","top-left",
"bottom-left","right","top-right","bottom-right"][index]
``` |
phpMyAdmin equivalent in python? | 1,480,453 | 27 | 2009-09-26T04:51:49Z | 1,480,549 | 9 | 2009-09-26T06:08:12Z | [
"python",
"phpmyadmin"
] | Is there a python equivalent of phpMyAdmin?
Here's why I'm looking for a python version of phpmyadmin: While I agree that phpmyadmin really rocks, I don't want to run php on my server. I'd like to move from apache2-prefork to apache2-mpm-worker. Worker blows the doors off of prefork for performance, but php5 doesn't w... | You can use phpMyAdmin for python project, because phpMyAdmin is meant for MySQL databases. If you are using MySQL, then regardless of whether you are using PHP or python, you can use phpMyAdmin. |
Python interpreter as a c++ class | 1,480,490 | 7 | 2009-09-26T05:28:18Z | 8,849,082 | 12 | 2012-01-13T10:28:54Z | [
"c++",
"python",
"multithreading",
"python-c-api",
"python-embedding"
] | I am working on embedding python in to c++. In some peculiar case I require two separate instances of the interpreter in same thread.
Can I wrap Python interpreter in to a c++ class and get services from two or more class instances? | I have used Py\_NewInterpreter for different interpreters in different threads, but this should also work for several interpreters within one thread:
In the main thread:
```
Py_Initialize();
PyEval_InitThreads();
mainThreadState = PyEval_SaveThread();
```
For each interpreter instance (in any thread):
```
// initia... |
pythonic format for indices | 1,481,192 | 6 | 2009-09-26T13:21:53Z | 1,481,281 | 7 | 2009-09-26T14:00:28Z | [
"python",
"indexing",
"set",
"sequence"
] | I am after a string format to efficiently represent a set of indices.
For example "1-3,6,8-10,16" would produce [1,2,3,6,8,9,10,16]
Ideally I would also be able to represent infinite sequences.
Is there an existing standard way of doing this? Or a good library? Or can you propose your own format?
thanks!
Edit: Wow!... | You don't need a string for that, This is as simple as it can get:
```
from types import SliceType
class sequence(object):
def __getitem__(self, item):
for a in item:
if isinstance(a, SliceType):
i = a.start
step = a.step if a.step else 1
while T... |
Python - Same line of code only works the second time it called? | 1,481,264 | 3 | 2009-09-26T13:49:42Z | 1,481,378 | 7 | 2009-09-26T14:56:27Z | [
"python"
] | Sorry I couldn't really describe my problem much better in the title.
I am trying to learn Python, and came across this strange behavior and was hoping someone could explain this to me.
I am running Ubuntu 8.10 and python 2.5.2
First I import xml.dom
Then I create an instance of a minidom (using its fully qaulifie... | The problem is in `apport_python_hook.apport_excepthook()` as a side effect it imports `xml.dom.minidom`.
Without `apport_except_hook`:
```
>>> import sys
>>> sys.excepthook = sys.__excepthook__
>>> import xml.dom
>>> xml.dom.minidom
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeEr... |
What is the __del__ method, How to call it? | 1,481,488 | 29 | 2009-09-26T15:49:52Z | 1,481,512 | 64 | 2009-09-26T15:58:53Z | [
"python",
"oop"
] | I am reading a code. There is a class in which `__del__` method is defined. I figured out that this method is used to destroy an instance of the class. However, I cannot find a place where this method is used. The main reason for that is that I do not know how this method is used, probably not like that: `obj1.del()`. ... | `__del__` is a **destructor**. It is called when an object is **garbage collected** which happens after all references to the object have been deleted.
In a **simple case** this could be right after you say `del x` or, if `x` is a local variable, after the function ends. In particular, unless there are circular refere... |
What is the __del__ method, How to call it? | 1,481,488 | 29 | 2009-09-26T15:49:52Z | 2,452,895 | 25 | 2010-03-16T08:21:02Z | [
"python",
"oop"
] | I am reading a code. There is a class in which `__del__` method is defined. I figured out that this method is used to destroy an instance of the class. However, I cannot find a place where this method is used. The main reason for that is that I do not know how this method is used, probably not like that: `obj1.del()`. ... | I wrote up the answer for another question, though this is a more accurate question for it.
[Can someone here explain constructors and destructors in python - simple explanation required - new to programming](http://stackoverflow.com/questions/2433130/can-someone-here-explain-constructors-and-destructors-in-python-sim... |
Why I get urllib2.HTTPError with urllib2 and no errors with urllib? | 1,482,028 | 6 | 2009-09-26T19:46:36Z | 1,482,046 | 9 | 2009-09-26T19:55:21Z | [
"python",
"urllib2",
"urllib"
] | I have the following simple code:
```
import urllib2
import sys
sys.path.append('../BeautifulSoup/BeautifulSoup-3.1.0.1')
from BeautifulSoup import *
page='http://en.wikipedia.org/wiki/Main_Page'
c=urllib2.urlopen(page)
```
This code generates the following error messages:
```
c=urllib2.urlopen(page)
File "/us... | The original `urllib` simply does not raise an exception on a 403 code. If you add `print c.getcode()` to the last line of your program, `urllib` will reach it and still print out 403.
Then if you do `print c.read()` at the end, you will see that you did indeed get an error page from Wikipedia. It's just a matter of `... |
Is there any way to programmatically generate Python bytecode? | 1,482,055 | 9 | 2009-09-26T20:01:18Z | 1,482,491 | 9 | 2009-09-27T00:35:35Z | [
"python",
"expression-trees",
"abstract-syntax-tree",
"dsl",
"bytecode"
] | I want to hack around with the Python interpreter and try creating a small DSL . Is there any module where I can do something like this theoretical code (similar to LINQ expression trees)?
```
expression_tree = Function(
Print(
String('Hello world!')
)
)
compile_to_bytecode(expression_tree)
```
Or wo... | Working via `ast` and compiling the tree into bytecode, as another answer suggests, is probably simplest; generating sources and compiling those, almost as good.
However, to explore lower-level approaches, check out the links from [this page](http://news.ycombinator.com/item?id=781461); I've found [byteplay](http://co... |
What does it mean "weakly-referenced object no longer exists"? | 1,482,141 | 5 | 2009-09-26T20:42:08Z | 1,482,477 | 14 | 2009-09-27T00:27:08Z | [
"python"
] | I am running a Python code and I get the following error message:
```
Exception exceptions.ReferenceError: 'weakly-referenced object no longer exists' in <bound method crawler.__del__ of <searchengine.crawler instance at 0x2b8c1f99ef80>> ignored
```
Does anybody know what can it means?
P.S.
This is the code which pr... | A normal AKA strong reference is one that keeps the referred-to object alive: in CPython, each object keeps the number of (normal) references to it that exists (known as its "reference count" or RC) and goes away as soon as the RC reaches zero (occasional generational mark and sweep passes also garbage-collect "referen... |
Java vs Python on Hadoop | 1,482,282 | 46 | 2009-09-26T21:55:05Z | 1,482,294 | 13 | 2009-09-26T22:03:11Z | [
"java",
"python",
"hadoop"
] | I am working on a project using Hadoop and it seems to natively incorporate Java and provide streaming support for Python. Is there is a significant performance impact to choosing one over the other? I am early enough in the process where I can go either way if there is a significant performance difference one way or t... | Java is less dynamic than Python and more effort has been put into its VM, making it a faster language. Python is also held back by its Global Interpreter Lock, meaning it cannot push threads of a single process onto different core.
Whether this makes any significant difference depends on what you intend to do. I susp... |
Java vs Python on Hadoop | 1,482,282 | 46 | 2009-09-26T21:55:05Z | 1,482,440 | 23 | 2009-09-26T23:51:13Z | [
"java",
"python",
"hadoop"
] | I am working on a project using Hadoop and it seems to natively incorporate Java and provide streaming support for Python. Is there is a significant performance impact to choosing one over the other? I am early enough in the process where I can go either way if there is a significant performance difference one way or t... | With Python you'll probably develop faster and with Java will definitely run faster.
Google "benchmarksgame" if you want to see some very accurate speed comparisons between all popular languages, but if I recall correctly you're talking about 3-5x faster.
That said, few things are processor bound these days, so if yo... |
Java vs Python on Hadoop | 1,482,282 | 46 | 2009-09-26T21:55:05Z | 6,700,580 | 14 | 2011-07-14T22:15:15Z | [
"java",
"python",
"hadoop"
] | I am working on a project using Hadoop and it seems to natively incorporate Java and provide streaming support for Python. Is there is a significant performance impact to choosing one over the other? I am early enough in the process where I can go either way if there is a significant performance difference one way or t... | You can write Hadoop mapreduce transformations either as "streaming" or as a "custom jar". If you use streaming, you can write your code in any language you like, including Python or C++. Your code will just read from STDIN and output to STDOUT. However, on hadoop versions before 0.21, hadoop streaming used to only str... |
what's a good way to combinate through a set? | 1,482,308 | 15 | 2009-09-26T22:11:20Z | 1,482,316 | 34 | 2009-09-26T22:18:15Z | [
"python",
"factorial"
] | Given a set `{a,b,c,d}`, what's a good way to produce `{a,b,c,d,ab,ac,ad,bc,bd,cd,abc,abd,abcd}`? | The Python [`itertools` page](http://docs.python.org/library/itertools.html#recipes) has exactly a `powerset` recipe for this:
```
def powerset(iterable):
"powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(... |
what's a good way to combinate through a set? | 1,482,308 | 15 | 2009-09-26T22:11:20Z | 1,482,320 | 11 | 2009-09-26T22:20:22Z | [
"python",
"factorial"
] | Given a set `{a,b,c,d}`, what's a good way to produce `{a,b,c,d,ab,ac,ad,bc,bd,cd,abc,abd,abcd}`? | Here is more code for a powerset. This is written from scratch:
```
>>> def powerset(s):
... x = len(s)
... for i in range(1 << x):
... print [s[j] for j in range(x) if (i & (1 << j))]
...
>>> powerset([4,5,6])
[]
[4]
[5]
[4, 5]
[6]
[4, 6]
[5, 6]
[4, 5, 6]
```
Mark Rushakoff's comment is applicable he... |
what's a good way to combinate through a set? | 1,482,308 | 15 | 2009-09-26T22:11:20Z | 1,482,322 | 10 | 2009-09-26T22:21:05Z | [
"python",
"factorial"
] | Given a set `{a,b,c,d}`, what's a good way to produce `{a,b,c,d,ab,ac,ad,bc,bd,cd,abc,abd,abcd}`? | If you're looking for a quick answer, I just searched "python power set" on google and came up with this: [Python Power Set Generator](http://blog.technomancy.org/2009/3/17/a-powerset-generator-in-python)
Here's a copy-paste from the code in that page:
```
def powerset(seq):
"""
Returns all the subsets of thi... |
`xrange(2**100)` -> OverflowError: long int too large to convert to int | 1,482,480 | 16 | 2009-09-27T00:28:45Z | 1,482,497 | 9 | 2009-09-27T00:38:54Z | [
"python",
"python-3.x",
"range",
"biginteger",
"xrange"
] | `xrange` function doesn't work for large integers:
```
>>> N = 10**100
>>> xrange(N)
Traceback (most recent call last):
...
OverflowError: long int too large to convert to int
>>> xrange(N, N+10)
Traceback (most recent call last):
...
OverflowError: long int too large to convert to int
```
Python 3.x:
```
>>> N = 10... | From the docs:
> Note
>
> xrange() is intended to be simple and fast. Implementations may impose restrictions to achieve this. The C implementation of Python restricts all arguments to native C longs (âshortâ Python integers), and also requires that the number of elements fit in a native C long. If a larger range ... |
`xrange(2**100)` -> OverflowError: long int too large to convert to int | 1,482,480 | 16 | 2009-09-27T00:28:45Z | 1,482,502 | 19 | 2009-09-27T00:41:55Z | [
"python",
"python-3.x",
"range",
"biginteger",
"xrange"
] | `xrange` function doesn't work for large integers:
```
>>> N = 10**100
>>> xrange(N)
Traceback (most recent call last):
...
OverflowError: long int too large to convert to int
>>> xrange(N, N+10)
Traceback (most recent call last):
...
OverflowError: long int too large to convert to int
```
Python 3.x:
```
>>> N = 10... | I believe there is no backport (Py 3's completely removed the int/long distinction, after all, but in 2.\* it's here to stay;-) but it's not hard to hack your own, e.g....:
```
import operator
def wowrange(start, stop, step=1):
if step == 0:
raise ValueError('step must be != 0')
elif step < 0:
proceed = o... |
`xrange(2**100)` -> OverflowError: long int too large to convert to int | 1,482,480 | 16 | 2009-09-27T00:28:45Z | 1,482,695 | 10 | 2009-09-27T03:05:09Z | [
"python",
"python-3.x",
"range",
"biginteger",
"xrange"
] | `xrange` function doesn't work for large integers:
```
>>> N = 10**100
>>> xrange(N)
Traceback (most recent call last):
...
OverflowError: long int too large to convert to int
>>> xrange(N, N+10)
Traceback (most recent call last):
...
OverflowError: long int too large to convert to int
```
Python 3.x:
```
>>> N = 10... | Okay, here's a go at a fuller reimplementation.
```
class MyXRange(object):
def __init__(self, a1, a2=None, step=1):
if step == 0:
raise ValueError("arg 3 must not be 0")
if a2 is None:
a1, a2 = 0, a1
if (a2 - a1) % step != 0:
a2 += step - (a2 - a1) % ste... |
How to make python window run as "Always On Top"? | 1,482,565 | 6 | 2009-09-27T01:25:09Z | 1,482,733 | 8 | 2009-09-27T03:39:33Z | [
"python",
"linux",
"gnome",
"pygame",
"always-on-top"
] | I am running a little program in python that launches a small window that needs to stay on top of all the other windows. I believe this is OS specific, how is it done in GNU-Linux with GNOME?
[**Update - Solution for Windows**]
Lovely, I think I got it working. I am using Python 2.5.4 with Pygame 1.9.1 in Eclipse on ... | The question is more like which windowing toolkit are you using ? PyGTK and similar educated googling gave me [this](http://library.gnome.org/devel/pygtk/stable/class-gtkwindow.html#method-gtkwindow--set-keep-above):
```
gtk.Window.set_keep_above
```
As mentioned previously it is upto the window manager to respect th... |
Python return without " ' " | 1,482,649 | 4 | 2009-09-27T02:37:26Z | 1,482,660 | 16 | 2009-09-27T02:42:29Z | [
"python"
] | In Python, how do you return a variable like:
```
function(x):
return x
```
Without the `'x'` (`'`) being around the `x`? | In the Python interactive prompt, if you return a string, it will be *displayed* with quotes around it, mainly so that you know it's a string.
If you just *print* the string, it will not be shown with quotes (unless the string *has* quotes in it).
```
>>> 1 # just a number, so no quotes
1
>>> "hi" # just a string, di... |
regex for character appearing at most once | 1,483,108 | 2 | 2009-09-27T08:34:58Z | 1,483,117 | 7 | 2009-09-27T08:37:37Z | [
"python",
"regex"
] | I want to check a string that contains the period, ".", at most once in python. | ```
[^.]*\.?[^.]*$
```
And be sure to `match`, don't `search`
```
>>> dot = re.compile("[^.]*\.[^.]*$")
>>> dot.match("fooooooooooooo.bar")
<_sre.SRE_Match object at 0xb7651838>
>>> dot.match("fooooooooooooo.bar.sad") is None
True
>>>
```
**Edit**:
If you consider only integers and decimals, it's even easier:
```
... |
How to except SyntaxError? | 1,483,343 | 2 | 2009-09-27T11:04:20Z | 1,483,450 | 9 | 2009-09-27T11:57:05Z | [
"python",
"exception-handling"
] | I would like to except the error the following code produces, but I don't know how.
```
from datetime import datetime
try:
date = datetime(2009, 12a, 31)
except:
print "error"
```
The code above is not printing `"error"`. That's what I would like to be able to do.
edit: The reason I would like to check for ... | command-line "parameters" are strings. if your code is:
```
datetime(2009, '12a', 31)
```
it won't produce `SyntaxError`. It raises `TypeError`.
All command-line parameters are needed to be cleaned up first, before use in your code. for example like this:
```
month = '12'
try:
month = int(month)
except ValueErr... |
How to print an error in Python? | 1,483,429 | 118 | 2009-09-27T11:48:19Z | 1,483,447 | 23 | 2009-09-27T11:56:30Z | [
"python",
"error-handling",
"exception-handling"
] | ```
try:
something here
except:
print 'the whatever error occurred.'
```
How can I print the error in my `except:` block? | In case you want to pass error strings, here is an example from [Errors and Exceptions](http://docs.python.org/tutorial/errors.html) (Python 2.6)
```
>>> try:
... raise Exception('spam', 'eggs')
... except Exception as inst:
... print type(inst) # the exception instance
... print inst.args # argument... |
How to print an error in Python? | 1,483,429 | 118 | 2009-09-27T11:48:19Z | 1,483,488 | 191 | 2009-09-27T12:19:27Z | [
"python",
"error-handling",
"exception-handling"
] | ```
try:
something here
except:
print 'the whatever error occurred.'
```
How can I print the error in my `except:` block? | ```
except Exception,e: print str(e)
``` |
How to print an error in Python? | 1,483,429 | 118 | 2009-09-27T11:48:19Z | 1,483,494 | 56 | 2009-09-27T12:25:48Z | [
"python",
"error-handling",
"exception-handling"
] | ```
try:
something here
except:
print 'the whatever error occurred.'
```
How can I print the error in my `except:` block? | [`traceback`](http://docs.python.org/library/traceback.html) module provides methods for formatting and printing exceptions and their tracebacks, e.g. this would print exception like the default handler does:
```
except: traceback.print_exc()
``` |
How to print an error in Python? | 1,483,429 | 118 | 2009-09-27T11:48:19Z | 1,483,909 | 74 | 2009-09-27T16:42:53Z | [
"python",
"error-handling",
"exception-handling"
] | ```
try:
something here
except:
print 'the whatever error occurred.'
```
How can I print the error in my `except:` block? | In **Python 2.6 or greater** it's a bit cleaner:
```
except Exception as e: print(e)
```
In older versions it's still quite readable:
```
except Exception, e: print e
``` |
Get offset of current buffer in vim (in particular, via python scripting) | 1,483,796 | 11 | 2009-09-27T15:36:59Z | 1,483,948 | 13 | 2009-09-27T16:59:18Z | [
"python",
"offset",
"vim"
] | i want to get the offset of
1. the current cursor position
2. the current selection range
in vim, beginning from the start of the file. I do this in python, so hints how to do it with vim's python scripting would be very helpful.
I have used vim.current.. before for doing scripting, but it uses lines and columns rat... | If your vim is compiled with the [`+byte_offset`](http://www.vim.org/htmldoc/various.html#+byte%5Foffset) option, then in a Python script after the usual `import vim`, you can use, e.g.:
```
vim.eval('line2byte(line("."))+col(".")')
```
to get the byte offset from start of file of the cursor position, and similarly f... |
Get offset of current buffer in vim (in particular, via python scripting) | 1,483,796 | 11 | 2009-09-27T15:36:59Z | 1,484,076 | 10 | 2009-09-27T18:01:40Z | [
"python",
"offset",
"vim"
] | i want to get the offset of
1. the current cursor position
2. the current selection range
in vim, beginning from the start of the file. I do this in python, so hints how to do it with vim's python scripting would be very helpful.
I have used vim.current.. before for doing scripting, but it uses lines and columns rat... | You may also want to look at the `statusline` setting. This will add the bye offset to the statusline:
```
set statusline+=%o
```
See `:h statusline`
Just be careful because the default statusline is blank, and by appending the %o to it, you loose all the defaults. |
Path to current file depends on how I execute the program | 1,483,827 | 5 | 2009-09-27T15:59:43Z | 1,483,832 | 8 | 2009-09-27T16:03:30Z | [
"python",
"path"
] | This is my Python program:
```
#!/usr/bin/env python
import os
BASE_PATH = os.path.dirname(__file__)
print BASE_PATH
```
If I run this using `python myfile.py` it prints an empty string. If I run it using `myfile.py`, it prints the correct path. Why is this? I'm using Windows Vista and Python 2.6.2. | It's just a harmless windows quirk; you can compensate by using `os.path.abspath(__file__)`, see [the docs](http://docs.python.org/library/os.path.html?highlight=os.path#os.path.abspath) |
Replace/delete field using sqlalchemy | 1,484,235 | 7 | 2009-09-27T19:17:05Z | 1,484,267 | 9 | 2009-09-27T19:39:37Z | [
"python",
"postgresql",
"replace",
"sqlalchemy"
] | Using postgres in python,
1. How do I replace all fields from the same column that match a specified value? For example, let's say I want to replace any fields that match "green" with "red" in the "Color" column.
2. How to delete all fields from the same column that match a specified value? For example, I'm trying to ... | Ad1. You need something like this:
```
session.query(Foo).filter_by(color = 'green').update({ 'color': 'red' })
session.commit()
```
Ad2. Similarly:
```
session.query(Foo).filter_by(color = 'green').delete()
session.commit()
```
You can find the querying documentation [here](http://www.sqlalchemy.org/docs/05/refere... |
How to pack a tkinter widget underneath an existing widget that has been packed to the left side? | 1,485,408 | 5 | 2009-09-28T04:25:57Z | 1,492,025 | 10 | 2009-09-29T11:40:58Z | [
"python",
"widget",
"tkinter",
"pack"
] | I'm attempting to write a basic Tkinter GUI that has a `Text` widget at the top, then a `Button` widget left aligned under it, then another `Text` widget underneath the button. The problem I'm having is, after packing the `Button` widget to the left, when I then go to pack the second `Text` widget, it puts it next to t... | There are generally two solutions to layout problems:
1. switch to using grid. It becomes real easy to do layouts like what you are trying to accomplish. Grid can solve probably 95% of all layout issues (it's amazing when you think about it -- Tk does with one manager what most toolkits need half a dozen to accomplish... |
Behaviour of increment and decrement operators in Python | 1,485,841 | 397 | 2009-09-28T07:33:19Z | 1,485,854 | 529 | 2009-09-28T07:39:36Z | [
"python",
"operators",
"increment",
"decrement"
] | I notice that a pre-increment/decrement operator can be applied on a variable (like `++count`). It compiles, but it does not actually change the value of the variable!
What is the behavior of the pre-increment/decrement operators (++/--) in Python?
Why does Python deviate from the behavior of these operators seen in ... | `++` is not an operator. It is two `+` operators. The `+` operator is the **identity** operator, which does nothing. (Clarification: the `+` and `-` unary operators only work on numbers, but I presume that you wouldn't expect a hypothetical `++` operator to work on strings.)
```
++count
```
Parses as
```
+(+count)
`... |
Behaviour of increment and decrement operators in Python | 1,485,841 | 397 | 2009-09-28T07:33:19Z | 1,486,086 | 251 | 2009-09-28T09:05:01Z | [
"python",
"operators",
"increment",
"decrement"
] | I notice that a pre-increment/decrement operator can be applied on a variable (like `++count`). It compiles, but it does not actually change the value of the variable!
What is the behavior of the pre-increment/decrement operators (++/--) in Python?
Why does Python deviate from the behavior of these operators seen in ... | When you want to increment or decrement, you typically want to do that on an integer. Like so:
```
b++
```
But in Python, integers are **immutable**. That is you can't change them. This is because the integer objects can be used under several names. Try this:
```
>>> b = 5
>>> a = 5
>>> id(a)
162334512
>>> id(b)
162... |
Behaviour of increment and decrement operators in Python | 1,485,841 | 397 | 2009-09-28T07:33:19Z | 11,210,198 | 30 | 2012-06-26T14:59:33Z | [
"python",
"operators",
"increment",
"decrement"
] | I notice that a pre-increment/decrement operator can be applied on a variable (like `++count`). It compiles, but it does not actually change the value of the variable!
What is the behavior of the pre-increment/decrement operators (++/--) in Python?
Why does Python deviate from the behavior of these operators seen in ... | While the others answers are correct in so far as they show what a mere `+` usually does (namely, leave the number as it is, if it is one), they are incomplete in so far as they don't explain what happens.
To be exact, `+x` evaluates to `x.__pos__()` and `++x` to `x.__pos__().__pos__()`.
I could imagine a VERY weird ... |
Python PIL cannot locate my "libjpeg" | 1,486,157 | 11 | 2009-09-28T09:29:42Z | 1,489,390 | 19 | 2009-09-28T21:09:49Z | [
"python",
"python-imaging-library"
] | I cannot use PIL because it cannot find my libjpeg!
First, I installed PIL default. And when I ran the `selftest.py`, it gave me:
```
IOError: decoder jpeg not available 1
items had failures: 1 of 57 in
selftest.testimage
***Test Failed*** 1 failures.
*** 1 tests of 57 failed.
```
Then, I followed instructions o... | There at least 3 header sets that you will want to install. 1 more if you want to deal with Tiff's
freetype, libjpeg, zlib all of which will be in the following packages on CentOS:
== 32 Bit:
zlib-devel.i386
libjpeg-devel.i386
freetype-devel.i386
== 64 Bit:
zlib-devel.x86\_64
libjpeg-devel.x86\_64
freetype-devel.x86... |
Mimic Python's strip() function in C | 1,488,372 | 3 | 2009-09-28T17:41:06Z | 1,488,403 | 12 | 2009-09-28T17:48:10Z | [
"python",
"c",
"string",
"fgets"
] | I started on a little toy project in C lately and have been scratching my head over the best way to mimic the strip() functionality that is part of the python string objects.
Reading around for fscanf or sscanf says that the string is processed upto the first whitespace that is encountered.
fgets doesn't help either ... | Python strings' `strip` method removes both trailing and leading whitespace. The two halves of the problem are very different when working on a C "string" (array of char, \0 terminated).
For trailing whitespace: set a pointer (or equivalently index) to the existing trailing \0. Keep decrementing the pointer until it h... |
Mimic Python's strip() function in C | 1,488,372 | 3 | 2009-09-28T17:41:06Z | 1,488,419 | 9 | 2009-09-28T17:51:07Z | [
"python",
"c",
"string",
"fgets"
] | I started on a little toy project in C lately and have been scratching my head over the best way to mimic the strip() functionality that is part of the python string objects.
Reading around for fscanf or sscanf says that the string is processed upto the first whitespace that is encountered.
fgets doesn't help either ... | There is no standard C implementation for a strip() or trim() function. That said, here's the one included in the Linux kernel:
```
char *strstrip(char *s)
{
size_t size;
char *end;
size = strlen(s);
if (!size)
return s;
end = s + size - 1;
while (end ... |
When is it advisable to use a ret_val variable? | 1,489,372 | 3 | 2009-09-28T21:06:45Z | 1,490,154 | 8 | 2009-09-29T01:35:54Z | [
"python",
"coding-style",
"return-value"
] | I have seen conflicting advice on whether the following code is better
```
def function():
ret_val = 0
if some_condition():
ret_val = 2
else:
ret_val = 3
return ret_val
```
or whether this is better:
```
def function():
if some_condition():
return 2
else:
retur... | Did we forget why "multiple exit points" was considered harmful in the first place? Back in the day (before widespread access to good exception handling and finally constructs, or managing objects like `auto_ptr` that do cleanup when they leave scope), this was the problem that haunted many multi-exit functions:
```
i... |
How do I find out my python path using python? | 1,489,599 | 174 | 2009-09-28T22:01:26Z | 1,489,625 | 118 | 2009-09-28T22:08:36Z | [
"python",
"python-module",
"pythonpath"
] | How do I find out which directories are listed in my systemâs `PYTHONPATH` variable, from within a Python script (or the interactive shell)? | `sys.path` might include items that aren't specifically in your `PYTHONPATH` environment variable. To query the variable directly, use:
```
import os
try:
user_paths = os.environ['PYTHONPATH'].split(os.pathsep)
except KeyError:
user_paths = []
``` |
How do I find out my python path using python? | 1,489,599 | 174 | 2009-09-28T22:01:26Z | 1,489,694 | 9 | 2009-09-28T22:27:31Z | [
"python",
"python-module",
"pythonpath"
] | How do I find out which directories are listed in my systemâs `PYTHONPATH` variable, from within a Python script (or the interactive shell)? | Can't seem to edit the other answer. Has a minor error in that it is Windows-only. The more generic solution is to use os.sep as below:
sys.path might include items that aren't specifically in your PYTHONPATH environment variable. To query the variable directly, use:
```
import os
os.environ['PYTHONPATH'].split(os.pa... |
How do I find out my python path using python? | 1,489,599 | 174 | 2009-09-28T22:01:26Z | 13,178,935 | 297 | 2012-11-01T14:15:11Z | [
"python",
"python-module",
"pythonpath"
] | How do I find out which directories are listed in my systemâs `PYTHONPATH` variable, from within a Python script (or the interactive shell)? | You would probably also want this:
```
import sys
print(sys.path)
```
Or as a one liner from the terminal:
```
python -c "import sys; print '\n'.join(sys.path)"
``` |
How to exit the entire application from a Python thread? | 1,489,669 | 24 | 2009-09-28T22:20:59Z | 1,489,838 | 16 | 2009-09-28T23:21:53Z | [
"python",
"multithreading"
] | How can I exit my entire Python application from one of its threads? sys.exit() only terminates the thread in which it is called, so that is no help.
I would not like to use an os.kill() solution, as this isn't very clean. | Short answer: use [`os._exit`](http://docs.python.org/library/os.html#os.%5Fexit).
Long answer with example:
I yanked and slightly modified a simple threading example from [a tutorial on DevShed](http://www.devshed.com/c/a/Python/Basic-Threading-in-Python/1/):
```
import threading, sys, os
theVar = 1
class MyThrea... |
How to exit the entire application from a Python thread? | 1,489,669 | 24 | 2009-09-28T22:20:59Z | 1,489,972 | 24 | 2009-09-29T00:17:28Z | [
"python",
"multithreading"
] | How can I exit my entire Python application from one of its threads? sys.exit() only terminates the thread in which it is called, so that is no help.
I would not like to use an os.kill() solution, as this isn't very clean. | If all your threads except the main ones are daemons, the best approach is generally [thread.interrupt\_main()](https://docs.python.org/2/library/thread.html#thread.interrupt_main) -- any thread can use it to raise a `KeyboardInterrupt` in the main thread, which can normally lead to reasonably clean exit from the main ... |
calling Objective C functions from Python? | 1,490,039 | 7 | 2009-09-29T00:47:28Z | 1,490,644 | 18 | 2009-09-29T04:58:47Z | [
"python",
"objective-c",
"osx"
] | Is there a way to dynamically call an Objective C function from Python?
For example, On the mac I would like to call this Objective C function
```
[NSSpeechSynthesizer availableVoices]
```
without having to precompile any special Python wrapper module. | As others have mentioned, PyObjC is the way to go. But, for completeness' sake, here's how you can do it with [ctypes](http://docs.python.org/library/ctypes.html), in case you need it to work on versions of OS X prior to 10.5 that do not have PyObjC installed:
```
import ctypes
import ctypes.util
# Need to do this to... |
Python Modules most worthwhile reading | 1,490,190 | 9 | 2009-09-29T01:48:51Z | 1,490,216 | 18 | 2009-09-29T01:59:29Z | [
"python"
] | I have been programming Python for a while and I have a very good understanding of its features, but I would like to improve my coding style. I think reading the source code of the Python Modules would be a good idea. Can anyone recommend any ones in particular?
Related Threads:
* [Beginner looking for beautiful and ... | [Queue.py](http://svn.python.org/view/python/trunk/Lib/Queue.py?revision=70405&view=markup) shows you how to make a class thread-safe, and the proper use of the [Template Method](http://en.wikipedia.org/wiki/Template%5Fmethod%5Fpattern) design pattern.
[sched.py](http://svn.python.org/view/python/trunk/Lib/sched.py?re... |
Python Regex "object has no attribute" | 1,491,277 | 6 | 2009-09-29T08:32:01Z | 1,491,439 | 15 | 2009-09-29T09:13:49Z | [
"python",
"regex"
] | I've been putting together a list of pages that we need to update with new content (we're switching media formats). In the process I'm cataloging pages that correctly have the new content.
Here's the general idea of what I'm doing:
1. Iterate through a file structure and get a list of files
2. For each file read to a... | Your exception means that urla has a value of None. Since urla's value is determined by the re.search call, it follows that re.search returns None. And this happens when the string doesn't match the pattern.
So basically you should use:
```
urla = re.search(pattern2, match)
if urla is not None:
print filename, ur... |
Telnet automation / scripting | 1,491,494 | 5 | 2009-09-29T09:29:42Z | 1,491,516 | 15 | 2009-09-29T09:33:54Z | [
"python",
"windows",
"scripting",
"automation",
"telnet"
] | I have already checked [This Question](http://stackoverflow.com/questions/709801/creating-a-script-for-a-telnet-session) but could not find what i'm looking for. I am running Windows (the client), and the server is a legacy mainframe type server.
Basically I need to write a script, python code or whatever, to send som... | There's a [python library for telnet](http://docs.python.org/library/telnetlib.html) connections that reads and writes from/to a telnet connection.
Check the link. It has some basic examples of what you are looking for.
Here's an example from the link:
```
import getpass
import sys
import telnetlib
HOST = "localhos... |
Download multiple pages concurrently? | 1,491,993 | 2 | 2009-09-29T11:35:11Z | 1,492,076 | 9 | 2009-09-29T11:52:32Z | [
"python",
"concurrent-processing"
] | I'd like to write a script in Python that can grab url's from a database, and download web pages concurrently to speed things instead of waiting for each page to download one after the other.
According to [this thread](http://stackoverflow.com/questions/1155404/python-accessing-multiple-webpages-at-once), Python doesn... | Don't worry about GIL. In your case it doesn't matter.
Easiest way to do what you want is to create thread pool, using *threading* module and one of thread pool implementations from [ASPN](http://code.activestate.com/recipes/langs/python/tags/pool/). Each thread from that pool can use *httplib* to download your web pa... |
Download multiple pages concurrently? | 1,491,993 | 2 | 2009-09-29T11:35:11Z | 1,492,194 | 7 | 2009-09-29T12:17:17Z | [
"python",
"concurrent-processing"
] | I'd like to write a script in Python that can grab url's from a database, and download web pages concurrently to speed things instead of waiting for each page to download one after the other.
According to [this thread](http://stackoverflow.com/questions/1155404/python-accessing-multiple-webpages-at-once), Python doesn... | GIL prevents you from effectively doing processor load balancing with threads. As this is not processor loads balancing but preventing one IO wait from stopping the whole download, the GIL is not relevant here. \*)
So all you need to do is create several processes that download at the same time. You can do that with t... |
Cannot access django app through ip address while accessing it through localhost | 1,493,479 | 13 | 2009-09-29T16:00:31Z | 1,493,598 | 47 | 2009-09-29T16:22:37Z | [
"python",
"django",
"networking"
] | I have a django app on my local computer. I can access the application from a browser by using the url: <http://localhost:8000/myapp/>
But I cannot access the application by using the ip of the host computer: <http://193.140.209.49:8000/myapp/> I get a 404 error.
What should I do? Any suggestions? | I assume you're using the development server. If so, then you need to specifically bind to your external IP for the server to be available there. Try this command:
```
./manage.py runserver 193.140.209.49:8000
``` |
Django - accessing the RequestContext from within a custom filter | 1,493,874 | 14 | 2009-09-29T17:18:29Z | 1,494,009 | 7 | 2009-09-29T17:45:22Z | [
"python",
"django",
"django-templates"
] | I've got a filter `currency`, which takes a value in USD and converts it to a currency (either USD or GBP). The currency to convert to is stored in the session, but filters don't take `RequestContext`, so I can't grab it straight from there.
Is there a better way than passing the relevant session element into the temp... | If you create a template tag instead of a filter, you are given the context to work with (which contains the request). <http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-tags> |
Is there any Python XML parser that was designed with humans in mind? | 1,493,899 | 23 | 2009-09-29T17:22:34Z | 1,493,970 | 22 | 2009-09-29T17:35:42Z | [
"python",
"xml",
"user-friendly"
] | I like Python, but I don't want to write 10 lines just to get an attribute from an element. Maybe it's just me, but `minidom` isn't that `mini`. The code I have to write in order to parse something using it looks a lot like Java code.
Is there something that is more `user-friendly` ? Something with overloaded operator... | You should take a look at [ElementTree](http://effbot.org/zone/element-index.htm). It's not doing exactly what you want but it's a lot better then minidom. If I remember correctly, starting from python 2.4, it's included in the standard libraries. For more speed use cElementTree. For more more speed (and more features)... |
How to define [] for class in Python? | 1,494,146 | 3 | 2009-09-29T18:22:17Z | 1,494,160 | 11 | 2009-09-29T18:25:51Z | [
"python"
] | I feel like this question has already been asked and answered, yet I couldn't find anything on-topic, so excuse me if it is so. I want to define the behaviour of [] brackets when applied to class, similar to `def []=()` construct in ruby, so that calling Python `obj['foo']` would actually call some `[](self, what)` met... | It's all in the docs: [`__getitem__`](http://docs.python.org/reference/datamodel.html#object.%5F%5Fgetitem%5F%5F). |
How to define [] for class in Python? | 1,494,146 | 3 | 2009-09-29T18:22:17Z | 1,494,161 | 7 | 2009-09-29T18:26:39Z | [
"python"
] | I feel like this question has already been asked and answered, yet I couldn't find anything on-topic, so excuse me if it is so. I want to define the behaviour of [] brackets when applied to class, similar to `def []=()` construct in ruby, so that calling Python `obj['foo']` would actually call some `[](self, what)` met... | This is done with `__getitem___` in Python.
Here is a list of all the operators:
<http://docs.python.org/library/operator.html> |
asn.1 parser in C/Python | 1,494,372 | 10 | 2009-09-29T19:06:56Z | 3,006,715 | 11 | 2010-06-09T14:20:12Z | [
"python",
"c",
"parsing",
"asn.1"
] | I am looking for a solution to parse asn.1 spec files and generate a decoder from those.
Ideally I would like to work with Python modules, but if nothing is available I would use C/C++ libraries and interface them with Python with the plethora of solutions out there.
In the past I have been using pyasn1 and building ... | I wrote such parser a few years ago. It generates python classes for pyasn1 library. I used in on ericsson doc to make parser for their CDRs.
I'll try posting the code here now.
```
import sys
from pyparsing import *
OpenBracket = Regex("[({]").suppress()
CloseBracket = Regex("[)}]").suppress()
def Enclose(val):
... |
General Command pattern and Command Dispatch pattern in Python | 1,494,442 | 19 | 2009-09-29T19:23:23Z | 1,494,532 | 47 | 2009-09-29T19:44:04Z | [
"python",
"design-patterns",
"oop"
] | I was looking for a *Command* pattern implementation in Python...
(According to [Wikipedia](http://en.wikipedia.org/wiki/Command%5Fpattern),
> the command pattern is a design
> pattern in which an object is used to
> represent and encapsulate all the
> information needed to call a method at
> a later time.
)
The onl... | The simplest command pattern is already built into Python, simply use a callable:
```
def greet(who):
print "Hello %s" % who
greet_command = lambda: greet("World")
# pass the callable around, and invoke it later
greet_command()
```
The command pattern as an object oriented design pattern makes more sense if your... |
Are Python's bools passed by value? | 1,494,696 | 5 | 2009-09-29T20:17:19Z | 1,494,728 | 12 | 2009-09-29T20:23:48Z | [
"python",
"boolean",
"pass-by-value"
] | I sent a reference to a bool object, and I modified it within a method. After the method finished it's execution, the value of the bool outside the method was unchanged.
This leads me to believe that Python's bools are passed by value. Is that true? What other Python types behave that way? | Python variables are not "references" in the C++ sense. Rather, they are simply local names bound to an object at some arbitrary location in memory. If that object is itself mutable, changes to it will be visible in other scopes that have bound a name to the object. Many primitive types (including `bool`, `int`, `str`,... |
Is there any python library for parsing dates and times from a natural language? | 1,495,487 | 26 | 2009-09-29T23:43:41Z | 1,495,548 | 34 | 2009-09-30T00:06:17Z | [
"python",
"parsing"
] | What I'm looking for is something that can translate 'tomorrow at 6am' or 'next moday at noon' to the appropriate datetime objects. | [parsedatetime](https://github.com/bear/parsedatetime) - *Python module that is able to parse 'human readable' date/time expressions.*
```
#!/usr/bin/env python
from datetime import datetime
import parsedatetime as pdt # $ pip install parsedatetime
cal = pdt.Calendar()
now = datetime.now()
print("now: %s" % now)
for ... |
Is there any python library for parsing dates and times from a natural language? | 1,495,487 | 26 | 2009-09-29T23:43:41Z | 1,496,032 | 10 | 2009-09-30T03:48:08Z | [
"python",
"parsing"
] | What I'm looking for is something that can translate 'tomorrow at 6am' or 'next moday at noon' to the appropriate datetime objects. | See what you think of [this example](http://pyparsing.wikispaces.com/UnderDevelopment#toc0) from the pyparsing wiki. It handles the following test cases:
```
today
tomorrow
yesterday
in a couple of days
a couple of days from now
a couple of days from today
in a day
3 days ago
3 days from now
a day ago
now
10 minutes a... |
Combining Dictionaries Of Lists In Python | 1,495,510 | 10 | 2009-09-29T23:54:01Z | 1,495,821 | 9 | 2009-09-30T02:17:58Z | [
"python",
"list",
"dictionary"
] | I have a very large collection of (p, q) tuples that I would like to convert into a dictionary of lists where the first item in each tuple is a key that indexes a list that contains q.
Example:
```
Original List: (1, 2), (1, 3), (2, 3)
Resultant Dictionary: {1:[2, 3], 2:[3]}
```
Furthermore, I would like to effici... | If the list of tuples is sorted, `itertools.groupby`, as suggested by @gnibbler, is not a bad alternative to `defaultdict`, but it needs to be used differently than he suggested:
```
import itertools
import operator
def lot_to_dict(lot):
key = operator.itemgetter(0)
# if lot's not sorted, you also need...:
# lo... |
How to download any(!) webpage with correct charset in python? | 1,495,627 | 28 | 2009-09-30T00:41:59Z | 1,495,631 | 13 | 2009-09-30T00:44:15Z | [
"python",
"character-encoding",
"screen-scraping",
"urllib2",
"urllib"
] | # Problem
**When screen-scraping a webpage using python one has to know the character encoding of the page.** If you get the character encoding wrong than your output will be messed up.
People usually use some rudimentary technique to detect the encoding. They either use the charset from the header or the charset def... | Use the [Universal Encoding Detector](http://pypi.python.org/pypi/chardet):
```
>>> import chardet
>>> chardet.detect(urlread("http://google.cn/"))
{'encoding': 'GB2312', 'confidence': 0.99}
```
The other option would be to just use wget:
```
import os
h = os.popen('wget -q -O foo1.txt http://foo.html')
h.clos... |
How to download any(!) webpage with correct charset in python? | 1,495,627 | 28 | 2009-09-30T00:41:59Z | 1,495,675 | 32 | 2009-09-30T01:04:36Z | [
"python",
"character-encoding",
"screen-scraping",
"urllib2",
"urllib"
] | # Problem
**When screen-scraping a webpage using python one has to know the character encoding of the page.** If you get the character encoding wrong than your output will be messed up.
People usually use some rudimentary technique to detect the encoding. They either use the charset from the header or the charset def... | When you download a file with urllib or urllib2, you can find out whether a charset header was transmitted:
```
fp = urllib2.urlopen(request)
charset = fp.headers.getparam('charset')
```
You can use BeautifulSoup to locate a meta element in the HTML:
```
soup = BeatifulSoup.BeautifulSoup(data)
meta = soup.findAll('m... |
How to define a class in Python | 1,495,666 | 40 | 2009-09-30T01:02:16Z | 1,495,680 | 38 | 2009-09-30T01:06:33Z | [
"python"
] | Quite simple, I'm learning python and I can't find a reference that tells me how to write the following:
```
public class Team {
private String name;
private String logo;
private int members;
public Team(){}
// getters/setters
}
```
Later:
```
Team team = new Team();
team.setName( "Oscar... | ```
class Team:
def __init__(self):
self.name = None
self.logo = None
self.members = 0
```
In Python, you typically don't write getters and setters, unless you really have a non-trivial implementation for them (at which point you use property descriptors). |
How to define a class in Python | 1,495,666 | 40 | 2009-09-30T01:02:16Z | 1,495,740 | 87 | 2009-09-30T01:35:29Z | [
"python"
] | Quite simple, I'm learning python and I can't find a reference that tells me how to write the following:
```
public class Team {
private String name;
private String logo;
private int members;
public Team(){}
// getters/setters
}
```
Later:
```
Team team = new Team();
team.setName( "Oscar... | Here is what I would recommend:
```
class Team(object):
def __init__(self, name=None, logo=None, members=0):
self.name = name
self.logo = logo
self.members = members
team = Team("Oscar", "http://...", 10)
team2 = Team()
team2.name = "Fred"
team3 = Team(name="Joe", members=10)
```
Some n... |
Passing a list of kwargs? | 1,496,346 | 43 | 2009-09-30T06:08:33Z | 1,496,355 | 75 | 2009-09-30T06:11:41Z | [
"python",
"kwargs"
] | Can I pass a list of kwargs to a method for brevity? This is what i'm attempting to do:
```
def method(**kwargs):
#do something
keywords = (keyword1 = 'foo', keyword2 = 'bar')
method(keywords)
``` | Yes. You do it like this:
```
def method(**kwargs):
print kwargs
keywords = {'keyword1': 'foo', 'keyword2': 'bar'}
method(keyword1='foo', keyword2='bar')
method(**keywords)
```
Running this in Python confirms these produce identical results:
```
{'keyword2': 'bar', 'keyword1': 'foo'}
{'keyword2': 'bar', 'keyword1... |
How to treat the first line of a file differently in Python? | 1,496,456 | 7 | 2009-09-30T06:46:59Z | 1,496,477 | 12 | 2009-09-30T06:52:33Z | [
"python",
"file",
"iteration"
] | I often need to process large text files containing headers in the first line. The headers are often treated differently to the body of the file, or my processing of the body is dependent on the headers. Either way I need to treat the first line as a special case.
I could use simple line iteration and set a flag:
```
... | You could:
```
processHeader(f.readline())
for line in f:
processBody(line)
``` |
How to treat the first line of a file differently in Python? | 1,496,456 | 7 | 2009-09-30T06:46:59Z | 1,496,491 | 8 | 2009-09-30T06:56:41Z | [
"python",
"file",
"iteration"
] | I often need to process large text files containing headers in the first line. The headers are often treated differently to the body of the file, or my processing of the body is dependent on the headers. Either way I need to treat the first line as a special case.
I could use simple line iteration and set a flag:
```
... | ```
f = file("test")
processHeader(f.next()) #or next(f) for py3
for line in f:
processBody(line)
```
This works.
Edit:
Changed `.__next__` to `next` (they *are* equivalent, but I suppose next is more concise).
Regaring `file` vs `open`, `file` just seems more clear to me, therefore I will continue to prefer it... |
question related to reverse function and kwargs | 1,497,258 | 4 | 2009-09-30T10:27:07Z | 1,497,331 | 9 | 2009-09-30T10:41:25Z | [
"python",
"django"
] | To reverse lookup an url by means of name or View\_name we will use reverse function in the views like below
```
reverse("calendarviewurl2", kwargs={"year":theyear,"month":themonth})
```
and reverse function signature is as follows
<http://code.djangoproject.com/browser/django/trunk/django/core/urlresolvers.py>
```... | Didn't you look at the [signature](http://code.djangoproject.com/browser/django/trunk/django/core/urlresolvers.py#L305),
```
def reverse(viewname, urlconf=None, args=None, kwargs=None,
prefix=None, current_app=None):
```
takes no `**kwargs` at all.
```
kwargs={"year":2009,"month":9}
reverse("n... |
How to make unique short URL with Python? | 1,497,504 | 26 | 2009-09-30T11:16:10Z | 1,497,541 | 14 | 2009-09-30T11:24:40Z | [
"python",
"url",
"uuid",
"tinyurl",
"short-url"
] | How can I make unique URL in Python a la <http://imgur.com/gM19g> or <http://tumblr.com/xzh3bi25y>
When using uuid from python I get a very large one. I want something shorter for URLs. | I'm not sure most URL shorteners use a random string. My impression is they write the URL to a database, then use the integer ID of the new record as the short URL, encoded base 36 or 62 (letters+digits).
Python code to convert an int to a string in arbitrary bases is [here](http://code.activestate.com/recipes/65212/)... |
How to make unique short URL with Python? | 1,497,504 | 26 | 2009-09-30T11:16:10Z | 1,497,573 | 22 | 2009-09-30T11:32:51Z | [
"python",
"url",
"uuid",
"tinyurl",
"short-url"
] | How can I make unique URL in Python a la <http://imgur.com/gM19g> or <http://tumblr.com/xzh3bi25y>
When using uuid from python I get a very large one. I want something shorter for URLs. | **Edit**: Here, I wrote a module for you. Use it. <http://code.activestate.com/recipes/576918/>
---
Counting up from 1 will guarantee short, unique URLS. /1, /2, /3 ... etc.
Adding uppercase and lowercase letters to your alphabet will give URLs like those in your question. And you're just counting in base-62 instead... |
Is it OK if objects from different classes interact with each other? | 1,498,009 | 4 | 2009-09-30T13:11:04Z | 1,498,030 | 7 | 2009-09-30T13:13:29Z | [
"python",
"oop"
] | I just started to use the object oriented programming in Python. I wander if it is OK if I create a method of a class which use objects from another class. In other words, when I call a method of the first class I give an object from the second class as one of the arguments. And then, the considered methods (of the fir... | If you're talking about passing an instance of one object to the method of a another one, then yes of course it's allowed! And it's considered fine practice.
If you want to know more about good object oriented coding, may I offer some suggested readings:
*Design Patterns: Elements of Reusable Object-Oriented Software... |
Performance of Python worth the cost? | 1,498,155 | 5 | 2009-09-30T13:32:45Z | 1,498,176 | 11 | 2009-09-30T13:36:28Z | [
"python",
"c",
"embedded",
"fuzzy-logic"
] | I'm looking at implementing a fuzzy logic controller based on either PyFuzzy (Python) or FFLL (C++) libraries.
I'd prefer to work with python but am unsure if the performance will be acceptable in the embedded environment it will work in (either ARM or embedded x86 proc both ~64Mbs of RAM).
The main concern is that r... | Python is very slow at handling large amounts of non-string data. For some operations, you may see that it is 1000 times slower than C/C++, so yes, you should investigate into this and do necessary benchmarks before you make time-critical algorithms in Python.
However, you can extend python with modules in C/C++ code,... |
Performance of Python worth the cost? | 1,498,155 | 5 | 2009-09-30T13:32:45Z | 1,498,214 | 35 | 2009-09-30T13:44:01Z | [
"python",
"c",
"embedded",
"fuzzy-logic"
] | I'm looking at implementing a fuzzy logic controller based on either PyFuzzy (Python) or FFLL (C++) libraries.
I'd prefer to work with python but am unsure if the performance will be acceptable in the embedded environment it will work in (either ARM or embedded x86 proc both ~64Mbs of RAM).
The main concern is that r... | In general, you shouldn't obsess over performance until you've actually seen it become a problem. Since we don't know the details of your app, we can't say how it'd perform if implemented in Python. And since you haven't implemented it yet, neither can you.
Implement the version you're most comfortable with, and can i... |
Django: form values not updating when model updates | 1,498,763 | 4 | 2009-09-30T15:14:17Z | 1,499,297 | 8 | 2009-09-30T16:37:14Z | [
"python",
"django",
"django-forms"
] | I am creating a form that uses MultipleChoiceField. The values for this field are derived from another model. This method works fine, however, I am noticing (on the production server) that when I add a new item to the model in question (NoticeType), the form does not dynamically update. I have to restart the server for... | Although mherren is right that you can fix this problem by defining your choices in the `__init__` method, there is an easier way: use the `ModelMultipleChoiceField` which is specifically designed to take a queryset, and updates dynamically.
```
class EditUserProfileForm(forms.Form):
notifications = forms. ModelMu... |
How to get the PATH separator in Python? | 1,499,019 | 106 | 2009-09-30T15:51:47Z | 1,499,033 | 163 | 2009-09-30T15:53:44Z | [
"python",
"operating-system"
] | When multiple directories need to be concatenated, as in an executable search path, there is an os-dependent separator character. For Windows it's `';'`, for Linux it's `':'`. Is there a way in Python to get which character to split on?
In the discussions to this question <http://stackoverflow.com/questions/1489599/ho... | [`os.pathsep`](http://docs.python.org/library/os.html#os.pathsep) |
How to get the PATH separator in Python? | 1,499,019 | 106 | 2009-09-30T15:51:47Z | 1,499,034 | 25 | 2009-09-30T15:53:53Z | [
"python",
"operating-system"
] | When multiple directories need to be concatenated, as in an executable search path, there is an os-dependent separator character. For Windows it's `';'`, for Linux it's `':'`. Is there a way in Python to get which character to split on?
In the discussions to this question <http://stackoverflow.com/questions/1489599/ho... | It is os.pathsep |
Python - importing package classes into console global namespace | 1,499,119 | 8 | 2009-09-30T16:04:52Z | 1,499,164 | 14 | 2009-09-30T16:13:14Z | [
"python",
"import",
"console",
"namespaces",
"global"
] | I'm having a spot of trouble getting my python classes to work within the python console. I want to automatically import all of my classes into the global namespace so I can use them without any prefix.module.names.
Here's what I've got so far...
```
projectname/
|-__init__.py
|
|-main_stuff/
|-__init__.py
|-main... | You want to use a different form of import.
In `projectname/main_stuff/__init__.py`:
```
from other_stuff import *
__all__ = ["main1", "main2", "main3"]
```
When you use a statement like this:
```
import foo
```
You are defining the name foo in the current module. Then you can use `foo.something` to get at the stu... |
Running python script as another user | 1,499,268 | 8 | 2009-09-30T16:31:05Z | 1,499,386 | 11 | 2009-09-30T16:53:11Z | [
"python",
"linux"
] | On a Linux box I want to run a Python script as another user.
I've already made a wrapper program in C++ that calls the script, since I've realized that the ownership of running the script is decided by the ownership of the python interpreter. After that I change the C++ program to a different user and run the C++ pro... | You can set the user with os.setuid(), and you can get the uid with pwd.
Like so:
```
>>> import pwd, os
>>> uid = pwd.getpwnam('root')[2]
>>> os.setuid(uid)
```
Obviously this only works if the user or executable has the permission to do so. Exactly how to set that up I don't know. Obviously it works if you are root... |
How to programmatically get SVN revision number? | 1,499,811 | 7 | 2009-09-30T18:17:47Z | 1,501,219 | 13 | 2009-09-30T23:37:06Z | [
"php",
"python",
"svn"
] | [Like this question](http://stackoverflow.com/questions/681770/how-to-programmatically-get-svn-revision-description-and-author-in-c), but without the need to actually query the SVN server. This is a web-based project, so I figure I'll just use the repository as the public view (unless someone can advise me why this is ... | Subversion includes the [svnversion](http://svnbook.red-bean.com/en/1.7/svn.ref.svnversion.re.html) tool for exactly this purpose. A working copy may actually have local modifications, or may consist of a mix of revisions. `svnversion` knows how to handle that; see the examples in the linked documentation.
You can inv... |
Python/WebApp Google App Engine - testing for user/pass in the headers | 1,499,832 | 4 | 2009-09-30T18:20:00Z | 1,500,515 | 7 | 2009-09-30T20:36:30Z | [
"python",
"google-app-engine",
"web-applications"
] | When you call a web service like this:
```
username = 'test12'
password = 'test34'
client = httplib2.Http(".cache")
client.add_credentials(username,password)
URL = "http://localhost:8080/wyWebServiceTest"
response, content = client.request(URL)
```
How do you get the username/password into variabl... | I haven't tested this code (insert smiley) but I think this is the sort of thing you need. Basically your credentials won't be in the header if your server hasn't bounced a 401 back to your client (the client needs to know the realm to know what credentials to provide).
```
class MYREALM_securepage(webapp.RequestHandl... |
What is the right way to override the copy/deepcopy operations on an object in Python? | 1,500,718 | 32 | 2009-09-30T21:18:45Z | 1,500,887 | 26 | 2009-09-30T21:58:58Z | [
"python"
] | So just to establish, I feel like I understand the difference between copy vs. deepcopy in the copy module and I've used copy.copy and copy.deepcopy before successfully, but this is the first time I've actually gone about overloading the \_\_copy\_\_ and \_\_deepcopy\_\_ methods. I've already Googled around and looked ... | The recommendations for customizing are at the very end of the [docs page](http://docs.python.org/library/copy.html):
> Classes can use the same interfaces to
> control copying that they use to
> control pickling. See the description
> of module pickle for information on
> these methods. The copy module does
> not use... |
What is the right way to override the copy/deepcopy operations on an object in Python? | 1,500,718 | 32 | 2009-09-30T21:18:45Z | 15,774,013 | 24 | 2013-04-02T20:46:44Z | [
"python"
] | So just to establish, I feel like I understand the difference between copy vs. deepcopy in the copy module and I've used copy.copy and copy.deepcopy before successfully, but this is the first time I've actually gone about overloading the \_\_copy\_\_ and \_\_deepcopy\_\_ methods. I've already Googled around and looked ... | Putting together Alex Martelli's answer and Rob Young's comment you get the following code:
```
from copy import copy, deepcopy
class A(object):
def __init__(self):
print 'init'
self.v = 10
self.z = [2,3,4]
def __copy__(self):
cls = self.__class__
result = cls.__new__(... |
What's the most pythonic way to ensure that all elements of a list are different? | 1,501,118 | 8 | 2009-09-30T23:07:02Z | 1,501,133 | 26 | 2009-09-30T23:09:26Z | [
"python",
"list",
"unique"
] | I have a list in Python that I generate as part of the program. I have a strong assumption that these are all different, and I check this with an assertion.
This is the way I do it now:
If there are two elements:
```
try:
assert(x[0] != x[1])
except:
print debug_info
raise Exception("throw to caller")
``... | Maybe something like this:
```
if len(x) == len(set(x)):
print "all elements are unique"
else:
print "elements are not unique"
``` |
What's the most pythonic way to ensure that all elements of a list are different? | 1,501,118 | 8 | 2009-09-30T23:07:02Z | 1,501,141 | 7 | 2009-09-30T23:11:09Z | [
"python",
"list",
"unique"
] | I have a list in Python that I generate as part of the program. I have a strong assumption that these are all different, and I check this with an assertion.
This is the way I do it now:
If there are two elements:
```
try:
assert(x[0] != x[1])
except:
print debug_info
raise Exception("throw to caller")
``... | How about this:
```
if len(x) != len(set(x)):
raise Exception("throw to caller")
```
This assumes that elements in `x` are hashable. |
What's the most pythonic way to ensure that all elements of a list are different? | 1,501,118 | 8 | 2009-09-30T23:07:02Z | 1,501,503 | 18 | 2009-10-01T01:45:12Z | [
"python",
"list",
"unique"
] | I have a list in Python that I generate as part of the program. I have a strong assumption that these are all different, and I check this with an assertion.
This is the way I do it now:
If there are two elements:
```
try:
assert(x[0] != x[1])
except:
print debug_info
raise Exception("throw to caller")
``... | The most popular answers are O(N) (good!-) but, as @Paul and @Mark point out, they require the list's items to be hashable. Both @Paul and @Mark's proposed approaches for unhashable items are general but take O(N squared) -- i.e., a lot.
If your list's items are not hashable but *are* comparable, you can do better... ... |
Log output of multiprocessing.Process | 1,501,651 | 43 | 2009-10-01T02:44:03Z | 1,501,756 | 9 | 2009-10-01T03:29:57Z | [
"python",
"logging",
"concurrency",
"multiprocessing"
] | Is there a way to log the stdout output from a given Process when using the multiprocessing.Process class in python? | You can set `sys.stdout = Logger()` where `Logger` is a class whose `write` method (immediately, or accumulating until a `\n` is detected) calls `logging.info` (or any other way you want to log). [An example of this in action.](https://github.com/jdloft/multiprocess-logging/blob/master/main.py)
I'm not sure what you m... |
Log output of multiprocessing.Process | 1,501,651 | 43 | 2009-10-01T02:44:03Z | 1,501,757 | 32 | 2009-10-01T03:30:09Z | [
"python",
"logging",
"concurrency",
"multiprocessing"
] | Is there a way to log the stdout output from a given Process when using the multiprocessing.Process class in python? | The easiest way might be to just override `sys.stdout`. Slightly modifying an example from [the multiprocessing manual](http://docs.python.org/library/multiprocessing.html#the-process-class):
```
from multiprocessing import Process
import os
import sys
def info(title):
print title
print 'module name:', __name... |
Log output of multiprocessing.Process | 1,501,651 | 43 | 2009-10-01T02:44:03Z | 23,937,468 | 7 | 2014-05-29T15:51:01Z | [
"python",
"logging",
"concurrency",
"multiprocessing"
] | Is there a way to log the stdout output from a given Process when using the multiprocessing.Process class in python? | There are only two things I would add to @Mark Rushakoff answer. When debugging, I found it really useful to change the `buffering` parameter of my `open()` calls to 0.
```
sys.stdout = open(str(os.getpid()) + ".out", "a", buffering=0)
```
Otherwise, **madness**, because when `tail -f`ing the output file the results ... |
Parsing out data using BeautifulSoup in Python | 1,501,690 | 9 | 2009-10-01T02:59:32Z | 1,501,755 | 12 | 2009-10-01T03:29:56Z | [
"python",
"html",
"parsing",
"beautifulsoup"
] | I am attempting to use BeautifulSoup to parse through a DOM tree and extract the names of authors. Below is a snippet of HTML to show the structure of the code I'm going to scrape.
```
<html>
<body>
<div class="list-authors">
<span class="descriptor">Authors:</span>
<a href="/find/astro-ph/1/au:+Lin_D/0/1/0/all/0/1">... | just use findAll for the divs link you do for the links
for authordiv in soup.findAll('div', attrs={'class': 'list-authors'}): |
How to pick certain elements of x-tuple returned by a function? | 1,502,470 | 2 | 2009-10-01T07:47:46Z | 1,502,488 | 13 | 2009-10-01T07:52:38Z | [
"python",
"list",
"tuples",
"iterable-unpacking"
] | I am a newbie to Python. Consider the function `str.partition()` which returns a 3-tuple. If I am interested in only elements 0 and 2 of this tuple, what is the best way to pick only certain elements out of such a tuple?
I can currently do either:
```
# Introduces "part1" variable, which is useless
(part0, part1, par... | Underscore is often used as a name for stuff you do not need, so something like this would work:
```
part0, _, part2 = str.partition(' ')
```
In this particular case, you could do this, but it isn't a pretty solution:
```
part0, part2 = str.partition(' ')[::2]
```
A more esoteric solution:
```
from operator import... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.