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
Changing user agent on urllib2.urlopen
802,134
75
2009-04-29T12:32:36Z
10,468,884
8
2012-05-06T07:19:05Z
[ "python", "urllib2", "user-agent" ]
How can I download a webpage with a user agent other than the default one on urllib2.urlopen?
For python 3, urllib is split into 3 modules... ``` import urllib.request req = urllib.request.Request(url="http://localhost/",data=b'None',headers={'User-Agent':' Mozilla/5.0 (Windows NT 6.1; WOW64; rv:12.0) Gecko/20100101 Firefox/12.0'}) handler = urllib.request.urlopen(req) ```
Face-tracking libraries for Java or Python
802,243
8
2009-04-29T12:55:12Z
802,381
7
2009-04-29T13:32:51Z
[ "java", "python", "face-detection" ]
I'm looking for a way to identify faces (not specific people, just where the faces are) and track them as they move across a room. We're trying to measure walking speed for people, and I assumed this would be the easiest way of identifying a person as a person. We'll have a reasonably fast camera for the project, so I...
Checkout [OpenCV Python Interface](http://opencv.willowgarage.com/wiki/PythonInterface)
How can I enumerate/list all installed applications in Windows XP?
802,499
6
2009-04-29T14:02:12Z
802,510
10
2009-04-29T14:05:59Z
[ "c++", "python", "winapi", "enumeration" ]
When I say "installed application", I basically mean any application visible in [Control Panel]->[Add/Remove Programs]. I would prefer to do it in Python, but C or C++ is also fine.
Check out the [Win32\_Product](http://msdn.microsoft.com/en-us/library/aa394378%28VS.85%29.aspx) WMI (Windows Management Instrumentation) class. [Here's a tutorial](http://timgolden.me.uk/python/wmi.html) on using WMI in Python.
How can I enumerate/list all installed applications in Windows XP?
802,499
6
2009-04-29T14:02:12Z
802,513
10
2009-04-29T14:06:25Z
[ "c++", "python", "winapi", "enumeration" ]
When I say "installed application", I basically mean any application visible in [Control Panel]->[Add/Remove Programs]. I would prefer to do it in Python, but C or C++ is also fine.
If you mean the list of installed applications that is shown in Add\Remove Programs in the control panel, you can find it in the registry key: ``` HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall ``` [more info about how the registry tree is structured can be found here](http://support.microsoft...
How can I enumerate/list all installed applications in Windows XP?
802,499
6
2009-04-29T14:02:12Z
803,056
7
2009-04-29T15:57:31Z
[ "c++", "python", "winapi", "enumeration" ]
When I say "installed application", I basically mean any application visible in [Control Panel]->[Add/Remove Programs]. I would prefer to do it in Python, but C or C++ is also fine.
Control Panel uses Win32 COM api, which is the official method (see Google Groups, Win32) Never rely on registry.
`final` keyword equivalent for variables in Python?
802,578
25
2009-04-29T14:21:07Z
802,622
7
2009-04-29T14:29:04Z
[ "java", "python", "keyword", "final" ]
I couldn't find documentation on an equivalent of Java's `final` in Python, is there such a thing? I'm creating a snapshot of an object (used for restoration if anything fails); once this backup variable is assigned, it should not be modified -- a final-like feature in Python would be nice for this.
There is no such thing. In general, the Python attitude is "if you don't want this modified, just don't modify it". Clients of an API are unlikely to just poke around your undocumented internals anyway. You could, I suppose, work around this by using tuples or namedtuples for the relevant bits of your model, which are...
`final` keyword equivalent for variables in Python?
802,578
25
2009-04-29T14:21:07Z
802,631
43
2009-04-29T14:30:34Z
[ "java", "python", "keyword", "final" ]
I couldn't find documentation on an equivalent of Java's `final` in Python, is there such a thing? I'm creating a snapshot of an object (used for restoration if anything fails); once this backup variable is assigned, it should not be modified -- a final-like feature in Python would be nice for this.
There is no ``final'' equivalent in Python. But, to create read-only fields of class instances, you can use the [property](http://docs.python.org/3.0/library/functions.html#property) function. **Edit**: perhaps you want something like this: ``` class WriteOnceReadWhenever: def __setattr__(self, attr, value): ...
`final` keyword equivalent for variables in Python?
802,578
25
2009-04-29T14:21:07Z
802,642
37
2009-04-29T14:32:44Z
[ "java", "python", "keyword", "final" ]
I couldn't find documentation on an equivalent of Java's `final` in Python, is there such a thing? I'm creating a snapshot of an object (used for restoration if anything fails); once this backup variable is assigned, it should not be modified -- a final-like feature in Python would be nice for this.
Having a variable in Java be `final` basically means that once you assign to a variable, you may not reassign that variable to point to another object. It actually doesn't mean that the object can't be modified. For example, the following Java code works perfectly well: ``` public final List<String> messages = new Lin...
`final` keyword equivalent for variables in Python?
802,578
25
2009-04-29T14:21:07Z
802,679
8
2009-04-29T14:41:33Z
[ "java", "python", "keyword", "final" ]
I couldn't find documentation on an equivalent of Java's `final` in Python, is there such a thing? I'm creating a snapshot of an object (used for restoration if anything fails); once this backup variable is assigned, it should not be modified -- a final-like feature in Python would be nice for this.
An assign-once variable is a design issue. You design your application in a way that the variable is set once and once only. However, if you want run-time checking of your design, you can do it with a wrapper around the object. ``` class OnePingOnlyPleaseVassily( object ): def __init__( self ): self.value...
Python - Possible to force raise exceptions regardless try/except blocks?
802,804
5
2009-04-29T15:06:40Z
802,826
12
2009-04-29T15:12:16Z
[ "python", "exception" ]
In Python is there any language (or interpreter) feature to force the python interpreter to always raise exceptions even if the exception offending code is inside a try/except block ? I've just inherited a larger and old codebase written in python, whose purpose is to communicate with some custom designed hardware we ...
The "all-exceptions" `except:` block is a remarkably bad thing and must simply be found and replaced with sensible except handling. In this case `grep` is your friend. A good IDE can help make these unpleasant chores manageable. But there's no "ignore the code as written" option in Python.
Getting realtime output using subprocess
803,265
64
2009-04-29T16:45:48Z
803,396
11
2009-04-29T17:21:10Z
[ "python", "subprocess" ]
I am trying to write a wrapper script for a command line program (svnadmin verify) that will display a nice progress indicator for the operation. This requires me to be able to see each line of output from the wrapped program as soon as it is output. I figured that I'd just execute the program using subprocess.Popen, ...
You can try this: ``` import subprocess import sys process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) while True: out = process.stdout.read(1) if out == '' and process.poll() != None: break if out != '': sys.stdout.write(out) sys.stdout.flush() ``` If yo...
Getting realtime output using subprocess
803,265
64
2009-04-29T16:45:48Z
803,421
43
2009-04-29T17:26:53Z
[ "python", "subprocess" ]
I am trying to write a wrapper script for a command line program (svnadmin verify) that will display a nice progress indicator for the operation. This requires me to be able to see each line of output from the wrapped program as soon as it is output. I figured that I'd just execute the program using subprocess.Popen, ...
I tried this, and for some reason while the code ``` for line in p.stdout: ... ``` buffers aggressively, the variant ``` while True: line = p.stdout.readline() if not line: break ... ``` does not. Apparently this is a known bug: <http://bugs.python.org/issue3907>
Getting realtime output using subprocess
803,265
64
2009-04-29T16:45:48Z
6,414,278
21
2011-06-20T16:13:51Z
[ "python", "subprocess" ]
I am trying to write a wrapper script for a command line program (svnadmin verify) that will display a nice progress indicator for the operation. This requires me to be able to see each line of output from the wrapped program as soon as it is output. I figured that I'd just execute the program using subprocess.Popen, ...
``` p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1) for line in iter(p.stdout.readline, b''): print line, p.stdout.close() p.wait() ```
Passing functions with arguments to another function in Python?
803,616
98
2009-04-29T18:24:26Z
803,626
56
2009-04-29T18:27:44Z
[ "python", "function" ]
Is it possible to pass functions with arguments to another function in Python? Say for something like: ``` def Perform ( function ) : function ``` but the functions to be passed will be like: ``` Action1() Action2(p) Action3(p,r) ```
This is what lambda is for: ``` def Perform(f): f() Perform(lambda: Action1()) Perform(lambda: Action2(p)) Perform(lambda: Action3(p, r)) ```
Passing functions with arguments to another function in Python?
803,616
98
2009-04-29T18:24:26Z
803,632
155
2009-04-29T18:28:24Z
[ "python", "function" ]
Is it possible to pass functions with arguments to another function in Python? Say for something like: ``` def Perform ( function ) : function ``` but the functions to be passed will be like: ``` Action1() Action2(p) Action3(p,r) ```
Do you mean this? ``` def perform( fun, *args ): fun( *args ) def action1( args ): something def action2( args ): something perform( action1 ) perform( action2, p ) perform( action3, p, r ) ```
Passing functions with arguments to another function in Python?
803,616
98
2009-04-29T18:24:26Z
803,668
13
2009-04-29T18:36:14Z
[ "python", "function" ]
Is it possible to pass functions with arguments to another function in Python? Say for something like: ``` def Perform ( function ) : function ``` but the functions to be passed will be like: ``` Action1() Action2(p) Action3(p,r) ```
Use functools.partial, not lambdas! And ofc Perform is a useless function, you can pass around functions directly. ``` for func in [Action1, partial(Action2, p), partial(Action3, p, r)]: func() ```
Passing functions with arguments to another function in Python?
803,616
98
2009-04-29T18:24:26Z
804,346
17
2009-04-29T21:23:23Z
[ "python", "function" ]
Is it possible to pass functions with arguments to another function in Python? Say for something like: ``` def Perform ( function ) : function ``` but the functions to be passed will be like: ``` Action1() Action2(p) Action3(p,r) ```
You can use the partial function from functools like so. ``` from functools import partial def perform(f): f() perform(Action1) perform(partial(Action2, p)) perform(partial(Action3, p, r)) ``` Also works with keywords ``` perform(partial(Action4, param1=p)) ```
Best way to convert a Unicode URL to ASCII (UTF-8 percent-escaped) in Python?
804,336
26
2009-04-29T21:21:25Z
804,380
43
2009-04-29T21:36:32Z
[ "python", "url", "unicode", "utf-8" ]
I'm wondering what's the best way -- or if there's a simple way with the standard library -- to convert a URL with Unicode chars in the domain name and path to the equivalent ASCII URL, encoded with domain as IDNA and the path %-encoded, as per RFC 3986. I get from the user a URL in UTF-8. So if they've typed in `http...
## Code: ``` import urlparse, urllib def fixurl(url): # turn string into unicode if not isinstance(url,unicode): url = url.decode('utf8') # parse it parsed = urlparse.urlsplit(url) # divide the netloc further userpass,at,hostport = parsed.netloc.rpartition('@') user,colon1,pass_ ...
Tool to determine what lowest version of Python required?
804,538
46
2009-04-29T22:21:12Z
804,917
8
2009-04-30T00:35:46Z
[ "python", "code-analysis" ]
Is there something similar to Pylint, that will look at a Python script (or run it), and determine which version of Python each line (or function) requires? For example, theoretical usage: ``` $ magic_tool <EOF with something: pass EOF 1: 'with' statement requires Python 2.6 or greater $ magic_tool <EOF class So...
Not an actual useful answer but here it goes anyway. I think this should be doable to make (though probably quite an exercise), for example you could make sure you have all the official grammars for the versions you want to check, like [this one](http://docs.python.org/reference/grammar.html) . Then parse the bit of c...
Tool to determine what lowest version of Python required?
804,538
46
2009-04-29T22:21:12Z
819,645
41
2009-05-04T10:55:39Z
[ "python", "code-analysis" ]
Is there something similar to Pylint, that will look at a Python script (or run it), and determine which version of Python each line (or function) requires? For example, theoretical usage: ``` $ magic_tool <EOF with something: pass EOF 1: 'with' statement requires Python 2.6 or greater $ magic_tool <EOF class So...
Inspired by this excellent question, I recently put together a script that tries to do this. You can find it on github at [pyqver](http://github.com/ghewgill/pyqver/tree/master). It's reasonably complete but there are some aspects that are not yet handled (as mentioned in the README file). Feel free to fork and improv...
How to consume XML from RESTful web services using Django / Python?
804,992
3
2009-04-30T01:13:48Z
804,998
9
2009-04-30T01:19:00Z
[ "python", "xml", "django", "rest" ]
Should I use PyXML or what's in the standard library?
ElementTree is provided as part of the standard Python libs. ElementTree is pure python, and cElementTree is the faster C implementation: ``` # Try to use the C implementation first, falling back to python try: from xml.etree import cElementTree as ElementTree except ImportError, e: from xml.etree import Eleme...
Call a parent class's method from child class in Python?
805,066
271
2009-04-30T01:52:31Z
805,081
328
2009-04-30T01:58:28Z
[ "python", "inheritance", "class", "object" ]
When creating a simple object hierarchy in Python, I'd like to be able to invoke methods of the parent class from a derived class. In Perl and Java, there is a keyword for this (super). In Perl, I might do this: ``` package Foo; sub frotz { return "Bamf"; } package Bar; @ISA = qw(Foo); sub frotz { my $str = ...
Yes, but only with [new-style classes](http://docs.python.org/glossary.html#term-new-style-class). Use the [`super()`](http://docs.python.org/library/functions.html#super) function: ``` class Foo(Bar): def baz(self, arg): return super(Foo, self).baz(arg) ```
Call a parent class's method from child class in Python?
805,066
271
2009-04-30T01:52:31Z
805,082
46
2009-04-30T01:58:31Z
[ "python", "inheritance", "class", "object" ]
When creating a simple object hierarchy in Python, I'd like to be able to invoke methods of the parent class from a derived class. In Perl and Java, there is a keyword for this (super). In Perl, I might do this: ``` package Foo; sub frotz { return "Bamf"; } package Bar; @ISA = qw(Foo); sub frotz { my $str = ...
Python also has [super](http://docs.python.org/library/functions.html) as well: `super(type[, object-or-type])` > Return a proxy object that delegates method calls to a parent or sibling class of type. > This is useful for accessing inherited methods that have been overridden in a class. > The search order is same as...
Call a parent class's method from child class in Python?
805,066
271
2009-04-30T01:52:31Z
805,085
9
2009-04-30T01:58:46Z
[ "python", "inheritance", "class", "object" ]
When creating a simple object hierarchy in Python, I'd like to be able to invoke methods of the parent class from a derived class. In Perl and Java, there is a keyword for this (super). In Perl, I might do this: ``` package Foo; sub frotz { return "Bamf"; } package Bar; @ISA = qw(Foo); sub frotz { my $str = ...
There's a super() in Python too. It's a bit wonky, because of Python's old- and new-style classes, but is quite commonly used e.g. in constructors: ``` class Foo(Bar): def __init__(self): super(Foo, self).__init__() self.baz = 5 ```
Call a parent class's method from child class in Python?
805,066
271
2009-04-30T01:52:31Z
805,091
50
2009-04-30T02:02:38Z
[ "python", "inheritance", "class", "object" ]
When creating a simple object hierarchy in Python, I'd like to be able to invoke methods of the parent class from a derived class. In Perl and Java, there is a keyword for this (super). In Perl, I might do this: ``` package Foo; sub frotz { return "Bamf"; } package Bar; @ISA = qw(Foo); sub frotz { my $str = ...
``` ImmediateParentClass.frotz(self) ``` will be just fine, whether the immediate parent class defined `frotz` itself or inherited it. `super` is only needed for proper support of *multiple* inheritance (and then it only works if every class uses it properly). In general, `AnyClass.whatever` is going to look up `whate...
Call a parent class's method from child class in Python?
805,066
271
2009-04-30T01:52:31Z
16,057,968
17
2013-04-17T10:44:59Z
[ "python", "inheritance", "class", "object" ]
When creating a simple object hierarchy in Python, I'd like to be able to invoke methods of the parent class from a derived class. In Perl and Java, there is a keyword for this (super). In Perl, I might do this: ``` package Foo; sub frotz { return "Bamf"; } package Bar; @ISA = qw(Foo); sub frotz { my $str = ...
Here is an example of using **super()**: ``` #New-style classes inherit from object, or from another new-style class class Dog(object): name = '' moves = [] def __init__(self, name): self.name = name def moves_setup(self): self.moves.append('walk') self.moves.append('run') ...
What is the best way to access stored procedures in Django's ORM
805,393
17
2009-04-30T05:03:05Z
805,423
15
2009-04-30T05:16:28Z
[ "python", "sql", "django", "stored-procedures", "django-models" ]
I am designing a fairly complex database, and know that some of my queries will be far outside the scope of Django's ORM. Has anyone integrated SP's with Django's ORM successfully? If so, what RDBMS and how did you do it?
You have to use the connection utility in Django: ``` from django.db import connection cursor = connection.cursor() cursor.execute("SQL STATEMENT CAN BE ANYTHING") ``` then you can fetch the data: ``` cursor.fetchone() ``` or: ``` cursor.fetchall() ``` More info here: <http://docs.djangoproject.com/en/dev/topics...
What is the best way to access stored procedures in Django's ORM
805,393
17
2009-04-30T05:03:05Z
820,130
15
2009-05-04T13:36:05Z
[ "python", "sql", "django", "stored-procedures", "django-models" ]
I am designing a fairly complex database, and know that some of my queries will be far outside the scope of Django's ORM. Has anyone integrated SP's with Django's ORM successfully? If so, what RDBMS and how did you do it?
We (musicpictures.com / eviscape.com) wrote that django snippet but its not the whole story (actually that code was only tested on Oracle at that time). Stored procedures make sense when you want to reuse tried and tested SP code or where one SP call will be faster than multiple calls to the database - or where securi...
How to get field names when running plain sql query in django
805,660
5
2009-04-30T06:49:33Z
805,778
7
2009-04-30T07:30:21Z
[ "python", "django" ]
In one of my django views I query database using plain sql (not orm) and return results. ``` sql = "select * from foo_bar" cursor = connection.cursor() cursor.execute(sql) rows = cursor.fetchall() ``` I am getting the data fine, but not the column names. How can I get the field names of the result set that is returne...
According to [PEP 249](http://www.python.org/dev/peps/pep-0249/), you can try using `cursor.description`, but this is not entirely reliable.
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
19
2009-04-30T08:43:03Z
806,004
20
2009-04-30T09:00:35Z
[ "php", "c++", "python", "perl", "fastcgi" ]
What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks).
Several years ago, I more or less learned web app programming on the job. C was the main language I knew, so I wrote the (fairly large-scale) web app in C. Bad mistake. C's string handling and memory management is tedious, and together with my lack of experience in web apps, it quickly became a hard-to-maintain project...
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
19
2009-04-30T08:43:03Z
806,037
11
2009-04-30T09:08:44Z
[ "php", "c++", "python", "perl", "fastcgi" ]
What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks).
Using C++ is likely to result in a radically faster application than PHP, Perl or Python and somewhat faster than C# or Java - unless it spends most of its time waiting for the DB, in which case there won't be a difference. This is actually the most common case. On the other hand, due to the reasons benhoyt mentioned,...
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
19
2009-04-30T08:43:03Z
806,135
8
2009-04-30T09:39:25Z
[ "php", "c++", "python", "perl", "fastcgi" ]
What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks).
I think that someone should be a pioneer in Webapp/C++ topic, to test the ground and provide proof of concept solutions. With arrival of STL and development of Boost parsing text happened to be extremely easy with C++. Two years ago, if I would have to parse CSV data I would use Python or PHP. Now I use C++ with STL/B...
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
19
2009-04-30T08:43:03Z
806,195
30
2009-04-30T09:54:56Z
[ "php", "c++", "python", "perl", "fastcgi" ]
What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks).
scripting languages may be slower than C, but is this a problem? almost never. and if the performance becomes a problem, you start to translate only the critical parts. twitter/ruby is a good example; ruby is slow. some of the language features (that make ruby nice in the first place) just prevent different kinds of o...
FastCGI C++ vs. A Script Language (PHP/Python/Perl)
805,957
19
2009-04-30T08:43:03Z
806,293
7
2009-04-30T10:21:35Z
[ "php", "c++", "python", "perl", "fastcgi" ]
What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job. Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks).
The question is "where's the value created?" If you think the value is created in Memory management, careful class design and getting the nightly build to work, then use C++. You'll get to spend lots of time writing a lot of code to do important things like deleting objects that are no longer referenced. If you think...
How to hash a large object (dataset) in Python?
806,151
25
2009-04-30T09:43:57Z
806,342
23
2009-04-30T10:42:19Z
[ "python", "hash", "numpy", "sha1", "pickle" ]
I would like to calculate a hash of a Python class containing a dataset for Machine Learning. The hash is meant to be used for caching, so I was thinking of `md5` or `sha1`. The problem is that most of the data is stored in NumPy arrays; these do not provide a `__hash__()` member. Currently I do a `pickle.dumps()` for ...
Thanks to John Montgomery I think I have found a solution, and I think it has less overhead than converting every number in possibly *huge* arrays to strings: I can create a byte-view of the arrays and use these to update the hash. And somehow this seems to give the same digest as directly updating using the array: `...
Django: Redirect to previous page after login
806,835
129
2009-04-30T13:14:14Z
806,912
13
2009-04-30T13:30:58Z
[ "python", "django" ]
I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user shou...
Django's built-in authentication works the way you want. Their login pages include a `next` query string which is the page to return to after login. Look at <http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.decorators.login_required>
Django: Redirect to previous page after login
806,835
129
2009-04-30T13:14:14Z
808,096
24
2009-04-30T17:22:31Z
[ "python", "django" ]
I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user shou...
This may not be a "best practice", but I've successfully used this before: ``` return HttpResponseRedirect(request.META.get('HTTP_REFERER','/')) ```
Django: Redirect to previous page after login
806,835
129
2009-04-30T13:14:14Z
1,711,592
105
2009-11-10T22:09:23Z
[ "python", "django" ]
I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user shou...
You do not need to make an extra view for this, the functionality is already built in. First each page with a login link needs to know the current path, and the easiest way is to add the request context preprosessor to settings.py (the 4 first are default), then the request object will be available in each request: *...
Django: Redirect to previous page after login
806,835
129
2009-04-30T13:14:14Z
13,595,154
17
2012-11-27T23:33:01Z
[ "python", "django" ]
I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user shou...
To support full urls with param/values you'd need: ``` ?next={{ request.get_full_path|urlencode }} ``` instead of just: ``` ?next={{ request.path }} ```
Python equivalent of Perl's while (<>) {...}?
807,173
20
2009-04-30T14:23:46Z
807,190
48
2009-04-30T14:26:51Z
[ "python", "stdin" ]
I write a lot of little scripts that process files on a line-by-line basis. In Perl, I use ``` while (<>) { do stuff; } ``` This is handy because it doesn't care where the input comes from (a file or stdin). In Python I use this ``` if len(sys.argv) == 2: # there's a command line argument sys.stdin = file(s...
The fileinput module in the standard library is just what you want: ``` import fileinput for line in fileinput.input(): ... ```
Python equivalent of Perl's while (<>) {...}?
807,173
20
2009-04-30T14:23:46Z
807,196
15
2009-04-30T14:27:48Z
[ "python", "stdin" ]
I write a lot of little scripts that process files on a line-by-line basis. In Perl, I use ``` while (<>) { do stuff; } ``` This is handy because it doesn't care where the input comes from (a file or stdin). In Python I use this ``` if len(sys.argv) == 2: # there's a command line argument sys.stdin = file(s...
``` import fileinput for line in fileinput.input(): process(line) ``` This iterates over the lines of all files listed in sys.argv[1:], defaulting to sys.stdin if the list is empty.
Python equivalent of Perl's while (<>) {...}?
807,173
20
2009-04-30T14:23:46Z
807,210
7
2009-04-30T14:31:06Z
[ "python", "stdin" ]
I write a lot of little scripts that process files on a line-by-line basis. In Perl, I use ``` while (<>) { do stuff; } ``` This is handy because it doesn't care where the input comes from (a file or stdin). In Python I use this ``` if len(sys.argv) == 2: # there's a command line argument sys.stdin = file(s...
[fileinput](http://docs.python.org/library/fileinput.html) defaults to stdin, so would make it slightly more concise. If you do a lot of command-line stuff, though, this [piping hack](http://code.activestate.com/recipes/276960/) is very neat.
How to output list of floats to a binary file in Python
807,863
17
2009-04-30T16:35:43Z
807,881
9
2009-04-30T16:39:05Z
[ "python", "file-io" ]
I have a list of floating-point values in Python: ``` floats = [3.14, 2.7, 0.0, -1.0, 1.1] ``` I would like to write these values out to a binary file using IEEE 32-bit encoding. What is the best way to do this in Python? My list actually contains about 200 MB of data, so something "not too slow" would be best. Sinc...
See: [Python's struct module](http://docs.python.org/library/struct.html) ``` import struct s = struct.pack('f'*len(floats), *floats) f = open('file','wb') f.write(s) f.close() ```
How to output list of floats to a binary file in Python
807,863
17
2009-04-30T16:35:43Z
808,049
10
2009-04-30T17:12:01Z
[ "python", "file-io" ]
I have a list of floating-point values in Python: ``` floats = [3.14, 2.7, 0.0, -1.0, 1.1] ``` I would like to write these values out to a binary file using IEEE 32-bit encoding. What is the best way to do this in Python? My list actually contains about 200 MB of data, so something "not too slow" would be best. Sinc...
The array module in the standard library may be more suitable for this task than the struct module which everybody is suggesting. Performance with 200 MB of data should be *substantially* better with array. If you'd like to take at a variety of options, try profiling on your system with [something like this](https://g...
How to output list of floats to a binary file in Python
807,863
17
2009-04-30T16:35:43Z
808,139
24
2009-04-30T17:32:59Z
[ "python", "file-io" ]
I have a list of floating-point values in Python: ``` floats = [3.14, 2.7, 0.0, -1.0, 1.1] ``` I would like to write these values out to a binary file using IEEE 32-bit encoding. What is the best way to do this in Python? My list actually contains about 200 MB of data, so something "not too slow" would be best. Sinc...
Alex is absolutely right, it's more efficient to do it this way: ``` from array import array output_file = open('file', 'wb') float_array = array('d', [3.14, 2.7, 0.0, -1.0, 1.1]) float_array.tofile(output_file) output_file.close() ``` And then read the array like that: ``` input_file = open('file', 'r') float_array...
How to output list of floats to a binary file in Python
807,863
17
2009-04-30T16:35:43Z
809,216
7
2009-04-30T21:33:52Z
[ "python", "file-io" ]
I have a list of floating-point values in Python: ``` floats = [3.14, 2.7, 0.0, -1.0, 1.1] ``` I would like to write these values out to a binary file using IEEE 32-bit encoding. What is the best way to do this in Python? My list actually contains about 200 MB of data, so something "not too slow" would be best. Sinc...
I'm not sure how [NumPy](http://numpy.scipy.org/) will compare performance-wise for your application, but it may be worth investigating. Using [NumPy](http://numpy.scipy.org/): ``` from numpy import array a = array(floats,'float32') output_file = open('file', 'wb') a.tofile(output_file) output_file.close() ``` resul...
Creating an interactive shell for .NET apps and embed scripting languages like python/iron python into it
808,692
13
2009-04-30T19:43:36Z
808,701
11
2009-04-30T19:45:40Z
[ "c#", "python", ".net", "ironpython", "python.net" ]
I was learning python using the tutorial that comes with the standard python installation. One of the benefits that the author states about python is "maybe you’ve written a program that could use an extension language, and you don’t want to design and implement a whole new language for your application" - My quest...
This sounds like a great use of [IronPython](http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython). It's fairly easy to set up a simple scripting host from C# to allow calls into IronPython scripts, as well as allowing IronPython to call into your C# code. There are samples and examples on the CodePlex site t...
Python - Threading and a While True Loop
808,746
9
2009-04-30T19:57:07Z
808,820
11
2009-04-30T20:16:46Z
[ "python", "multithreading", "loops" ]
I have a thread that appends rows to self.output and a loop that runs until self.done is True (or the max execution time is reached). Is there a more efficient way to do this other than using a while loop that constantly checks to see if it's done. The while loop causes the CPU to spike to 100% while it's running.. `...
Are your threads appending to self.output here, with your main task consuming them? If so, this is a tailor-made job for [Queue.Queue](http://docs.python.org/library/queue.html). Your code should become something like: ``` import Queue # Initialise queue as: queue = Queue.Queue() Finished = object() # Unique marker...
Django Manager Chaining
809,210
28
2009-04-30T21:33:29Z
813,277
20
2009-05-01T21:04:31Z
[ "python", "django", "django-models", "django-managers" ]
I was wondering if it was possible (and, if so, how) to chain together multiple managers to produce a query set that is affected by both of the individual managers. I'll explain the specific example that I'm working on: I have multiple abstract model classes that I use to provide small, specific functionality to other...
See this snippet on Djangosnippets: <http://djangosnippets.org/snippets/734/> Instead of putting your custom methods in a manager, you subclass the queryset itself. It's very easy and works perfectly. The only issue I've had is with model inheritance, you always have to define the manager in model subclasses (just: "o...
How to calculate cumulative normal distribution in Python
809,362
48
2009-04-30T22:13:11Z
809,402
15
2009-04-30T22:23:28Z
[ "python", "statistics" ]
I am looking for a function in Numpy or Scipy (or any rigorous Python library) that will give me the cumulative normal distribution function in Python.
Adapted from here <http://mail.python.org/pipermail/python-list/2000-June/039873.html> ``` from math import * def erfcc(x): """Complementary error function.""" z = abs(x) t = 1. / (1. + 0.5*z) r = t * exp(-z*z-1.26551223+t*(1.00002368+t*(.37409196+ t*(.09678418+t*(-.18628806+t*(.27886807+ t*(...
How to calculate cumulative normal distribution in Python
809,362
48
2009-04-30T22:13:11Z
809,406
63
2009-04-30T22:24:02Z
[ "python", "statistics" ]
I am looking for a function in Numpy or Scipy (or any rigorous Python library) that will give me the cumulative normal distribution function in Python.
Here's an example: ``` >>> from scipy.stats import norm >>> norm.cdf(1.96) array(0.97500210485177952) ``` If you need the inverse CDF: ``` >>> norm.ppf(norm.cdf(1.96)) array(1.9599999999999991) ```
How to calculate cumulative normal distribution in Python
809,362
48
2009-04-30T22:13:11Z
3,525,548
11
2010-08-19T19:35:08Z
[ "python", "statistics" ]
I am looking for a function in Numpy or Scipy (or any rigorous Python library) that will give me the cumulative normal distribution function in Python.
To build upon Unknown's example, the Python equivalent of the function normdist() implemented in a lot of libraries would be: ``` def normcdf(x, mu, sigma): t = x-mu; y = 0.5*erfcc(-t/(sigma*sqrt(2.0))); if y>1.0: y = 1.0; return y def normpdf(x, mu, sigma): u = (x-mu)/abs(sigma) y = (...
How to calculate cumulative normal distribution in Python
809,362
48
2009-04-30T22:13:11Z
29,273,201
8
2015-03-26T07:40:44Z
[ "python", "statistics" ]
I am looking for a function in Numpy or Scipy (or any rigorous Python library) that will give me the cumulative normal distribution function in Python.
It may be too late to answer the question but since Google still leads people here, I decide to write my solution here. That is, since Python 2.7, the **math** library has integrated the error function **math.erf(x)** The erf() function can be used to compute traditional statistical functions such as the cumulative s...
Any gotchas using unicode_literals in Python 2.6?
809,796
91
2009-05-01T00:56:37Z
826,710
11
2009-05-05T20:09:56Z
[ "python", "unicode", "python-2.6", "unicode-literals" ]
We've already gotten our code base running under Python 2.6. In order to prepare for Python 3.0, we've started adding: ``` from __future__ import unicode_literals ``` into our `.py` files (as we modify them). I'm wondering if anyone else has been doing this and has run into any non-obvious gotchas (perhaps after spen...
I did find that if you add the `unicode_literals` directive you should also add something like: ``` # -*- coding: utf-8 ``` to the first or second line your .py file. Otherwise lines such as: ``` foo = "barré" ``` result in an an error such as: ``` SyntaxError: Non-ASCII character '\xc3' in file mumble.py on li...
Any gotchas using unicode_literals in Python 2.6?
809,796
91
2009-05-01T00:56:37Z
827,449
94
2009-05-05T23:52:06Z
[ "python", "unicode", "python-2.6", "unicode-literals" ]
We've already gotten our code base running under Python 2.6. In order to prepare for Python 3.0, we've started adding: ``` from __future__ import unicode_literals ``` into our `.py` files (as we modify them). I'm wondering if anyone else has been doing this and has run into any non-obvious gotchas (perhaps after spen...
The main source of problems I've had working with unicode strings is when you mix utf-8 encoded strings with unicode ones. For example, consider the following scripts. two.py ``` # encoding: utf-8 name = 'helló wörld from two' ``` one.py ``` # encoding: utf-8 from __future__ import unicode_literals import two na...
Any gotchas using unicode_literals in Python 2.6?
809,796
91
2009-05-01T00:56:37Z
1,789,107
16
2009-11-24T10:10:01Z
[ "python", "unicode", "python-2.6", "unicode-literals" ]
We've already gotten our code base running under Python 2.6. In order to prepare for Python 3.0, we've started adding: ``` from __future__ import unicode_literals ``` into our `.py` files (as we modify them). I'm wondering if anyone else has been doing this and has run into any non-obvious gotchas (perhaps after spen...
Also in 2.6 (before python 2.6.5 RC1+) unicode literals doesn't play nice with keyword arguments ([issue4978](http://bugs.python.org/issue4978)): The following code for example works without unicode\_literals, but fails with TypeError: `keywords must be string` if unicode\_literals is used. ``` >>> def foo(a=None):...
Any gotchas using unicode_literals in Python 2.6?
809,796
91
2009-05-01T00:56:37Z
3,987,102
8
2010-10-21T11:51:19Z
[ "python", "unicode", "python-2.6", "unicode-literals" ]
We've already gotten our code base running under Python 2.6. In order to prepare for Python 3.0, we've started adding: ``` from __future__ import unicode_literals ``` into our `.py` files (as we modify them). I'm wondering if anyone else has been doing this and has run into any non-obvious gotchas (perhaps after spen...
Also take into account that `unicode_literal` will affect `eval()` but not `repr()` (an asymmetric behavior which imho is a bug), i.e. `eval(repr(b'\xa4'))` won't be equal to `b'\xa4'` (as it would with Python 3). Ideally, the following code would be an invariant, which should always work, for all combinations of `uni...
How to work with threads in pygtk
809,818
5
2009-05-01T01:05:26Z
810,854
12
2009-05-01T10:03:37Z
[ "python", "multithreading", "pygtk" ]
I have a problem with threads in pygtk. My application consist of a program that downloads pictures off the internet and then displays it with pygtk. The problem is that in order to do this and keep the GUI responsive, I need to use threads. So I got into a callback after the user clicked on the button "Download pictu...
Your question is a bit vague, and without a reference to your actual code it's hard to speculate what you're doing wrong. So I'll give you some pointers to read, then speculate wildly based on experience. First of all, you seem to think that you can only keep the GUI responsive by using threads. This is not true. You...
Biggest python projects
810,055
13
2009-05-01T03:24:53Z
810,063
30
2009-05-01T03:28:24Z
[ "python" ]
What is the biggest software development team that uses Python? I am wondering how well the dynamic type system scales to large development teams. It's pretty clear that at Google they have C++ and Java codebases with thousands of developers; their use of Python is much smaller. Are there some huge companies that dev...
[Youtube](http://www.youtube.com) is probably the biggest user after Google (and subsequently bought by them). [Reddit](http://www.reddit.com), a digg-like website, is written in Python. [Eve](http://www.eveonline.com/faq/faq%5F07.asp), an MMO with a good chunk written in Python is pretty impressive as well. <http:/...
Biggest python projects
810,055
13
2009-05-01T03:24:53Z
810,240
10
2009-05-01T04:55:05Z
[ "python" ]
What is the biggest software development team that uses Python? I am wondering how well the dynamic type system scales to large development teams. It's pretty clear that at Google they have C++ and Java codebases with thousands of developers; their use of Python is much smaller. Are there some huge companies that dev...
Among many other Python-centered companies, beyond the ones already mentioned by Unknown, I'd mention big pharma firms such as Astra-Zeneca, film studios such as Lucasfilm, and research places such as NASA, Caltech, Lawrence Livermore NRL. Among the sponsors of Pycon Italia Tre (next week in Firenze, IT -- see www.pyc...
Django form field using SelectDateWidget
810,308
6
2009-05-01T05:36:12Z
812,513
9
2009-05-01T18:12:11Z
[ "python", "django", "forms", "widget", "admin" ]
I've installed the latest SVN branch from Django which includes the new forms. I'm trying to use the SelectDateWidget from django.forms.extras.widgets but the field is showing up as a normal DateInput widget. Here is the forms.py from my application: ``` from django import forms from jacob_forms.models import Client ...
The real problem was that SelectDateWidget can't be referenced this way. Changing the code to reference it differently solved my problem: ``` from django.forms import extras ... DOB = forms.DateField(widget=extras.SelectDateWidget) ``` This seems to be a limitation that you can't reference package.package.Class f...
how to manually assign imagefield in Django
811,167
12
2009-05-01T12:32:16Z
811,288
14
2009-05-01T13:13:40Z
[ "python", "django", "django-models" ]
I have a model that has an ImageField. How can I manually assign an imagefile to it? I want it to treat it like any other uploaded file...
See the django docs for [django.core.files.File](http://docs.djangoproject.com/en/dev/ref/files/file/#django.core.files.File.save) Where fd is an open file object: ``` model_instance.image_field.save('filename.jpeg', fd.read(), True) ```
How to scroll automaticaly within a Tkinter message window
811,532
5
2009-05-01T14:16:00Z
811,708
18
2009-05-01T14:50:48Z
[ "python", "qt", "qt4", "tkinter", "ipython" ]
I wrote the following class for producing "monitoring" output within an extra window. 1. Unfortunately it doesn't scroll automatically down to the most recent line. What is wrong? 2. As I also have problems with Tkinter and ipython: how would an equivalent implementation with qt4 look like? Here is the code: ``` imp...
Add a statement `cls.text.see(Tkinter.END)` right after the one calling insert.
Sqlite and Python -- return a dictionary using fetchone()?
811,548
22
2009-05-01T14:19:06Z
811,637
17
2009-05-01T14:37:46Z
[ "python", "database", "sqlite" ]
I'm using sqlite3 in python 2.5. I've created a table that looks like this: ``` create table votes ( bill text, senator_id text, vote text) ``` I'm accessing it with something like this: ``` v_cur.execute("select * from votes") row = v_cur.fetchone() bill = row[0] senator_id = row[1] vote = row[...
The way I've done this in the past: ``` def dict_factory(cursor, row): d = {} for idx,col in enumerate(cursor.description): d[col[0]] = row[idx] return d ``` Then you set it up in your connection: ``` from pysqlite2 import dbapi2 as sqlite conn = sqlite.connect(...) conn.row_factory = dict_factor...
Sqlite and Python -- return a dictionary using fetchone()?
811,548
22
2009-05-01T14:19:06Z
2,526,294
66
2010-03-26T19:51:49Z
[ "python", "database", "sqlite" ]
I'm using sqlite3 in python 2.5. I've created a table that looks like this: ``` create table votes ( bill text, senator_id text, vote text) ``` I'm accessing it with something like this: ``` v_cur.execute("select * from votes") row = v_cur.fetchone() bill = row[0] senator_id = row[1] vote = row[...
There is actually an option for this in sqlite3. Change the `row_factory` member of the connection object to `sqlite3.Row`: ``` conn = sqlite3.connect('db', row_factory=sqlite3.Row) ``` or ``` conn.row_factory = sqlite3.Row ``` This will allow you to access row elements by name--dictionary-style--or by index. This ...
How can I create a locked-down python environment?
811,670
4
2009-05-01T14:41:58Z
811,711
9
2009-05-01T14:51:10Z
[ "python", "windows", "security", "excel" ]
I'm responsible for developing a large Python/Windows/Excel application used by a financial institution which has offices all round the world. Recently the regulations in one country have changed, and as a result we have been told that we need to create a "locked-down" version of our distribution. After some frustrati...
"reasonably safe" defined arbitrarily as "safer than Excel and VBA". You can't win that fight. Because the fight is over the wrong thing. Anyone can use any EXE or DLL. You need to define "locked down" differently -- in a way that you can succeed. You need to define "locked down" as "cannot change the .PY files" or ...
How many times was logging.error() called?
812,477
7
2009-05-01T18:00:09Z
812,714
9
2009-05-01T18:51:37Z
[ "python", "logging" ]
Maybe it's just doesn't exist, as I cannot find it in pydoc. But using python's logging package, is there a way to query a Logger to find out how many times a particular function was called? For example, how many errors/warnings were reported?
The logging module doesn't appear to support this. In the long run you'd probably be better off creating a new module, and adding this feature via sub-classing the items in the existing logging module to add the features you need, but you could also achieve this behavior pretty easily with a decorator: ``` class callc...
Python's bz2 module not compiled by default
812,781
22
2009-05-01T19:03:50Z
813,112
28
2009-05-01T20:24:55Z
[ "python", "c", "compiler-construction" ]
It seems that Python 2.6.1 doesn't compile bz2 library by default from source. I don't have lib-dynload/bz2.so What's the quickest way to add it (without installing Python from scratch)? OS is Linux 2.4.32-grsec+f6b+gr217+nfs+a32+fuse23+tg+++opt+c8+gr2b-v6.194 #1 SMP Tue Jun 6 15:52:09 PDT 2006 i686 GNU/Linux IIRC ...
You need libbz2.so (the general purpose libbz2 library) properly installed first, for Python to be able to build its own interface to it. That would typically be from a package in your Linux distro likely to have "libbz2" and "dev" in the package name.
Python's bz2 module not compiled by default
812,781
22
2009-05-01T19:03:50Z
813,744
20
2009-05-01T23:52:30Z
[ "python", "c", "compiler-construction" ]
It seems that Python 2.6.1 doesn't compile bz2 library by default from source. I don't have lib-dynload/bz2.so What's the quickest way to add it (without installing Python from scratch)? OS is Linux 2.4.32-grsec+f6b+gr217+nfs+a32+fuse23+tg+++opt+c8+gr2b-v6.194 #1 SMP Tue Jun 6 15:52:09 PDT 2006 i686 GNU/Linux IIRC ...
Use your vendor's package management to add the package that contains the development files for bz2. It's usually a package called "libbz2-dev". E.g. on Ubuntu `sudo apt-get install libbz2-dev`
Python's bz2 module not compiled by default
812,781
22
2009-05-01T19:03:50Z
6,848,047
8
2011-07-27T16:38:23Z
[ "python", "c", "compiler-construction" ]
It seems that Python 2.6.1 doesn't compile bz2 library by default from source. I don't have lib-dynload/bz2.so What's the quickest way to add it (without installing Python from scratch)? OS is Linux 2.4.32-grsec+f6b+gr217+nfs+a32+fuse23+tg+++opt+c8+gr2b-v6.194 #1 SMP Tue Jun 6 15:52:09 PDT 2006 i686 GNU/Linux IIRC ...
If you happen to be trying to compile Python on RHEL5 the package is called **bzip2-devel**, and if you have RHN set up it can be installed with this command: > yum install bzip2-devel Once that is done, you don't need either of the --enable-bz2 or --with-bz2 options, but you might need --enable-shared.
Python's bz2 module not compiled by default
812,781
22
2009-05-01T19:03:50Z
10,972,897
13
2012-06-10T22:37:21Z
[ "python", "c", "compiler-construction" ]
It seems that Python 2.6.1 doesn't compile bz2 library by default from source. I don't have lib-dynload/bz2.so What's the quickest way to add it (without installing Python from scratch)? OS is Linux 2.4.32-grsec+f6b+gr217+nfs+a32+fuse23+tg+++opt+c8+gr2b-v6.194 #1 SMP Tue Jun 6 15:52:09 PDT 2006 i686 GNU/Linux IIRC ...
There are 2 solutions for this trouble: ## option 1. install bzip2-devel On Debian and derivatives, you can install easily like this: ``` sudo apt-get install bzip2-devel ``` ## option 2. build and install bzip2 In the README file of [bzip2 package](http://bzip.org), it is explained that under certain platforms, n...
How to debug wxpython applications?
812,911
18
2009-05-01T19:40:11Z
813,102
8
2009-05-01T20:23:01Z
[ "python", "user-interface", "wxpython" ]
I'm trying wxpython for the first time. I've wrote a GUI for a python program and when I run it, it produces some error in the GUI, but the GUI disappears very quickly, quickly enough for me to be unable to read the error info. Is there any log that I can check for the error message? (I'm running Mac OS X) or any othe...
Here's a way to have the error be reported in the GUI instead of the console, via a MessageDialog. You can use the show\_error() method anywhere an exception is caught, here I just have it being caught at the top-most level. You can change it so that the app continues running after the error occurs, if the error can be...
How to debug wxpython applications?
812,911
18
2009-05-01T19:40:11Z
814,418
14
2009-05-02T08:24:49Z
[ "python", "user-interface", "wxpython" ]
I'm trying wxpython for the first time. I've wrote a GUI for a python program and when I run it, it produces some error in the GUI, but the GUI disappears very quickly, quickly enough for me to be unable to read the error info. Is there any log that I can check for the error message? (I'm running Mac OS X) or any othe...
not sure about the mac version, but wxPython has a built in way to redirect errors to a window (which will unfortunately close when your application crashes, but it's useful for catching errors that silently fail) or to a log file (only updated after your application closes): ``` app = wx.App(redirect=True) app = wx....
Does Python have properties?
813,135
3
2009-05-01T20:32:08Z
813,143
14
2009-05-01T20:34:36Z
[ "python" ]
So something like: ``` vector3.Length ``` that's in fact a function call that calculates the length of the vector, not a variable.
With new-style classes you can use `property()`: <http://www.python.org/download/releases/2.2.3/descrintro/#property>.
Ruby String Translation
813,147
2
2009-05-01T20:35:38Z
813,179
8
2009-05-01T20:43:54Z
[ "python", "ruby", "string" ]
I want to find the successor of each element in my encoded string. For example K->M A->C etc. ``` string.each_char do |ch| dummy_string<< ch.succ.succ end ``` However this method translates y->aa. Is there a method in Ruby that is like maketrans() in Python?
You seem to be looking for [String#tr](http://ruby-doc.org/core/classes/String.html#M000845). Use like this: `some_string.tr('a-zA-Z', 'c-zabC-ZAB')`
Embedding a Python shell inside a Python program
813,571
11
2009-05-01T22:31:41Z
813,593
14
2009-05-01T22:38:19Z
[ "python", "shell" ]
I am making a sort of a science lab in Python, in which the user can create, modify and analyze all sorts of objects. I would like to put a Python shell inside the program, so the user could manipulate the objects through the shell. (Note: He could also manipulate the objects through the usual GUI.) A mockup that illu...
You are looking for [code - Interpreter base classes](http://docs.python.org/library/code.html), particularly code.interact(). Some [examples from effbot](http://effbot.org/librarybook/code.htm).
Embedding a Python shell inside a Python program
813,571
11
2009-05-01T22:31:41Z
814,817
10
2009-05-02T12:48:42Z
[ "python", "shell" ]
I am making a sort of a science lab in Python, in which the user can create, modify and analyze all sorts of objects. I would like to put a Python shell inside the program, so the user could manipulate the objects through the shell. (Note: He could also manipulate the objects through the usual GUI.) A mockup that illu...
Depending on your GUI framework, it may already has been done: * For wxpython, look up "PyCrust" - it's very easy to embed into your app * For PyQt, [pyqtshell](http://code.google.com/p/pyqtshell/) (**Update 29.04.2011:** these days called `spyder`) Here's what I did to embed PyCrust into the application: ``` import...
If I want to use a pylons app with Apache, should I use mod_wsgi or proxy to paste?
813,943
4
2009-05-02T01:37:39Z
814,005
8
2009-05-02T02:26:56Z
[ "python", "apache2", "pylons", "mod-wsgi" ]
Or should I be using a totally different server?
Nginx with mod\_wsgi requires the use of a non-blocking asynchronous framework and setup and isn't likely to work out of box with Pylons. I usually go with the proxy route to a stand-alone Pylons process using the PasteScript#cherrypy WSGI server (as its higher performing than the Paste#http one, though it won't recyc...
Easiest way to rm -rf in Python
814,167
42
2009-05-02T04:52:24Z
814,170
51
2009-05-02T04:54:34Z
[ "python" ]
What is the easiest way to do the equivalent of `rm -rf` in Python?
``` import shutil shutil.rmtree("dir-you-want-to-remove") ```
Easiest way to rm -rf in Python
814,167
42
2009-05-02T04:52:24Z
9,559,881
24
2012-03-04T23:28:12Z
[ "python" ]
What is the easiest way to do the equivalent of `rm -rf` in Python?
While useful, rmtree isn't equivalent: it errors out if you try to remove a single file, which `rm -f` does not (see example below). To get around this, you'll need to check whether your path is a file or a directory, and act accordingly. Something like this should do the trick: ``` import os import shutil def rm_r(...
Python regex parsing
814,786
2
2009-05-02T12:28:13Z
814,797
7
2009-05-02T12:34:08Z
[ "python", "regex" ]
I have an array of strings in python which each string in the array looking something like this: ``` <r n="Foo Bar" t="5" s="10" l="25"/> ``` I have been searching around for a while and the best thing I could find is attempting to modify a HTML hyperlink regex into something that will fit my needs. But not really k...
This will get you most of the way there: ``` >>> print re.findall(r'(\w+)="(.*?)"', string) [('n', 'Foo Bar'), ('t', '5'), ('s', '10'), ('l', '25')] ``` [re.split](http://docs.python.org/library/re.html#re.split) and [re.findall](http://docs.python.org/library/re.html#re.findall) are complementary. Every time your t...
Is there a decorator to simply cache function return values?
815,110
67
2009-05-02T16:15:40Z
815,160
22
2009-05-02T16:42:33Z
[ "python", "caching", "decorator" ]
Consider the following: ``` @property def name(self): if not hasattr(self, '_name'): # expensive calculation self._name = 1 + 1 return self._name ``` I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;) PS the real calculation doesn't depend ...
It sounds like you're **not** asking for a general-purpose memoization decorator (i.e., you're not interested in the general case where you want to cache return values for different argument values). That is, you'd like to have this: ``` x = obj.name # expensive y = obj.name # cheap ``` while a general-purpose memo...
Is there a decorator to simply cache function return values?
815,110
67
2009-05-02T16:15:40Z
5,295,190
8
2011-03-14T05:48:16Z
[ "python", "caching", "decorator" ]
Consider the following: ``` @property def name(self): if not hasattr(self, '_name'): # expensive calculation self._name = 1 + 1 return self._name ``` I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;) PS the real calculation doesn't depend ...
Werkzeug has a `cached_property` decorator ([docs](http://werkzeug.pocoo.org/docs/utils/#werkzeug.utils.cached_property), [source](https://github.com/mitsuhiko/werkzeug/blob/master/werkzeug/utils.py))
Is there a decorator to simply cache function return values?
815,110
67
2009-05-02T16:15:40Z
9,674,327
81
2012-03-12T20:28:46Z
[ "python", "caching", "decorator" ]
Consider the following: ``` @property def name(self): if not hasattr(self, '_name'): # expensive calculation self._name = 1 + 1 return self._name ``` I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;) PS the real calculation doesn't depend ...
Starting from Python 3.2 there is a built-in decorator: [`@functools.lru_cache(maxsize=100, typed=False)`](http://docs.python.org/dev/library/functools.html#functools.lru_cache) > Decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls. It can save time when an expensive ...
Is there a decorator to simply cache function return values?
815,110
67
2009-05-02T16:15:40Z
22,552,713
11
2014-03-21T07:27:09Z
[ "python", "caching", "decorator" ]
Consider the following: ``` @property def name(self): if not hasattr(self, '_name'): # expensive calculation self._name = 1 + 1 return self._name ``` I'm new, but I think the caching could be factored out into a decorator. Only I didn't find one like it ;) PS the real calculation doesn't depend ...
``` class memorize(dict): def __init__(self, func): self.func = func def __call__(self, *args): return self[args] def __missing__(self, key): result = self[key] = self.func(*key) return result ``` Sample uses: ``` >>> @memorize ... def foo(a, b): ... return a * b >>> ...
How to designate unreachable python code
815,310
8
2009-05-02T18:16:06Z
815,320
23
2009-05-02T18:22:36Z
[ "python" ]
What's the pythonic way to designate unreachable code in python as in: ``` gender = readFromDB(...) # either 'm' or 'f' if gender == 'm': greeting = 'Mr.' elif gender == 'f': greeting = 'Ms.' else: # What should this line say? ```
``` raise ValueError('invalid gender %r' % gender) ```
How to designate unreachable python code
815,310
8
2009-05-02T18:16:06Z
815,324
7
2009-05-02T18:23:00Z
[ "python" ]
What's the pythonic way to designate unreachable code in python as in: ``` gender = readFromDB(...) # either 'm' or 'f' if gender == 'm': greeting = 'Mr.' elif gender == 'f': greeting = 'Ms.' else: # What should this line say? ```
This depends on how sure you are of the gender being either `'m'` or `'f'`. If you're absolutely certain, use `if...else` instead of `if...elif...else`. Just makes it easier for everyone. If there's any chance of malformed data, however, you should probably raise an exception to make testing and bug-fixing easier. Yo...
How to designate unreachable python code
815,310
8
2009-05-02T18:16:06Z
815,327
7
2009-05-02T18:24:22Z
[ "python" ]
What's the pythonic way to designate unreachable code in python as in: ``` gender = readFromDB(...) # either 'm' or 'f' if gender == 'm': greeting = 'Mr.' elif gender == 'f': greeting = 'Ms.' else: # What should this line say? ```
You could raise an exception: ``` raise ValueError("Unexpected gender; expected 'm' or 'f', got %s" % gender) ``` or use an assert False if you expect the database to return only 'm' or 'f': ``` assert False, "Unexpected gender; expected 'm' or 'f', got %s" % gender ```
Scientific Plotting in Python
816,086
8
2009-05-03T01:53:32Z
816,115
16
2009-05-03T02:14:07Z
[ "python", "visualization", "plot", "scientific-computing" ]
I have a large data set of tuples containing (time of event, latitude, longitude) that I need to visualize. I was hoping to generate a 'movie'-like xy-plot, but was wondering if anyone has a better idea or if there is an easy way to do this in Python? Thanks in advance for the help, --Leo
get [matplotlib](http://matplotlib.sourceforge.net)
Scientific Plotting in Python
816,086
8
2009-05-03T01:53:32Z
936,552
8
2009-06-01T20:17:06Z
[ "python", "visualization", "plot", "scientific-computing" ]
I have a large data set of tuples containing (time of event, latitude, longitude) that I need to visualize. I was hoping to generate a 'movie'-like xy-plot, but was wondering if anyone has a better idea or if there is an easy way to do this in Python? Thanks in advance for the help, --Leo
The easiest option is matplotlib. Two particular solutions that might work for you are: 1) You can generate a series of plots, each a snapshot at a given time. These can either be displayed as a dynamic plot in matplotlib, where the axes stay the same and the data moves around; or you can save the series of plots to s...
Python/Ruby as mobile OS
816,212
10
2009-05-03T03:09:58Z
816,248
13
2009-05-03T03:26:56Z
[ "python", "ruby", "mobile", "operating-system", "dynamic-languages" ]
I was wondering why smartphone/mobile device OSs are not written to allow dynamic languages as the language of choice? iPhone uses Objective-C, Google Android uses Java, Windows Mobile uses any manner of .NET language. What would be the reasoning behind a mobile OS being written in Python, Ruby, or any other dynamic l...
In general it's all of these things. Memory, speed, and probably most importantly programmer familiarity. Apple has a huge investment in Objective C, Java is known by basically everyone, and C# is very popular as well. If you're trying for mass programmer appeal it makes sense to start with something popular, even if i...
Where is Python's "best ASCII for this Unicode" database?
816,285
66
2009-05-03T03:46:17Z
816,318
16
2009-05-03T04:15:43Z
[ "python", "unicode", "ascii" ]
I have some text that uses Unicode punctuation, like left double quote, right single quote for apostrophe, and so on, and I need it in ASCII. Does Python have a database of these characters with obvious ASCII substitutes so I can do better than turning them all into "?" ?
Interesting question. Google helped me find [this page](http://www.peterbe.com/plog/unicode-to-ascii) which descibes using the [unicodedata module](http://effbot.org/librarybook/unicodedata.htm) as the following: ``` import unicodedata unicodedata.normalize('NFKD', title).encode('ascii','ignore') ```
Where is Python's "best ASCII for this Unicode" database?
816,285
66
2009-05-03T03:46:17Z
816,319
24
2009-05-03T04:16:58Z
[ "python", "unicode", "ascii" ]
I have some text that uses Unicode punctuation, like left double quote, right single quote for apostrophe, and so on, and I need it in ASCII. Does Python have a database of these characters with obvious ASCII substitutes so I can do better than turning them all into "?" ?
In my original answer, I also suggested `unicodedata.normalize`. However, I decided to test it out and it turns out it doesn't work with Unicode quotation marks. It does a good job translating accented Unicode characters, so I'm guessing `unicodedata.normalize` is implemented using the `unicode.decomposition` function,...
Where is Python's "best ASCII for this Unicode" database?
816,285
66
2009-05-03T03:46:17Z
1,701,378
73
2009-11-09T14:37:23Z
[ "python", "unicode", "ascii" ]
I have some text that uses Unicode punctuation, like left double quote, right single quote for apostrophe, and so on, and I need it in ASCII. Does Python have a database of these characters with obvious ASCII substitutes so I can do better than turning them all into "?" ?
[Unidecode](http://pypi.python.org/pypi/Unidecode) looks like a complete solution. It converts fancy quotes to ascii quotes, accented latin characters to unaccented and even attempts transliteration to deal with characters that don't have ASCII equivalents. That way your users don't have to see a bunch of ? when you ha...
Python: avoiding pylint warnings about too many arguments
816,391
16
2009-05-03T05:13:02Z
816,396
9
2009-05-03T05:17:42Z
[ "python", "refactoring", "pylint" ]
I want to refactor a big Python function into smaller ones. For example, consider this following code snippet: ``` x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 ``` Of course, this is a trivial example. In practice, the code is more complex. My point is that it contains many local-scope variables that would have to ...
You could try using [Python's variable arguments](http://docs.python.org/tutorial/controlflow.html#arbitrary-argument-lists) feature: ``` def myfunction(*args): for x in args: # Do stuff with specific argument here ```
Python: avoiding pylint warnings about too many arguments
816,391
16
2009-05-03T05:13:02Z
816,517
35
2009-05-03T07:22:58Z
[ "python", "refactoring", "pylint" ]
I want to refactor a big Python function into smaller ones. For example, consider this following code snippet: ``` x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 ``` Of course, this is a trivial example. In practice, the code is more complex. My point is that it contains many local-scope variables that would have to ...
First, one of [Perlis's epigrams](http://www.cs.yale.edu/quotes.html): > "If you have a procedure with 10 > parameters, you probably missed some." Some of the 10 arguments are presumably related. Group them into an object, and pass that instead. Making an example up, because there's not enough information in the que...
Python: avoiding pylint warnings about too many arguments
816,391
16
2009-05-03T05:13:02Z
816,549
18
2009-05-03T07:59:40Z
[ "python", "refactoring", "pylint" ]
I want to refactor a big Python function into smaller ones. For example, consider this following code snippet: ``` x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 ``` Of course, this is a trivial example. In practice, the code is more complex. My point is that it contains many local-scope variables that would have to ...
Do you want a better way to pass the arguments or just a way to stop `pylint` from giving you a hard time? If the latter, I seem to recall that you could stop the nagging by putting `pylint`-controlling comments in your code along the lines of: ``` #pylint: disable-msg=R0913 ``` or: ``` #pylint: disable-msg=too-many...
Python: avoiding pylint warnings about too many arguments
816,391
16
2009-05-03T05:13:02Z
816,789
11
2009-05-03T10:58:03Z
[ "python", "refactoring", "pylint" ]
I want to refactor a big Python function into smaller ones. For example, consider this following code snippet: ``` x = x1 + x2 + x3 + x4 + x5 + x6 + x7 + x8 + x9 ``` Of course, this is a trivial example. In practice, the code is more complex. My point is that it contains many local-scope variables that would have to ...
You can easily change the maximum allowed number of arguments in pylint. Just open your pylintrc file (generate it if you don't already have one) and change: max-args=5 to: max-args = 6 # or any value that suits you From pylint's [manual](http://www.logilab.org/card/pylint%5Fmanual) > Specifying all the options su...
Call a function with argument list in python
817,087
104
2009-05-03T13:43:33Z
817,093
10
2009-05-03T13:47:05Z
[ "python", "function" ]
I'm trying to call a function inside another function in python, but can't find the right syntax. What I want to do is something like this: ``` def wrapper(func, args): func(args) def func1(x): print(x) def func2(x, y, z): return x+y+z wrapper(func1, [x]) wrapper(func2, [x, y, z]) ``` In this case firs...
You can use \*args and \*\*kwargs syntax for variable length arguments. <http://stackoverflow.com/questions/287085/what-does-args-and-kwargs-mean> And from the official python tutorial <http://docs.python.org/dev/tutorial/controlflow.html#more-on-defining-functions>
Call a function with argument list in python
817,087
104
2009-05-03T13:43:33Z
817,111
8
2009-05-03T13:53:57Z
[ "python", "function" ]
I'm trying to call a function inside another function in python, but can't find the right syntax. What I want to do is something like this: ``` def wrapper(func, args): func(args) def func1(x): print(x) def func2(x, y, z): return x+y+z wrapper(func1, [x]) wrapper(func2, [x, y, z]) ``` In this case firs...
You need to use arguments unpacking.. ``` def wrapper(func, *args): func(*args) def func1(x): print(x) def func2(x, y, z): print x+y+z wrapper(func1, 1) wrapper(func2, 1, 2, 3) ```