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
What are some elegant ways to abstract out repetitive exception handling in python?
5,374,357
10
2011-03-21T06:06:42Z
5,374,745
18
2011-03-21T07:06:36Z
[ "python", "design", "exception-handling" ]
When handling exceptions in python, I find myself repeating code quite often. The basic pattern is something of the form: ``` try: action_here() except CommonException1: Action_always_taken_for_CommonException1() except CommonException2: Action_always_taken_for_CommonException2() except Exception: Default_acti...
This situation is one of the main use cases for context managers and the with statement: ``` from __future__ import with_statement # Needed in 2.5, but not in 2.6 or later from contextlib import contextmanager @contextmanager def handle_exceptions(): try: yield # Body of the with statement effectively ru...
ImportError: cannot import name Publisher
5,374,451
5
2011-03-21T06:20:33Z
5,900,028
8
2011-05-05T15:08:31Z
[ "python", "executable", "py2exe" ]
I created succesfully an executable version (Py2exe, Pyinstaller) of my application. When I try to run the app from .exe, I get an error as follows in the log file: `Traceback (most recent call last): File "CreateAS.pyw", line 8, in <module> ImportError: cannot import name Publisher` I am really stuck in this part. C...
I'm guessing that you are using a version of [wxPython](http://www.wxpython.org) that is `>= 2.8.11.0`? If so, the `wx.lib.pubsub` package has changed. [This page](http://wiki.wxpython.org/WxLibPubSub) describes the changes. There is also a thread on the [wxPython](http://www.wxpython.org) mailing list [here](http://gr...
How do I stop Tornado web server?
5,375,220
19
2011-03-21T08:16:56Z
8,774,273
17
2012-01-08T00:12:04Z
[ "python", "tornado" ]
I've been playing around a bit with the [Tornado web server](http://www.tornadoweb.org/) and have come to a point where I want to stop the web server (for example during unit testing). The following simple example [exists on the Tornado web page](http://www.tornadoweb.org/documentation#overview): ``` import tornado.io...
I just ran into this and found this issue myself, and using info from this thread came up with the following. I simply took my working stand alone Tornado code (copied from all the examples) and moved the actual starting code into a function. I then called the function as a threading thread. My case different as the th...
How do I stop Tornado web server?
5,375,220
19
2011-03-21T08:16:56Z
17,325,148
13
2013-06-26T16:07:06Z
[ "python", "tornado" ]
I've been playing around a bit with the [Tornado web server](http://www.tornadoweb.org/) and have come to a point where I want to stop the web server (for example during unit testing). The following simple example [exists on the Tornado web page](http://www.tornadoweb.org/documentation#overview): ``` import tornado.io...
Here is the solution how to stop Torando from another thread. Schildmeijer provided a good hint, but it took me a while to actually figure the final example that works. Please see below: ``` import threading import tornado.ioloop import tornado.web import time class MainHandler(tornado.web.RequestHandler): def ...
A decorator that profiles a method call and logs the profiling result
5,375,624
9
2011-03-21T09:11:57Z
5,375,728
7
2011-03-21T09:26:12Z
[ "python", "profiling", "decorator" ]
I want to create a decorator that profiles a method and logs the result. How can this be done?
The decorator would look something like: ``` import time import logging def profile(func): def wrap(*args, **kwargs): started_at = time.time() result = func(*args, **kwargs) logging.info(time.time() - started_at) return result return wrap @profile def foo(): pass ``` Any...
A decorator that profiles a method call and logs the profiling result
5,375,624
9
2011-03-21T09:11:57Z
5,376,616
43
2011-03-21T10:52:29Z
[ "python", "profiling", "decorator" ]
I want to create a decorator that profiles a method and logs the result. How can this be done?
If you want proper profiling instead of timing, you can use an undocumented feature of `cProfile` (from [this question](http://stackoverflow.com/questions/1584425/return-value-while-using-cprofile)): ``` import cProfile def profileit(func): def wrapper(*args, **kwargs): datafn = func.__name__ + ".profile"...
Attaching csv file to email in django
5,375,769
2
2011-03-21T09:29:23Z
5,376,241
7
2011-03-21T10:18:23Z
[ "python", "django" ]
I need to create a mail that should have a csv file as an attachment. How do I attach a csv file to a mail in django?
To attach files to emails sent by django, you'll have to create an [`EmailMessage`](http://docs.djangoproject.com/en/dev/topics/email/#emailmessage-objects) instance and attach the file using the `.attach()` method. For example, assuming you have the CSV content in `csv_data`: ``` email = EmailMessage('Subject', 'ema...
How can I do an "if run from ipython" test in Python?
5,376,837
16
2011-03-21T11:14:09Z
5,377,037
7
2011-03-21T11:31:54Z
[ "python", "ipython" ]
To ease debugging from Ipython, I include the following in the beginning of my scripts ``` from IPython.Debugger import Tracer debug = Tracer() ``` However, if I launch my script from the command line with ``` $ python myscript.py ``` I get an error related to Ipython. Is there a way to do the following ``` if run...
The Python way is to use exceptions. Like: ``` try: from IPython.Debugger import Tracer debug = Tracer() except ImportError: pass # or set "debug" to something else or whatever ```
How can I do an "if run from ipython" test in Python?
5,376,837
16
2011-03-21T11:14:09Z
5,377,051
28
2011-03-21T11:33:49Z
[ "python", "ipython" ]
To ease debugging from Ipython, I include the following in the beginning of my scripts ``` from IPython.Debugger import Tracer debug = Tracer() ``` However, if I launch my script from the command line with ``` $ python myscript.py ``` I get an error related to Ipython. Is there a way to do the following ``` if run...
This is probably the kind of thing you are looking for: ``` def run_from_ipython(): try: __IPYTHON__ return True except NameError: return False ```
Doing shell backquote in python?
5,377,229
4
2011-03-21T11:52:48Z
5,377,255
8
2011-03-21T11:55:34Z
[ "python" ]
I am translating bash scripts into python for some reasons. Python is more powerfull, nevertheless, it is much more harder to code simple bash code like this : ``` MYVAR = `grep -c myfile` ``` With python I have first to define a backquote function could be : ``` def backquote(cmd,noErrorCode=(0,),output=PIPE,errou...
In Python 2.7 or above, there is [`subprocess.check_output()`](http://docs.python.org/library/subprocess.html#subprocess.check_output) which basically does what you are after.
Profiling of a python function
5,377,795
2
2011-03-21T12:51:05Z
5,377,920
8
2011-03-21T13:01:11Z
[ "python", "profiling", "python-3.x" ]
Do you have any idea of how can I make this function more time-efficient? ``` def c(n): word = 32 #l = [] c = 0 for i in range(0, 2**word): #print(str(bin(i)))#.count('1') if str(bin(i)).count('1') == n: c = c + 1 print(c) if i == 2**28: pri...
You are counting how many 32-bit numbers have a given number of `1`s. This number is the [binomial coefficient](http://en.wikipedia.org/wiki/Binomial_coefficient) `32 choose bits`, and can be calculated with: ``` from math import factorial print factorial(32) // (factorial(bits) * factorial(32-bits)) ```
How do I exclude an inherited field in a form in Django?
5,378,169
6
2011-03-21T13:23:32Z
5,378,588
7
2011-03-21T13:55:01Z
[ "python", "django", "django-forms" ]
I have the following form and inherited form: ``` class UsuarioAdminForm(ModelForm): first_name = forms.CharField(label='Nombre', help_text = 'Nombre del usuario', required=True) last_name = forms.CharField(label='Apellidos', help_text = 'Apellidos del usuario', required=True) dni = ESIdentityCardNumberFi...
Maybe you could change the order of this lines: ``` def __init__(self, *args, **kwargs): super(UsuarioForm,self).__init__(*args, **kwargs) self.is_staff = None ``` You could also do: ``` def __init__(self, *args, **kwargs): super(UsuarioForm,self).__init__(*args, **kwargs) self.fields.pop('is...
Python: list to dictionary, multiple values per key
5,378,231
34
2011-03-21T13:28:47Z
5,378,250
35
2011-03-21T13:30:14Z
[ "python", "list", "dictionary", "type-conversion" ]
I have a Python list which holds pairs of key/value: ``` l=[ [1, 'A'], [1, 'B'], [2, 'C'] ] ``` I want to convert the list into a dictionary, where multiple values per key would be aggregated into a tuple: ``` { 1:('A', 'B'), 2:('C',) } ``` The iterative solution is trivial: ``` l=[ [1, 'A'], [1, 'B'], [2, 'C'] ] ...
``` from collections import defaultdict d1 = defaultdict(list) for k, v in l: d1[k].append(v) d = dict((k, tuple(v)) for k, v in d1.iteritems()) ``` `d` contains now `{1: ('A', 'B'), 2: ('C',)}` `d1` is a temporary defaultdict with lists as values, which will be converted to tuples in the last line. This way y...
Python: list to dictionary, multiple values per key
5,378,231
34
2011-03-21T13:28:47Z
14,946,804
8
2013-02-18T22:54:53Z
[ "python", "list", "dictionary", "type-conversion" ]
I have a Python list which holds pairs of key/value: ``` l=[ [1, 'A'], [1, 'B'], [2, 'C'] ] ``` I want to convert the list into a dictionary, where multiple values per key would be aggregated into a tuple: ``` { 1:('A', 'B'), 2:('C',) } ``` The iterative solution is trivial: ``` l=[ [1, 'A'], [1, 'B'], [2, 'C'] ] ...
This method is relatively efficient and quite compact: ``` reduce(lambda x, (k,v): x[k].append(v) or x, l, defaultdict(list)) ```
Any way to make {% extends '...' %} conditional? - Django
5,380,984
51
2011-03-21T16:58:37Z
5,381,015
56
2011-03-21T17:02:16Z
[ "python", "ajax", "django", "django-templates" ]
I would like to share a template between AJAX and regualr HTTP calls, the only difference is that one template needs to be served with the base.html html, the other one without. Any idea?
Use a variable. ``` {% extends base_template %} ``` and in your view, set it to "base.html" in your view, or a new "ajax.html" file which just provides the block and nothing else.
Any way to make {% extends '...' %} conditional? - Django
5,380,984
51
2011-03-21T16:58:37Z
7,817,990
94
2011-10-19T07:38:16Z
[ "python", "ajax", "django", "django-templates" ]
I would like to share a template between AJAX and regualr HTTP calls, the only difference is that one template needs to be served with the base.html html, the other one without. Any idea?
The other answers require you to pass an additional context variable. But as long as you can access the request object, there is no need: ``` {% extends request.is_ajax|yesno:"app/base_ajax.html,app/base.html" %} ``` I found this to be much more convenient.
Any way to make {% extends '...' %} conditional? - Django
5,380,984
51
2011-03-21T16:58:37Z
14,115,934
14
2013-01-02T01:27:56Z
[ "python", "ajax", "django", "django-templates" ]
I would like to share a template between AJAX and regualr HTTP calls, the only difference is that one template needs to be served with the base.html html, the other one without. Any idea?
``` {% extends override_base|default:'base.html' %} ``` P.s. I know this is an old question, but I found it when searching for an answer. Maybe it'll help someone else with the same problem.
Flask/Bottle project organization
5,381,208
10
2011-03-21T17:17:53Z
5,382,001
9
2011-03-21T18:32:21Z
[ "python", "django", "flask", "bottle" ]
I've been looking into microframeworks for Python, and have come across two interesting options, Flask and Bottle. each have some similar features. One thing I noticed is that all the example sites show all the application code located inside a single Python file. Obviously, for even moderately sized sites, this would ...
I don't have any experience with Bottle, but take a look at the [Flask docs](http://flask.pocoo.org/docs/patterns/packages/) on larger applications. My Flask apps all use multiple Flask [`Module`](http://flask.pocoo.org/docs/api/#module-objects) objects as that page recommends, one per Python module, and it seems to wo...
Google App Engine Datastore Query to JSON with Python
5,381,660
2
2011-03-21T18:01:04Z
7,594,509
7
2011-09-29T08:30:55Z
[ "python", "json", "gae-datastore" ]
How can I get a JSON Object in python from getting data via Google App Engine Datastore? I've got model in datastore with following field: ``` id key_name object userid created ``` Now I want to get all objects for one user: ``` query = Model.all().filter('userid', user.user_id()) ``` How can I create a JSON objec...
Not sure if you got the answer you were looking for, but did you mean how to parse the model (entry) data in the Query object directly into a JSON object? (At least that's what I've been searching for). I wrote this to parse the entries from Query object into a list of JSON objects: ``` def gql_json_parser(query_obj)...
Cython correctness
5,382,028
6
2011-03-21T18:34:55Z
5,383,451
9
2011-03-21T20:45:06Z
[ "python", "cython", "correctness" ]
Is code produced by Cython always just as correct as the Python code it was produced from? It may help other readers to address the use of Cython static type declarations and other Cython features (if any), though I am only interested in the case of creating Cython files by renaming the Python modules to \*.pyx. I on...
Generally, yes. Of course there are [bugs](http://trac.cython.org/cython_trac/report/1) (many revolve around expanding the supported Python subset though, bugs that actually make generated C code incorrect are relatively rare), and there are a few necessary [caveats](http://docs.cython.org/src/tutorial/caveats.html) (a...
Where can I download binary eggs with psycopg2 for Windows?
5,382,801
20
2011-03-21T19:48:36Z
5,383,266
48
2011-03-21T20:30:42Z
[ "python", "windows", "binary", "psycopg2", "egg" ]
I'm looking for binary eggs with psycopg2's binaries for Windows but can't find any. On <http://initd.org/psycopg/download/> there's only source package and link to [Windows port of Psycopg](http://www.stickpeople.com/projects/python/win-psycopg/) which provides binary installers but no binary eggs. The reason I'm l...
We just use something like `easy_install http://www.stickpeople.com/projects/python/win-psycopg/psycopg2-2.4.win32-pyx.x-pg9.0.3-release.exe` from within the virtual environment. Seems to work; we end up with psycopg2 in the virtual environment and not in the base environment, which I take to be the endgame here. **U...
QWebKit linkClicked signal never fires
5,383,032
3
2011-03-21T20:08:48Z
5,383,166
7
2011-03-21T20:21:17Z
[ "python", "qt", "pyqt", "qwebview", "qwebkit" ]
``` import sys from PyQt4.QtGui import * from PyQt4.QtCore import * from PyQt4.QtWebKit import QWebView app = QApplication(sys.argv) web_view = QWebView() def url_changed(url): print 'url changed: ', url def link_clicked(url): print 'link clicked: ', url def load_started(): print 'load started' def load_finished(o...
The [link delegation policy](http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qwebpage.html#LinkDelegationPolicy-enum) must be set appropriately for the [linkClicked](http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qwebview.html#linkClicked) signal to be emitted. ``` import sys from PyQt4.QtGui i...
Python or Lua - Realtime application
5,383,145
4
2011-03-21T20:19:45Z
5,383,274
7
2011-03-21T20:31:26Z
[ "python", "lua" ]
I have started using **Python** in a real-time application *(serial communication with to gps modules at once)*, but have found out recently about **Lua**. Which language would be more suited to the application? My definition of real-time in this context is *the fastest possible time to receive, process and output the...
Both are fine languages. Neither should take you years to learn. An easy way to make the decision is to look at what modules are out there already. For example, you mentioned that your application is related to GPS. Take a look at what libraries are already written to hook Python and Lua into your particular GPS hardw...
Python or Lua - Realtime application
5,383,145
4
2011-03-21T20:19:45Z
5,383,280
8
2011-03-21T20:32:09Z
[ "python", "lua" ]
I have started using **Python** in a real-time application *(serial communication with to gps modules at once)*, but have found out recently about **Lua**. Which language would be more suited to the application? My definition of real-time in this context is *the fastest possible time to receive, process and output the...
It's a good but very wide question. [Googling it](http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=lua+vs+python) or reading [this thread](http://stackoverflow.com/questions/902038/lua-vs-other-scripting-languages) is a good start. In my opinion, Lua is *by design* a lightweight scripting language. Whereas Pyth...
What's the shortest way to count the number of items in a generator/iterator?
5,384,570
30
2011-03-21T22:35:56Z
5,384,573
65
2011-03-21T22:37:14Z
[ "python", "iterator", "generator", "iterable" ]
If I want the number of items in an iterable without caring about the elements themselves, what would be the pythonic way to get that? Right now, I would define ``` def ilen(it): return sum(itertools.imap(lambda _: 1, it)) # or just map in Python 3 ``` but I understand `lambda` is close to being considered har...
The usual way is ``` sum(1 for i in it) ```
Why aren't bound instance methods in python reference equal?
5,384,621
9
2011-03-21T22:43:17Z
5,384,691
7
2011-03-21T22:52:19Z
[ "python", "equality", "sentinel" ]
``` >>> class foo(object): ... def test(s): ... pass ... >>> a=foo() >>> a.test is a.test False >>> print a.test <bound method foo.test of <__main__.foo object at 0x1962b90>> >>> print a.test <bound method foo.test of <__main__.foo object at 0x1962b90>> >>> hash(a.test) 28808 >>> hash(a.test) 28808 >>> id(a...
They're bound at runtime; accessing the attribute on the object rebinds the method anew each time. The reason they're different when you put both on the same line is that the first method hasn't been released by the time the second is bound.
How to delete items from a dictionary while iterating over it?
5,384,914
132
2011-03-21T23:23:29Z
5,384,934
12
2011-03-21T23:25:20Z
[ "scripting", "dictionary", "python" ]
Is it legitimate to delete items from a dictionary in Python while iterating over it? For example: ``` for k, v in mydict.iteritems(): if k == val: del mydict[k] ``` The idea is to remove elements that don't meet a certain condition from the dictionary, instead of creating a new dictionary that's a subset of...
Iterate over a copy instead, such as the one returned by `items()`: ``` for k, v in mydict.items(): ```
How to delete items from a dictionary while iterating over it?
5,384,914
132
2011-03-21T23:23:29Z
5,384,956
16
2011-03-21T23:28:01Z
[ "scripting", "dictionary", "python" ]
Is it legitimate to delete items from a dictionary in Python while iterating over it? For example: ``` for k, v in mydict.iteritems(): if k == val: del mydict[k] ``` The idea is to remove elements that don't meet a certain condition from the dictionary, instead of creating a new dictionary that's a subset of...
You can't modify a collection while iterating it. That way lies madness - most notably, if you were allowed to delete and deleted the current item, the iterator would have to move on (+1) and the next call to `next` would take you beyond that (+2), so you'd end up skipping one element (the one right behind the one you ...
How to delete items from a dictionary while iterating over it?
5,384,914
132
2011-03-21T23:23:29Z
5,385,075
175
2011-03-21T23:47:28Z
[ "scripting", "dictionary", "python" ]
Is it legitimate to delete items from a dictionary in Python while iterating over it? For example: ``` for k, v in mydict.iteritems(): if k == val: del mydict[k] ``` The idea is to remove elements that don't meet a certain condition from the dictionary, instead of creating a new dictionary that's a subset of...
A simple test in the console shows you cannot modify a dictionary while iterating over it: ``` >>> mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4} >>> for k, v in mydict.iteritems(): ... if k == 'two': ... del mydict[k] ... ------------------------------------------------------------ Traceback (most rec...
How to delete items from a dictionary while iterating over it?
5,384,914
132
2011-03-21T23:23:29Z
5,385,196
42
2011-03-22T00:04:25Z
[ "scripting", "dictionary", "python" ]
Is it legitimate to delete items from a dictionary in Python while iterating over it? For example: ``` for k, v in mydict.iteritems(): if k == val: del mydict[k] ``` The idea is to remove elements that don't meet a certain condition from the dictionary, instead of creating a new dictionary that's a subset of...
You could also do it in two steps: ``` remove = [k for k in mydict if k == val] for k in remove: del mydict[k] ``` My favorite approach is usually to just make a new dict: ``` # Python 2.7 and 3.x mydict = { k:v for k,v in mydict.items() if k!=val } # before Python 2.7 mydict = dict((k,v) for k,v in mydict.iteritems...
template in python
5,385,397
6
2011-03-22T00:35:12Z
5,385,426
9
2011-03-22T00:38:50Z
[ "python", "string", "templates", "format" ]
How to write a function render\_user which takes one of the tuples returned by userlist and a string template and returns the data substituted into the template, eg: ``` >>> tpl = "<a href='mailto:%s'>%s</a>" >>> render_user(('matt.rez@where.com', 'matt rez', ), tpl) "<a href='mailto:matt.rez@where.com>Matt rez</a>" `...
No urgent need to create a function, if you don't require one: ``` >>> tpl = "<a href='mailto:%s'>%s</a>" >>> s = tpl % ('matt.rez@where.com', 'matt rez', ) >>> print s "<a href='mailto:matt.rez@where.com'>matt rez</a>" ``` If you're on 2.6+ you can alternatively use the new `format` function along with its mini lan...
Consuming RSS in Django ( / Python)
5,385,565
8
2011-03-22T00:59:34Z
5,385,657
7
2011-03-22T01:12:10Z
[ "python", "django", "rss" ]
For a site I'm working on I would like to import a lot of RSS feeds using Django. Since I need the content of them fast I will need to cache them locally (either in the database or in some other way) **Is there a standard app to do RSS consumption in Django, or is there a standard way to do this in Python?** Of cours...
Check out~~http://feedparser.org/docs/~~ <http://code.google.com/p/feedparser/> One of the best Python libraries for parsing RSS and Atom Feeds; although it seems like you want to do a bit more (caching, auto-refresh etc.)
Python Lxml (objectify): Checking whether a tag exists
5,385,821
10
2011-03-22T01:40:37Z
8,785,975
20
2012-01-09T09:08:02Z
[ "python", "xml", "lxml", "objectify" ]
I need to check whether a certain tag exists in an xml file. For example, I want to see if the tag exists in this snippet: ``` <main> <elem1/> <elem2>Hi</elem2> <elem3/> ... </main> ``` Currently, I am using an ugly hack with error checking, like this: ``` try: if root.elem1.tag: ...
`hasattr()` works for this: ``` if hasattr(root, 'elem1'): foo = root.elem1 ```
django content types - how to get model class of content type to create a instance?
5,386,104
12
2011-03-22T02:33:20Z
5,386,134
21
2011-03-22T02:38:51Z
[ "python", "django", "django-contenttypes" ]
I dont know if im clear with the title quiestion, what I want to do is the next case: ``` >>> from django.contrib.contenttypes.models import ContentType >>> ct = ContentType.objects.get(model='user') >>> ct.model_class() <class 'django.contrib.auth.models.User'> >>> ct_class = ct.model_class() >>> ct_class.username = ...
You need to create an instance of the class. `ct.model_class()` returns the class, not an instance of it. Try the following: ``` >>> from django.contrib.contenttypes.models import ContentType >>> ct = ContentType.objects.get(model='user') >>> ct_class = ct.model_class() >>> ct_instance = ct_class() >>> ct_instance.use...
Fast way to Hash Numpy objects for Caching
5,386,694
15
2011-03-22T04:09:55Z
5,386,770
19
2011-03-22T04:21:59Z
[ "python", "performance", "numpy" ]
Implementing a system where, when it comes to the heavy mathematical lifting, I want to do as little as possible. I'm aware that there are issues with memoisation with numpy objects, and as such implemented a lazy-key cache to avoid the whole "Premature optimisation" argument. ``` def magic(numpyarg,intarg): key ...
Borrowed from [this answer](http://stackoverflow.com/questions/806151/how-to-hash-a-large-object-dataset-in-python/806342#806342)... so really I guess this is a duplicate: ``` >>> import hashlib >>> import numpy >>> a = numpy.random.rand(10, 100) >>> b = a.view(numpy.uint8) >>> hashlib.sha1(b).hexdigest() '15c61fba5c9...
convert a string to an array
5,387,208
39
2011-03-22T05:26:58Z
5,387,227
72
2011-03-22T05:29:23Z
[ "python", "arrays", "string" ]
How do you convert a string into an array? say the string is like `text = "a,b,c"`. After the conversion, `text == [a,b,c]` and hopefully `text[0] == a`, `text[1] == b`? Thank you
Like this: ``` >>> text = 'a,b,c' >>> text = text.split(',') >>> text [ 'a', 'b', 'c' ] ``` Alternatively, you can use `eval()` if you trust the string to be safe: ``` >>> text = 'a,b,c' >>> text = eval('[' + text + ']') ```
convert a string to an array
5,387,208
39
2011-03-22T05:26:58Z
10,693,785
11
2012-05-21T23:09:50Z
[ "python", "arrays", "string" ]
How do you convert a string into an array? say the string is like `text = "a,b,c"`. After the conversion, `text == [a,b,c]` and hopefully `text[0] == a`, `text[1] == b`? Thank you
The following Python code will turn your string into a list of strings: ``` import ast teststr = "['aaa','bbb','ccc']" testarray = ast.literal_eval(teststr) ```
convert a string to an array
5,387,208
39
2011-03-22T05:26:58Z
11,493,649
53
2012-07-15T16:32:53Z
[ "python", "arrays", "string" ]
How do you convert a string into an array? say the string is like `text = "a,b,c"`. After the conversion, `text == [a,b,c]` and hopefully `text[0] == a`, `text[1] == b`? Thank you
Just to add on to the existing answers: hopefully, you'll encounter something more like this in the future: ``` >>> word = 'abc' >>> L = list(word) >>> L ['a', 'b', 'c'] >>> ''.join(L) 'abc' ``` But what you're dealing with *right now*, go with @[Cameron](http://stackoverflow.com/users/21475/cameron)'s answer. ``` >...
convert a string to an array
5,387,208
39
2011-03-22T05:26:58Z
25,907,664
7
2014-09-18T08:23:57Z
[ "python", "arrays", "string" ]
How do you convert a string into an array? say the string is like `text = "a,b,c"`. After the conversion, `text == [a,b,c]` and hopefully `text[0] == a`, `text[1] == b`? Thank you
# I don't think you *need* to In python you seldom need to convert a string to a list, because strings and lists are very similar ## Changing the type If you really have a string which should be a character array, do this: ``` In [1]: x = "foobar" In [2]: list(x) Out[2]: ['f', 'o', 'o', 'b', 'a', 'r'] ``` ## Not c...
Python unittest.TestCase execution order
5,387,299
37
2011-03-22T05:40:12Z
5,387,360
15
2011-03-22T05:48:35Z
[ "python", "unit-testing" ]
Is there a way in Python `unittest` to set the order in which test cases are run? In my current `TestCase` class, some testcases have side-effects that set conditions for the others to run properly. Now I realize the proper way to do this is to use `setUp()` to do all setup realted things, but I would like to implemen...
<http://docs.python.org/library/unittest.html> > Note that the order in which the various test cases will be run is determined by sorting the test function names with respect to the built-in ordering for strings. So just make sure `test_setup`'s name has the smallest string value. **Note that you should not rely on ...
Python unittest.TestCase execution order
5,387,299
37
2011-03-22T05:40:12Z
5,387,956
45
2011-03-22T07:18:45Z
[ "python", "unit-testing" ]
Is there a way in Python `unittest` to set the order in which test cases are run? In my current `TestCase` class, some testcases have side-effects that set conditions for the others to run properly. Now I realize the proper way to do this is to use `setUp()` to do all setup realted things, but I would like to implemen...
Don't make them independent tests - if you want a monolithic test, write a monolithic test. ``` class Monolithic(TestCase): def step1(self): ... def step2(self): ... def _steps(self): for name in sorted(dir(self)): if name.startswith("step"): yield name, getattr(self, name) de...
Python unittest.TestCase execution order
5,387,299
37
2011-03-22T05:40:12Z
7,085,051
13
2011-08-16T21:08:59Z
[ "python", "unit-testing" ]
Is there a way in Python `unittest` to set the order in which test cases are run? In my current `TestCase` class, some testcases have side-effects that set conditions for the others to run properly. Now I realize the proper way to do this is to use `setUp()` to do all setup realted things, but I would like to implemen...
Its a good practice to always write a monolithic test for such expectations, however if yer a goofy dude like me, then you could simply write ugly looking methods in alphabetical order so that they are sorted from a to b as mentioned in the python docs <http://docs.python.org/library/unittest.html> > Note that the ord...
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 3 2: ordinal not in range(128)
5,387,895
35
2011-03-22T07:09:19Z
5,387,966
39
2011-03-22T07:20:17Z
[ "python" ]
I am parsing an xsl file using xlrd. Most of the things are working fine. I have a dictionary where keys are strings and values are lists of strings. All the keys and values are unicode. I can print most of the keys and values using `str()` method. But some values have the unicode character - `\u2013` for which I get t...
You can print Unicode objects as well, you don't need to do str() around it. Assuming you really want a str: When you do str(u'\u2013') you are trying to convert the Unicode string to a 8-bit string. To do this you need to use an encoding, a mapping between Unicode data to 8-bit data. What str() does is that is uses ...
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2013' in position 3 2: ordinal not in range(128)
5,387,895
35
2011-03-22T07:09:19Z
27,948,713
7
2015-01-14T17:18:32Z
[ "python" ]
I am parsing an xsl file using xlrd. Most of the things are working fine. I have a dictionary where keys are strings and values are lists of strings. All the keys and values are unicode. I can print most of the keys and values using `str()` method. But some values have the unicode character - `\u2013` for which I get t...
You can also try this to get the text. ``` foo.encode('ascii', 'ignore') ```
Iterating over every two elements in a list
5,389,507
93
2011-03-22T10:01:39Z
5,389,547
124
2011-03-22T10:04:03Z
[ "python", "list" ]
How do I make a `for` loop or a list comprehension so that every iteration gives me two elements? ``` l = [1,2,3,4,5,6] for i,k in ???: print str(i), '+', str(k), '=', str(i+k) ``` Output: ``` 1+2=3 3+4=7 5+6=11 ```
You need a **`pairwise()`** (or **`grouped()`**) implementation. For Python 2: ``` from itertools import izip def pairwise(iterable): "s -> (s0, s1), (s2, s3), (s4, s5), ..." a = iter(iterable) return izip(a, a) for x, y in pairwise(l): print "%d + %d = %d" % (x, y, x + y) ``` Or, more generally: `...
Iterating over every two elements in a list
5,389,507
93
2011-03-22T10:01:39Z
5,389,578
81
2011-03-22T10:06:12Z
[ "python", "list" ]
How do I make a `for` loop or a list comprehension so that every iteration gives me two elements? ``` l = [1,2,3,4,5,6] for i,k in ???: print str(i), '+', str(k), '=', str(i+k) ``` Output: ``` 1+2=3 3+4=7 5+6=11 ```
Well you need tuple of 2 elements, so ``` data = [1,2,3,4,5,6] for i,k in zip(data[0::2], data[1::2]): print str(i), '+', str(k), '=', str(i+k) ``` Where: * `data[0::2]` means create subset collection of elements that `(index % 2 == 0)` * `zip(x,y)` creates a tuple collection from x and y collections same index ...
Iterating over every two elements in a list
5,389,507
93
2011-03-22T10:01:39Z
5,389,599
32
2011-03-22T10:07:47Z
[ "python", "list" ]
How do I make a `for` loop or a list comprehension so that every iteration gives me two elements? ``` l = [1,2,3,4,5,6] for i,k in ???: print str(i), '+', str(k), '=', str(i+k) ``` Output: ``` 1+2=3 3+4=7 5+6=11 ```
A simple solution. ``` l = [1, 2, 3, 4, 5, 6] for i in range(0, len(l), 2): print str(l[i]), '+', str(l[i + 1]), '=', str(l[i] + l[i + 1]) ```
Iterating over every two elements in a list
5,389,507
93
2011-03-22T10:01:39Z
5,394,908
40
2011-03-22T16:54:51Z
[ "python", "list" ]
How do I make a `for` loop or a list comprehension so that every iteration gives me two elements? ``` l = [1,2,3,4,5,6] for i,k in ???: print str(i), '+', str(k), '=', str(i+k) ``` Output: ``` 1+2=3 3+4=7 5+6=11 ```
``` >>> l = [1,2,3,4,5,6] >>> zip(l,l[1:]) [(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)] >>> zip(l,l[1:])[::2] [(1, 2), (3, 4), (5, 6)] >>> [a+b for a,b in zip(l,l[1:])[::2]] [3, 7, 11] >>> ["%d + %d = %d" % (a,b,a+b) for a,b in zip(l,l[1:])[::2]] ['1 + 2 = 3', '3 + 4 = 7', '5 + 6 = 11'] ```
Iterating over every two elements in a list
5,389,507
93
2011-03-22T10:01:39Z
30,426,000
13
2015-05-24T16:57:24Z
[ "python", "list" ]
How do I make a `for` loop or a list comprehension so that every iteration gives me two elements? ``` l = [1,2,3,4,5,6] for i,k in ???: print str(i), '+', str(k), '=', str(i+k) ``` Output: ``` 1+2=3 3+4=7 5+6=11 ```
While all the answers using `zip` are correct, I find that implementing the functionality yourself leads to more readable code: ``` def pairwise(it): it = iter(it) while True: yield next(it), next(it) ``` The `it = iter(it)` part ensures that `it` is actually an iterator, not just an iterable. If `it`...
Python - iterating over result of list.append
5,390,352
2
2011-03-22T11:18:41Z
5,390,393
10
2011-03-22T11:22:18Z
[ "python", "list" ]
why can't I do something like this: ``` files = [file for file in ['default.txt'].append(sys.argv[1:]) if os.path.exists(file)] ```
`list.append` doesn't return anything in Python: ``` >>> l = [1, 2, 3] >>> k = l.append(5) >>> k >>> k is None True ``` You may want this instead: ``` >>> k = [1, 2, 3] + [5] >>> k [1, 2, 3, 5] >>> ``` Or, in your code: ``` files = [file for file in ['default.txt'] + sys.argv[1:] if os.path.exists(file)] ```
Patches I add to my graph are not opaque with alpha=1. Why?
5,390,699
3
2011-03-22T11:48:05Z
5,391,258
8
2011-03-22T12:32:47Z
[ "python", "matplotlib" ]
I would like to add a rectangle over a graph. Through all the documentation I've found, the rectangle should be opaque by default, with transparency controlled by an alpha argument. However, I can't get the rectangle to show up as opaque, even with alpha = 1. Am I doing something wrong, or is there something else I nee...
From the [documentation](http://matplotlib.sourceforge.net/faq/howto_faq.html?highlight=zorder#control-the-depth-of-plot-elements): > Within an axes, the order that the > various lines, markers, text, > collections, etc appear is determined > by the > matplotlib.artist.Artist.set\_zorder() > property. The default orde...
Matplotlib, alternatives to savefig() to improve performance when saving into a CString object?
5,391,026
14
2011-03-22T12:15:23Z
5,394,042
32
2011-03-22T15:57:24Z
[ "python", "performance", "matplotlib", "plot", "cstring" ]
I am trying to speed up the process of saving my charts to images. Right now I am creating a cString Object where I save the chart to by using savefig; but I would really, really appreciate any help to improve this method of saving the image. I have to do this operation dozens of times, and the savefig command is very ...
If you just want a raw buffer, try `fig.canvas.print_rgb`, `fig.canvas.print_raw`, etc (the difference between the two is that `raw` is rgba, whereas `rgb` is rgb. There's also `print_png`, `print_ps`, etc) This will use `fig.dpi` instead of the default dpi value for `savefig` (100 dpi). Still, even comparing `fig.can...
Executing a function by variable name in Python
5,391,199
8
2011-03-22T12:28:24Z
5,391,245
20
2011-03-22T12:32:15Z
[ "python" ]
What I need to do is loop over a large number of different files and (try to) fetch metadata from the files. I can make a large if...elif... and test for every extension, but I think it would be much easier to store the extension in a variable, check if a function with that name exists, and execute it. This is my cur...
You can do : ``` func = getattr(modulename, funcname, None): if func: func(arg) ``` Or maybe better: ``` try: func = getattr(modulename, funcname) except AttributeError: print 'function not found "%s" (%s)' % (funcname, arg) else: func(arg) ```
Python dict.get() behavior when first arg exists but *default* doesn't
5,391,968
3
2011-03-22T13:23:21Z
5,391,992
9
2011-03-22T13:25:25Z
[ "python", "dictionary" ]
So, I have some code which contains a dictionary, and I do some validation on the dictionary. The validation rule is basically that the dictionary may contain either a 'to' key, or a 'to[]' key. Whichever one it contains, I need the value back so I can check the length against the length of another key in the dictionar...
Arguments to a function or method are always evaluated before the function is called. If you don't want this then use a sentinel object instead of the expression as the default.
How to close cursor in MongoKit
5,392,318
6
2011-03-22T13:50:41Z
5,394,241
9
2011-03-22T16:08:00Z
[ "python", "mongodb", "cursor", "pymongo", "mongokit" ]
I'm using MongoKit to perform iteration over a huge amount of data. During this process my cursor becomes invalid, and I'm getting `OperationFailure: cursor id '369397057360964334' not valid at server` I've read in mailing lists that I can pass parameter `timeout=False` to `.find()` method, but [PyMongo FAQ](http://...
You'll have to close the cursor since the MongoDB server won't time out the cursor for you, given that you specifically asked it not to. simply call `del` on your cursor. The default pymongo implementation for `__del__` will notify the server to kill the cursor. Assuming something like: ``` cursor = db.test.find(tim...
Why is PyPi called the cheese shop?
5,393,986
36
2011-03-22T15:54:05Z
5,394,057
10
2011-03-22T15:58:07Z
[ "python", "pypi" ]
I was running through the tutorials to build a Python distro package yesterday and the PyPi site kept on being calling the Cheese Shop. Why is that?
Because it's where you get your eggs!
Why is PyPi called the cheese shop?
5,393,986
36
2011-03-22T15:54:05Z
5,394,060
38
2011-03-22T15:58:16Z
[ "python", "pypi" ]
I was running through the tutorials to build a Python distro package yesterday and the PyPi site kept on being calling the Cheese Shop. Why is that?
Following the fact that the name of the Python language is taken from the Monty Python comedy group, it's a reference to the "[Cheese Shop](http://www.youtube.com/watch?v=B3KBuQHHKx0)" sketch they did. There have been other prominent Python projects that have used the same approach to select names ([Bicycle Repairman]...
How to setup PostgreSQL Database in Django?
5,394,331
58
2011-03-22T16:13:19Z
5,421,511
126
2011-03-24T15:23:28Z
[ "python", "django", "postgresql", "psycopg2", "django-settings" ]
I'm new to Python and Django. I'm configuring a Django project using PostgreSQL database engine backend, But I'm getting errors on each database operations, for example when i run `manage.py syncdb`, I'm getting: ``` C:\xampp\htdocs\djangodir>python manage.py syncdb Traceback (most recent call last): File "manage.p...
It's same to my problem, and I solved it! You need to install [`psycopg2`](http://initd.org/psycopg/) Python library. ## Installation --- Download <http://initd.org/psycopg/>, then install it under django & python PATH After downloading, easily extract the tarball and: ``` python setup.py install ``` Or if you w...
How to setup PostgreSQL Database in Django?
5,394,331
58
2011-03-22T16:13:19Z
11,989,045
24
2012-08-16T14:12:25Z
[ "python", "django", "postgresql", "psycopg2", "django-settings" ]
I'm new to Python and Django. I'm configuring a Django project using PostgreSQL database engine backend, But I'm getting errors on each database operations, for example when i run `manage.py syncdb`, I'm getting: ``` C:\xampp\htdocs\djangodir>python manage.py syncdb Traceback (most recent call last): File "manage.p...
Also make sure you have the PostgreSQL development package installed. On Ubuntu you need to do something like this: ``` $ sudo apt-get install libpq-dev ```
How to specify install order for python pip?
5,394,356
26
2011-03-22T16:14:38Z
5,395,951
7
2011-03-22T18:21:02Z
[ "python", "requirements", "virtualenv", "pip" ]
I'm working with fabric(0.9.4)+pip(0.8.2) and I need to install some python modules for multiple servers. All servers have old version of setuptools (0.6c8) which needs to be upgraded for pymongo module. Pymongo requires setuptools>=0.6c9. My problem is that pip starts installation with pymongo instead of setuptools w...
This is a silly hack, but might just work. Write a bash script that reads from your requirements file line by line and runs the pip command on it. ``` #!/bin/bash for line in $(cat requirements.txt) do pip install $line -E /path/to/virtualenv done ```
How to specify install order for python pip?
5,394,356
26
2011-03-22T16:14:38Z
13,503,666
18
2012-11-21T23:22:05Z
[ "python", "requirements", "virtualenv", "pip" ]
I'm working with fabric(0.9.4)+pip(0.8.2) and I need to install some python modules for multiple servers. All servers have old version of setuptools (0.6c8) which needs to be upgraded for pymongo module. Pymongo requires setuptools>=0.6c9. My problem is that pip starts installation with pymongo instead of setuptools w...
You can just use: ``` cat requirements.txt | xargs pip install ```
is it possible to call a function every x-number of lines that get interpreted?
5,394,929
2
2011-03-22T16:56:46Z
5,395,225
9
2011-03-22T17:17:35Z
[ "python" ]
I am trying to do a progress bar. Would it be possible to count the number of execution lines on a script and associate each execution line with a function so that it is executed every line or every 5 lines? My plan is to update a progress bar every time a line is executed. Is it possible? Can I use decorators to do...
Yep, you can do that by asking Python to alert you every time it processes a line. Here's an example that prints to stdout after every `updatelines` times a line is executed: ``` import sys class EveryNLines(object): def __init__(self, updatelines): self.processed = 0 self.updatelines = updateline...
How can I create a Python timestamp with millisecond granularity?
5,395,872
15
2011-03-22T18:13:13Z
5,395,939
25
2011-03-22T18:19:51Z
[ "python", "datetime", "timestamp" ]
I need a single timestamp of milliseconds (ms) since epoch. This should not be hard, I am sure I am just missing some method of `datetime` or something similar. Actually microsecond (µs) granularity is fine too. I just need sub 1/10th second timing. Example. I have an event that happens every 750 ms, lets say it che...
``` import time time.time() * 1000 ``` where 1000 is milliseconds per second. If all you want is hundredths of a second since the epoch, multiply by 100.
Incredibly basic lxml questions: getting HTML/string content of lxml.etree._Element?
5,395,948
11
2011-03-22T18:20:56Z
5,396,320
28
2011-03-22T18:50:57Z
[ "python", "lxml" ]
This is such a basic question that I actually can't find it in the docs :-/ In the following: ``` img = house_tree.xpath('//img[@id="mainphoto"]')[0] ``` How do I get the HTML of the `<img/>` tag? I've tried adding `html_content()` but get `AttributeError: 'lxml.etree._Element' object has no attribute 'html_content...
I suppose it will be as simple as: ``` from lxml.etree import tostring inner_html=tostring(img) ``` As for getting content from inside `<p>`, say, some selected element `el`: ``` content = el.text_content() ```
What are the difference in these two 2d arrays?
5,397,519
2
2011-03-22T20:36:10Z
5,397,545
7
2011-03-22T20:38:37Z
[ "python", "arrays", "syntax", "multidimensional-array" ]
I was writing a program that needs a 2d array, and came upon a strange problem. At first, I wrote: ``` board = [[]]*11 ``` to make eleven arrays within an array. Then I wanted eleven blanks within each array so I wrote: ``` for i in range(11): board[i].append(' ') ``` I wanted to fill the third array, from in...
The list `[[]] * 11` contains 11 references to the *same list*. Your second example creates 11 *different* lists. ``` board = [[]]*11 # ^^ this is called just once board2 = [] for i in range(11): board2.append([]) # ^^ this is called 11 times, creating 11 different lists ``` Another way t...
Fourier transform of a Gaussian is not a Gaussian, but thats wrong! - Python
5,398,304
5
2011-03-22T21:52:12Z
5,398,901
11
2011-03-22T22:59:33Z
[ "python", "numpy", "fft" ]
I am trying to utilize Numpy's fft function, however when I give the function a simple gausian function the fft of that gausian function is not a gausian, its close but its halved so that each half is at either end of the x axis. The Gaussian function I'm calculating is y = exp(-x^2) Here is my code: ``` from cmath ...
`np.fft.fft` returns a result in so-called "standard order": ([from the docs](http://docs.scipy.org/doc/numpy/reference/routines.fft.html#background-information)) > If `A = fft(a, n)`, then `A[0]` > contains the zero-frequency term (the > mean of the signal), which is always > purely real for real inputs. Then > `A[1:...
django - regex for optional url paramaters
5,399,035
7
2011-03-22T23:15:57Z
5,399,826
9
2011-03-23T01:18:07Z
[ "python", "django", "url-pattern", "urlconf" ]
I have a view in django that can accept a number of different filter parameters, but they are all optional. If I have 6 optional filters, do I really have to write urls for every combination of the 6 or is there a way to define what parts of the url are optional? To give you an example with just 2 filters, I could hav...
One method would be to make the regular expression read all the given filters as a single string, and then split them up into individual values in the view. I came up with the following URL: ``` (r'^(?P<city>[^/]+)/(?P<state>[^/]+)(?P<filters>(?:/[^/]+/[^/]+)*)/?$', 'views.my_view'), ``` Matching the required city ...
django - regex for optional url paramaters
5,399,035
7
2011-03-22T23:15:57Z
5,402,658
8
2011-03-23T08:41:02Z
[ "python", "django", "url-pattern", "urlconf" ]
I have a view in django that can accept a number of different filter parameters, but they are all optional. If I have 6 optional filters, do I really have to write urls for every combination of the 6 or is there a way to define what parts of the url are optional? To give you an example with just 2 filters, I could hav...
This is absolutely the use-case for GET parameters. Your urlconf should just be `/city/state/`, then the various filters go on the end as GET variables: ``` /city/state/?radius=5&company=google ``` Now, in your view, you accept `city` and `state` as normal parameters, but everything else is stored in the `request.GET...
How do I url encode in Python?
5,399,112
4
2011-03-22T23:26:27Z
5,399,164
9
2011-03-22T23:32:43Z
[ "python" ]
I tried this: but it doesn't work. ``` print urllib.urlencode("http://"+SITE_DOMAIN+"/go/") ``` I want to turn it into a string with url encodings
Were you looking for the [quote()](http://docs.python.org/release/2.7/library/urllib.html#urllib.quote) or [quote\_plus()](http://docs.python.org/release/2.7/library/urllib.html#urllib.quote_plus) function instead? ``` >>> urllib.quote("http://spam.com/go/") 'http%3A%2F%2Fspam.com%2Fgo%2F' ```
Why is the "else" line giving an invalid syntax error?
5,399,190
10
2011-03-22T23:36:45Z
5,399,203
22
2011-03-22T23:38:39Z
[ "python", "syntax-error", "indentation", "if-statement" ]
I'm having this error: ``` File "zzz.py", line 70 else: ^ SyntaxError: invalid syntax ``` The line which causes the problem is marked with a comment in the code: ``` def FileParse(self, table_file): vars={} tf = open(table_file, 'r') for line in tf: if line.startswith("#") or line.stri...
Because you left out a closing brace ``` w.rules.append(Rule(change[:5],change[5]) ) ```
fast, large-width, non-cryptographic string hashing in python
5,400,275
30
2011-03-23T02:40:16Z
5,400,389
20
2011-03-23T03:00:17Z
[ "python", "string", "hash", "high-speed-computing" ]
I have a need for a high-performance string hashing function in python that produces integers with at least **34** bits of output (64 bits would make sense, but 32 is too few). There are several other questions like this one on Stack Overflow, but of those every accepted/upvoted answer I could find fell in to one of a ...
Take a look at the [128-bit variant of MurmurHash3](http://code.google.com/p/smhasher/). The [algorithm's page](http://code.google.com/p/smhasher/wiki/MurmurHash3) includes some performance numbers. Should be possible to port this to Python, pure or as a C extension. (**Updated** the author recommends using the 128-bit...
How to write a simple Bittorrent application?
5,400,828
27
2011-03-23T04:18:03Z
5,494,823
64
2011-03-31T02:49:25Z
[ "python", "c", "network-programming", "p2p", "bittorrent" ]
How to write a simple bittorrent application. Something like a "hello world" using a bittorrent library, I mean a simplest of the application to understand the working of bittorrent. I would prefer a python or a C/C++ implementation, but it can be any language. Platform is not an issues either, but i would prefer Linux...
You should try libtorrent (rasterbar). <http://libtorrent.org> If you want to write your client in python, on linux, install it with: `sudo apt-get install python-libtorrent` A very simple example of python code to use it to download a torrent: ``` import libtorrent as lt import time import sys ses = lt.session() ...
Installation of pygtk not working
5,401,864
8
2011-03-23T07:02:52Z
5,404,476
10
2011-03-23T11:23:26Z
[ "python", "installation", "64bit", "pygtk" ]
I am running on Windows (64bit version) and have python 2.7 (also 64 bit) installed. I downloaded the all-in-one installer for pygtk for python 2.7, but when I run it, it shows "python 2.7 could not be located on your system". Why is it so when I already have python 2.7 installed?
Currently, the all-in-one installer binaries [here](http://ftp.gnome.org/pub/GNOME/binaries/win32/pygtk/2.22/) are compiled against 32 bits python only. There is no 64 bits binary in there. Install python 2.7 32 bits on your windows and it should work. Alternatively, you could grab a C compiler, and then try to compil...
Error when creating a PostgreSQL database using python, sqlalchemy and psycopg2
5,402,805
12
2011-03-23T08:58:27Z
5,403,680
12
2011-03-23T10:18:00Z
[ "python", "postgresql", "sqlalchemy", "psycopg2" ]
I use sqlalchemy that uses psycopg2 for connecting to postgresql servers. When I launch the following code: ``` from sqlalchemy.engine.url import URL from sqlalchemy.engine import create_engine url = URL(drivername='postgresql', username='myname', password='mypasswd', host='localhost', database='template1') eng = cre...
``` from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker engine = create_engine('postgresql+psycopg2://USER:PASSWORD@127.0.0.1:5432/DB_OR_TEMPLATE') session = sessionmaker(bind=engine)() session.connection().connection.set_isolation_level(0) session.execute('CREATE DATABASE test') session.connec...
Error when creating a PostgreSQL database using python, sqlalchemy and psycopg2
5,402,805
12
2011-03-23T08:58:27Z
5,654,427
13
2011-04-13T19:21:13Z
[ "python", "postgresql", "sqlalchemy", "psycopg2" ]
I use sqlalchemy that uses psycopg2 for connecting to postgresql servers. When I launch the following code: ``` from sqlalchemy.engine.url import URL from sqlalchemy.engine import create_engine url = URL(drivername='postgresql', username='myname', password='mypasswd', host='localhost', database='template1') eng = cre...
Same without using ORM Session: ``` conn = eng.connect() conn.connection.connection.set_isolation_level(0) conn.execute('create database test') conn.connection.connection.set_isolation_level(1) ``` Surely there would be no reason to use ORM to set isolation level on plain DB connection, right?
Zero-value colour in matplotlib hexbin
5,402,898
9
2011-03-23T09:07:04Z
5,405,654
12
2011-03-23T13:05:15Z
[ "python", "matplotlib", "plot" ]
I have some spatially-distributed data. I'm plotting this with `matplotlib.pyplot.hexbin` and would like to change the "background" (i.e. zero-value) colour. An example is shown below - my colour-map of choice is `matplotlib.cm.jet`: ![Example data](http://i.stack.imgur.com/X1UzW.png) How can I change the base colour...
`hexbin(x,y,mincnt=1)` should do the trick. Essentially, you only want to display the hexagons with more than 1 count in them. ``` from numpy import linspace from numpy.random import normal from pylab import hexbin,show n = 2**6 x = linspace(-1,1,n) y = normal(0,1,n) h = hexbin(x,y,gridsize=10,mincnt=0) ``` gives,...
How to set a default string for raw_input?
5,403,138
28
2011-03-23T09:30:49Z
5,405,058
8
2011-03-23T12:12:26Z
[ "python", "input", "raw-input" ]
I'm using python2.7's `raw_input` to read from stdin. I want to let the user change a given default string. Code: ``` i = raw_input("Please enter name:") ``` Console: ``` Please enter name: Jack ``` The user should be presented with `Jack` but can change (backspace) it to something else. The `Please enter name:`...
In dheerosaur's answer If user press Enter to select default value in reality it wont be saved as python considers it as '' string so Extending a bit on what dheerosaur. ``` default = "Jack" user_input = raw_input("Please enter name: %s"%default + chr(8)*4) if not user_input: user_input = default ``` Fyi .. The `...
How to set a default string for raw_input?
5,403,138
28
2011-03-23T09:30:49Z
20,351,345
50
2013-12-03T12:34:05Z
[ "python", "input", "raw-input" ]
I'm using python2.7's `raw_input` to read from stdin. I want to let the user change a given default string. Code: ``` i = raw_input("Please enter name:") ``` Console: ``` Please enter name: Jack ``` The user should be presented with `Jack` but can change (backspace) it to something else. The `Please enter name:`...
You could do: ``` i = raw_input("Please enter name[Jack]:") or "Jack" ``` This way, if user just presses return without entering anything, "i" will be assigned "Jack".
Is there a way to close a workbook using xlrd
5,403,781
17
2011-03-23T10:24:22Z
5,403,934
16
2011-03-23T10:37:38Z
[ "python", "xlrd" ]
I am using the function open\_workbook() to open an excel file. But I cannot find any function to close the file later in the xlrd module. Is there a way to close the xls file using xlrd? Or is not required at all?
Digging into the [mailing list archive](https://groups.google.com/forum/?hl=en&pli=1#!searchin/python-excel/close/python-excel/U2mKQkfLkGQ/ogym1iiW_R4J), it seems that the file object is closed directly by the constructor, so you don't need to close it explicitly.
How to read keyboard-input?
5,404,068
46
2011-03-23T10:49:06Z
5,404,116
60
2011-03-23T10:53:34Z
[ "python", "keyboard" ]
I would like to read data from the keyboard in python I try this : ``` nb = input('Choose a number') print ('Number%s \n' % (nb)) ``` and this one : ``` conv = BufferedReader (InputStreamReader(System.inputStream)) nb = conv.readLine() print ('Number %s \n' % (nb)) ``` But nothing works, neither with eclipse nor i...
try ``` raw_input('Enter your input:') ``` and if you want to have a numeric value just convert it: ``` try: mode=int(raw_input('Input:')) except ValueError: print "Not a number" ```
How to read keyboard-input?
5,404,068
46
2011-03-23T10:49:06Z
5,405,460
48
2011-03-23T12:47:22Z
[ "python", "keyboard" ]
I would like to read data from the keyboard in python I try this : ``` nb = input('Choose a number') print ('Number%s \n' % (nb)) ``` and this one : ``` conv = BufferedReader (InputStreamReader(System.inputStream)) nb = conv.readLine() print ('Number %s \n' % (nb)) ``` But nothing works, neither with eclipse nor i...
It seems that you are mixing different Pythons here (Python 2.x vs. Python 3.x)... This is basically correct: ``` nb = input('Choose a number: ') ``` The problem is that it is only supported in Python 3. As @sharpner answered, for older versions of Python (2.x), you have to use the function `raw_input`: ``` nb = raw...
Accessing elements of python dictionary
5,404,665
32
2011-03-23T11:40:02Z
5,404,716
29
2011-03-23T11:44:06Z
[ "python", "dictionary" ]
Consider a dict like ``` dict = { 'Apple': {'American':'16', 'Mexican':10, 'Chinese':5}, 'Grapes':{'Arabian':'25','Indian':'20'} } ``` How do I access for instance a particular element of this dictionary ? for instance I would like to print first element after some formatting the first element of Apple which in o...
Given that it is a dictionary you access it by using the keys. Getting the dictionary stored under "Apples", do the following: ``` >>> dict["Apple"] {'American': '16', 'Mexican': 10, 'Chinese': 5} ``` And getting how many of them are American (16), do like this: ``` >>> dict["Apple"]["American"] '16' ```
Accessing elements of python dictionary
5,404,665
32
2011-03-23T11:40:02Z
5,405,130
13
2011-03-23T12:18:32Z
[ "python", "dictionary" ]
Consider a dict like ``` dict = { 'Apple': {'American':'16', 'Mexican':10, 'Chinese':5}, 'Grapes':{'Arabian':'25','Indian':'20'} } ``` How do I access for instance a particular element of this dictionary ? for instance I would like to print first element after some formatting the first element of Apple which in o...
If the questions is, if I know that I have a dict of dicts that contains 'Apple' as a fruit and 'American' as a type of apple, I would use: ``` myDict = {'Apple': {'American':'16', 'Mexican':10, 'Chinese':5}, 'Grapes':{'Arabian':'25','Indian':'20'} } print myDict['Apple']['American'] ``` as others suggest...
problem with python list
5,405,887
2
2011-03-23T13:24:30Z
5,405,967
7
2011-03-23T13:30:07Z
[ "python", "list", "text-files" ]
Hi im trying to create a list adding to it via a for loop reading line by line from a txt file. Im getting a syntax error on the list but am unsure about how to fix the problem ??? ``` import re file = open("text.txt","r") text = file.readlines() file.close() line_count=0 for line in text: User_Input_list[] += [...
Do it like this: ``` input = [] line_count = 0 with open("text.txt","r") as file: for line in file: input.extend(line.split()) line_count += 1 ```
How can i remove <p> </p> with python sub
5,406,326
3
2011-03-23T13:55:59Z
5,406,342
10
2011-03-23T13:56:57Z
[ "python", "html", "string" ]
I have an html file and I want to replace the empty paragraphs with a space. ``` mystring = "This <p></p><p>is a test</p><p></p><p></p>" result = mystring.sub("<p></p>" , "&nbsp;") ``` This is not working.
Please, [don't try to parse HTML with regular expressions](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454). Use a proper parsing module, like `htmlparser` or `BeautifulSoup` to achieve this. "Suffer" a short learning curve now and benefit: 1. Your pars...
How to wrap an init/cleanup function in Boost python
5,406,334
5
2011-03-23T13:56:28Z
5,406,938
8
2011-03-23T14:41:00Z
[ "c++", "python", "boost-python" ]
I recently discovered the existence of boost-python and was astonished by it's apparent simplicity. I wanted to give it a try and started to wrap an existing C++ library. While wrapping the basic library API calls is quite simple (nothing special, just regular function calls and very common parameters), I don't know h...
You could try to do a guard object and assign it to a hidden attribute of your module. ``` struct MyLibGuard { MyLibGuard() { myLib::initialize();} ~MyLibGuard() { myLib::cleanup();} }; using namespace boost::python; BOOST_PYTHON_MODULE(arch_lib) { boost::shared_ptr<MyLibGuard> libGuard = new MyLibGuard(...
Is there any adequate scaffolding for Django? (A la Ruby on Rails)
5,406,460
22
2011-03-23T14:06:34Z
5,696,465
15
2011-04-17T21:10:19Z
[ "python", "django", "scaffolding" ]
Is there any adequate [scaffolding](http://en.wikipedia.org/wiki/Scaffold_%28programming%29) for Django? It may be in the newly released 1.3 version, but I haven't found it yet.
I've looked and not yet found something for Django quite like the Rails Generate command. Django has a bit of a different philosophy. It gives you tools to make doing things easily but doesn't actually do it for you (except the admin interface). In the grand scheme of things, I think this is OK. When I use rails' scaff...
Is there any adequate scaffolding for Django? (A la Ruby on Rails)
5,406,460
22
2011-03-23T14:06:34Z
6,901,691
7
2011-08-01T16:46:19Z
[ "python", "django", "scaffolding" ]
Is there any adequate [scaffolding](http://en.wikipedia.org/wiki/Scaffold_%28programming%29) for Django? It may be in the newly released 1.3 version, but I haven't found it yet.
So Django 1.3 still lacks 'scaffold' functionality. Not good. What is best in scaffold, is that it allows developer to immediately start with the project, without recalling all 'models', 'urls' and 'views' syntaxes. Look at this example, let's start new project and app: ``` $django-admin startproject mysite $python m...
Python decodes JSON
5,407,072
2
2011-03-23T14:50:45Z
5,407,096
7
2011-03-23T14:52:26Z
[ "python", "json", "python-3.x" ]
I've the following json: ``` { "slate" : { "id" : { "type" : "integer" }, "name" : { "type" : "string" }, "code" : { "type" : "integer", "fk" : "banned.id" } }, "banned" : { "id" : { "type" :...
Try ``` obj = json.loads(jstr) ``` instead of ``` obj = json.JSONDecoder(jstr) ```
Python decodes JSON
5,407,072
2
2011-03-23T14:50:45Z
5,407,268
7
2011-03-23T15:04:01Z
[ "python", "json", "python-3.x" ]
I've the following json: ``` { "slate" : { "id" : { "type" : "integer" }, "name" : { "type" : "string" }, "code" : { "type" : "integer", "fk" : "banned.id" } }, "banned" : { "id" : { "type" :...
You seem to need help iterating over the returned object, as well as decoding the JSON. ``` import json #jstr = "... that thing above ..." # This line only decodes the JSON into a structure in memory: obj = json.loads(jstr) # obj, in this case, is a dictionary, a built-in Python type. # These lines just iterate over...
Irrational number representation in any programming language?
5,407,286
8
2011-03-23T15:04:46Z
5,407,313
7
2011-03-23T15:07:09Z
[ "java", "c++", "python", "ruby", "numbers" ]
Does anyone know of an irrational number representation type/object/class/whatever in *any* programming language? All suggestions welcome. Simply put, if I have two irrational objects, both representing the square root of five, and I multiply those objects, I want to get back the integer five, not float 4 point lots ...
You could try [sympy](http://code.google.com/p/sympy/) since you appear to be after symbolic computation and are amenable to using Python.
Irrational number representation in any programming language?
5,407,286
8
2011-03-23T15:04:46Z
5,407,323
14
2011-03-23T15:08:11Z
[ "java", "c++", "python", "ruby", "numbers" ]
Does anyone know of an irrational number representation type/object/class/whatever in *any* programming language? All suggestions welcome. Simply put, if I have two irrational objects, both representing the square root of five, and I multiply those objects, I want to get back the integer five, not float 4 point lots ...
What you are looking for is called symbolic mathematics. You might want to try some computer algebra system like Maxima, Maple or Mathematica. There are also libraries for this purpose, for example the [SymPy](http://code.google.com/p/sympy/) library for Python.
Distance formula between two points in a list
5,407,969
11
2011-03-23T15:50:29Z
5,408,077
19
2011-03-23T15:58:42Z
[ "python", "math" ]
I need to take a list I have created and find the closest two points and print them out. How can I go about comparing each point in the list? There isn't any need to plot or anything, just compare the points and find the closest two in the list. ``` import math # 'math' needed for 'sqrt' # Distance function def dist...
It is more convenient to rewrite your `distance()` function to take two `(x, y)` tuples as parameters: ``` def distance(p0, p1): return math.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2) ``` Now you want to iterate over all pairs of points from your list `fList`. The function `iterools.combinations()` is handy fo...
Google app engine static file handlers example
5,408,255
7
2011-03-23T16:10:38Z
5,408,374
12
2011-03-23T16:18:55Z
[ "python", "google-app-engine" ]
The [static\_dir](http://code.google.com/appengine/docs/python/config/appconfig.html#Static_Directory_Handlers) examples are pretty clear So for example, I want requests to `http://mysite.appengine.com/main.htm` to go to the `C:\<appenginesiteroot>\html\main.htm` file (on the hard disk), and this can be achieved with ...
`script` is for scripts, you are trying to map to a static file. Have you looked at the [Static File Pattern Handlers](http://code.google.com/appengine/docs/python/config/appconfig.html#Static_File_Pattern_Handlers) section of the doc? Have you tried: ``` - url: / static_files: main.html upload: main.html ```
Sampling uniformly distributed random points inside a spherical volume
5,408,276
20
2011-03-23T16:11:51Z
5,408,344
12
2011-03-23T16:16:46Z
[ "python", "matlab", "geometry", "random-sample", "uniform-distribution" ]
I am looking to be able to generate a random uniform sample of particle locations that fall within a spherical volume. The image below (courtesy of <http://nojhan.free.fr/metah/>) shows what I am looking for. This is a slice through the sphere, showing a uniform distribution of points: ![Uniformly distributed circle]...
Generate a set of points uniformly distributed within a cube, then discard the ones whose distance from the center exceeds the radius of the desired sphere.
Sampling uniformly distributed random points inside a spherical volume
5,408,276
20
2011-03-23T16:11:51Z
5,408,843
21
2011-03-23T16:55:02Z
[ "python", "matlab", "geometry", "random-sample", "uniform-distribution" ]
I am looking to be able to generate a random uniform sample of particle locations that fall within a spherical volume. The image below (courtesy of <http://nojhan.free.fr/metah/>) shows what I am looking for. This is a slice through the sphere, showing a uniform distribution of points: ![Uniformly distributed circle]...
While I prefer the discarding method for spheres, for completeness [I offer the exact solution](http://stackoverflow.com/questions/918736/random-number-generator-that-produces-a-power-law-distribution/918782#918782). In spherical coordinates, taking advantage of the [sampling rule](http://stackoverflow.com/questions/2...
Sampling uniformly distributed random points inside a spherical volume
5,408,276
20
2011-03-23T16:11:51Z
23,785,326
7
2014-05-21T13:54:22Z
[ "python", "matlab", "geometry", "random-sample", "uniform-distribution" ]
I am looking to be able to generate a random uniform sample of particle locations that fall within a spherical volume. The image below (courtesy of <http://nojhan.free.fr/metah/>) shows what I am looking for. This is a slice through the sphere, showing a uniform distribution of points: ![Uniformly distributed circle]...
There is a brilliant way to generate uniformly points on sphere in n-dimensional space, and you have pointed this in your question (I mean MATLAB code). Why does it work? The answer is: let us look at the probability density of n-dimensional normal distribution. It is equal (up to constant) exp(-x\_1\*x\_1/2) \*exp(-...
How to read/make sense of a PHP serialised data string in python
5,408,599
4
2011-03-23T16:35:13Z
5,408,685
12
2011-03-23T16:41:40Z
[ "python", "django", "serialization" ]
A legacy database I'm accessing via Django has a table column that stores serialised data in the following string format: ``` a:5:{i:1;s:4:"1869";i:2;s:4:"1859";i:3;s:4:"1715";i:4;s:1:"0";i:5;s:1:"0";} ``` Is there any way I can use python/python-library to change it into a list or any other friendly python data type...
[phpserialize](http://pypi.python.org/pypi/phpserialize): > a port of the `serialize` and `unserialize` functions of php to python. This module implements the python serialization interface (eg: provides *dumps*, *loads* and similar functions)...
Python Raytracing
5,408,669
5
2011-03-23T16:39:50Z
5,408,807
7
2011-03-23T16:51:18Z
[ "python", "vector", "raytracing" ]
I'm building a simple Python raytracer with pure Python (just for the heck of it), but I've hit a roadblock. The setup of my scene is currently this: 1. Camera located at `0, -10, 0` pointing along the *y*-axis. 2. Sphere with radius `1` located at `0, 0, 0`. 3. Imaging plane-thing is a distance of `1` away from the ...
Are you normalising the ray's direction vector?
Matplotlib Unicode axis labels using the Cairo renderer
5,408,862
5
2011-03-23T16:56:47Z
5,408,986
7
2011-03-23T17:07:30Z
[ "python", "unicode", "matplotlib", "label" ]
I'm trying to generate a plot using Matplotlib with a non-Latin character (a "μ") in an axis label, like this: ``` matplotlib.pyplot.xlabel(u'Sarcomere Length (μm)') ``` I'm using the Cairo renderer on Linux and I'm getting a "box" instead of "μ": ![Incorrect Axis Label](http://i.stack.imgur.com/MzZBw.png) It wo...
It's a font problem. Whatever font you have set as matplotlib's default doesn't have that particular character. There are a number of ways to potentially fix this, but it's going to be fairly system dependent. (It may be as simple as ensuring that you have the appropriate font package installed.) You can set the fonts...