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 |
|---|---|---|---|---|---|---|---|---|---|
Django Custom Managers for User model | 1,642,779 | 7 | 2009-10-29T10:31:05Z | 1,644,255 | 14 | 2009-10-29T14:46:44Z | [
"python",
"django"
] | How would I go about extending the default User model with custom managers?
My app has many user types that will be defined using the built-in Groups model. So a User might be a client, a staff member, and so on. It would be ideal to be able to do something like:
```
User.clients.filter(name='Test')
```
To get all c... | Yes, you can add a custom manager directly to the User class. This is monkeypatching, and it does make your code less maintainable (someone trying to figure out your code may have no idea where the User class acquired that custom manager, or where they could look to find it). In this case it's relatively harmless, as y... |
Folder and file organization for Python development | 1,642,975 | 14 | 2009-10-29T11:08:00Z | 1,643,354 | 9 | 2009-10-29T12:25:18Z | [
"python",
"organization",
"code-organization"
] | What is the best way to organize code that belongs to the same project in a Python development environment? What are the do and donts of Python project organization? Do you separate each class in a file?
```
Project A
Classes
"subsystem1"
class1
class2
subsystem1Module
... | Some suggestions are at <http://jcalderone.livejournal.com/39794.html> and <http://infinitemonkeycorps.net/docs/pph/> |
Forward slash in a Python regex | 1,643,772 | 7 | 2009-10-29T13:33:43Z | 1,643,823 | 16 | 2009-10-29T13:42:38Z | [
"python",
"regex"
] | I'm trying to use a Python regex to find a mathematical expression in a string. The problem is that the forward slash seems to do something unexpected. I'd have thought that `[\w\d\s+-/*]*` would work for finding math expressions, but it finds commas too for some reason. A bit of experimenting reveals that forward slas... | Look [here for documentation](http://docs.python.org/library/re.html#module-re) on Python's re module.
I think it is not the "/", but rather the "-" in your first character class: `[+-/]` matches '+', '/' and any ASCII value between
, which happen to include the comma.
Maybe this hint from the docs help:
If you want... |
Is there any way to use a strftime-like function for dates before 1900 in Python? | 1,643,967 | 18 | 2009-10-29T14:03:24Z | 1,644,026 | 11 | 2009-10-29T14:12:37Z | [
"python",
"oracle",
"datetime",
"sql-loader",
"strftime"
] | I didn't realize this, but apparently Python's `strftime` function doesn't support dates before 1900:
```
>>> from datetime import datetime
>>> d = datetime(1899, 1, 1)
>>> d.strftime('%Y-%m-%d')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: year=1899 is before 1900; the datetime... | The [documentation seems pretty clear about this:](http://docs.python.org/library/datetime.html#strftime-behavior)
> The exact range of years for which `strftime()` works also varies across platforms. Regardless of platform, years before 1900 cannot be used.
So there isn't going to be a solution that uses `strftime()... |
Is there any way to use a strftime-like function for dates before 1900 in Python? | 1,643,967 | 18 | 2009-10-29T14:03:24Z | 1,644,392 | 13 | 2009-10-29T15:07:26Z | [
"python",
"oracle",
"datetime",
"sql-loader",
"strftime"
] | I didn't realize this, but apparently Python's `strftime` function doesn't support dates before 1900:
```
>>> from datetime import datetime
>>> d = datetime(1899, 1, 1)
>>> d.strftime('%Y-%m-%d')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: year=1899 is before 1900; the datetime... | [isoformat](http://docs.python.org/library/datetime.html?highlight=isoformat#datetime.datetime.isoformat) works on `datetime` instances w/o limitation of range:
```
>>> import datetime
>>> x=datetime.datetime(1865, 7, 2, 9, 30, 21)
>>> x.isoformat()
'1865-07-02T09:30:21'
```
If you need a different-format string it's... |
CPython is bytecode interpreter? | 1,644,619 | 7 | 2009-10-29T15:39:57Z | 1,644,643 | 7 | 2009-10-29T15:42:45Z | [
"c++",
"python",
"interpreter",
"bytecode",
"cpython"
] | I don't really get the concept of "bytecode interpreter" in the context of CPython. Can someone shed some light over the whole picture?
Does it mean that CPython will compile and execute pyc file (bytecode file?). Then what compile py file to pyc file? And how is Jython different from CPython (except they are implemen... | CPython is both the bytecode compiler, and interpreter (virtual machine).
It automatically detects if no existing pre-compiler file (.pyc) exists, compiles the code, and saves it out. |
CPython is bytecode interpreter? | 1,644,619 | 7 | 2009-10-29T15:39:57Z | 1,644,742 | 10 | 2009-10-29T15:57:51Z | [
"c++",
"python",
"interpreter",
"bytecode",
"cpython"
] | I don't really get the concept of "bytecode interpreter" in the context of CPython. Can someone shed some light over the whole picture?
Does it mean that CPython will compile and execute pyc file (bytecode file?). Then what compile py file to pyc file? And how is Jython different from CPython (except they are implemen... | CPython is the implementation of Python in C. It's the first implementation, and still the main one that people mean when they talk about Python. It compiles .py files to .pyc files. .pyc files contain bytecodes. The CPython implementation also interprets those bytecodes.
CPython is not written in C++, it is C.
The co... |
CPython is bytecode interpreter? | 1,644,619 | 7 | 2009-10-29T15:39:57Z | 6,830,193 | 8 | 2011-07-26T12:43:49Z | [
"c++",
"python",
"interpreter",
"bytecode",
"cpython"
] | I don't really get the concept of "bytecode interpreter" in the context of CPython. Can someone shed some light over the whole picture?
Does it mean that CPython will compile and execute pyc file (bytecode file?). Then what compile py file to pyc file? And how is Jython different from CPython (except they are implemen... | First: The fact that CPython is a bytecode interpreter should not matter to you as a user of python. Go ahead and write code, and don't worry about how it's turned into action.
So, to answer your question and satisfy your curiosity, here is what happens: CPython reads python source code, and compiles it into python by... |
How to handle Unicode (non-ASCII) characters in Python? | 1,644,640 | 8 | 2009-10-29T15:42:32Z | 1,645,140 | 9 | 2009-10-29T16:58:42Z | [
"python",
"unicode",
"character-encoding"
] | I'm programming in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29) and I'm obtaining information from a web page through the [`urllib2`](http://docs.python.org/library/urllib2.html) library. The problem is that that page can provide me with non-ASCII characters, like `'ñ'`, `'á'`, etc. In the... | You just read a set of bytes from the socket. If you want a string you have to decode it:
```
yourstring = receivedbytes.decode("utf-8")
```
(substituting whatever encoding you're using for `utf-8`)
Then you have to do the reverse to send it back out:
```
outbytes = yourstring.encode("utf-8")
``` |
Trace Table for Python Programs | 1,645,028 | 7 | 2009-10-29T16:41:29Z | 1,645,159 | 10 | 2009-10-29T17:00:41Z | [
"python"
] | Is there a way to get the trace table for a Python program? Or for a program to run another program and get its trace table? I'm a teacher trying to flawlessly verify the answers to the tracing problems that we use on our tests.
So, for example, assuming I have a Python program named `problem1.py` with the following c... | This isn't a use case that the current Python tracing tool support, but it should be possible to build. I don't know how you decide what columns to output. In your sample, a and b are the only local variables, but larger programs would have more interesting ecosystems of data.
Updated: here's a simple proof of concept... |
Concurrency control in Django model | 1,645,269 | 15 | 2009-10-29T17:19:12Z | 1,656,572 | 17 | 2009-11-01T07:00:54Z | [
"python",
"django",
"concurrency"
] | How do I handle concurrency in a Django model? I dont want the changes to the record being overwritten by another user who reads the same record | The short answer, this really isn't a Django question as presented.
Concurrency control is often presented as a technical question, but is in many ways a question of functional requirements. How do you want/need your application to work? Until we know that, it will be difficult to give any Django-specific advice.
But... |
Concurrency control in Django model | 1,645,269 | 15 | 2009-10-29T17:19:12Z | 4,679,345 | 8 | 2011-01-13T11:04:58Z | [
"python",
"django",
"concurrency"
] | How do I handle concurrency in a Django model? I dont want the changes to the record being overwritten by another user who reads the same record | I don't think that 'keeping a version number or timestamp' works. When self.version == self.read\_current\_version() is true, there is still a chance that the version number got modified by other sessions just before you call super().save. |
how convert list of int to list of tuples | 1,645,673 | 4 | 2009-10-29T18:29:40Z | 1,645,728 | 10 | 2009-10-29T18:37:55Z | [
"python"
] | I want to convert a list like this
```
l1 = [1,2,3,4,5,6,7,8]
```
to
```
l2 = [(1,2),(3,4),(5,6),(7,8)]
```
because want to loop
```
for x,y in l2:
draw_thing(x,y)
``` | One *good* way is:
```
from itertools import izip
it = iter([1, 2, 3, 4])
for x, y in izip(it, it):
print x, y
```
Output:
```
1 2
3 4
>>>
``` |
how convert list of int to list of tuples | 1,645,673 | 4 | 2009-10-29T18:29:40Z | 1,645,837 | 7 | 2009-10-29T18:57:38Z | [
"python"
] | I want to convert a list like this
```
l1 = [1,2,3,4,5,6,7,8]
```
to
```
l2 = [(1,2),(3,4),(5,6),(7,8)]
```
because want to loop
```
for x,y in l2:
draw_thing(x,y)
``` | Building on Nick D's answer:
```
>>> from itertools import izip
>>> t = [1,2,3,4,5,6,7,8,9,10,11,12]
>>> for a, b in izip(*[iter(t)]*2):
... print a, b
...
1 2
3 4
5 6
7 8
9 10
11 12
>>> for a, b, c in izip(*[iter(t)]*3):
... print a, b, c
...
1 2 3
4 5 6
7 8 9
10 11 12
>>> for a, b, c, d in izip(*[iter(t)]*4)... |
Django Year/Month based posts archive | 1,645,962 | 6 | 2009-10-29T19:21:11Z | 1,646,414 | 12 | 2009-10-29T20:40:43Z | [
"python",
"django"
] | i'm new to Django and started an application, i did the models,
views, templates, but i want to add some kind of archive to the bottom
of the page, something like this <http://www.flickr.com/photos/ionutgabriel/3990015411/>.
So i want to list all years and next to them all the months from that year. The months who hav... | Firstly, the datetime format strings are given in the [django docs](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#now). I think you want capital instead of lowercase 'M'.
Since you want to display all 12 months of a year, even if only some have posts, we'll create an `archives` object to pass to the tem... |
How do I import a COM object namespace/enumeration in Python? | 1,646,230 | 7 | 2009-10-29T20:08:48Z | 5,413,586 | 8 | 2011-03-24T01:10:52Z | [
"python",
"excel",
"com",
"namespaces",
"enumeration"
] | I'm relatively new to programming/python, so I'd appreciate any help I can get. I want to save an excel file as a specific format using Excel through COM. Here is the code:
```
import win32com.client as win32
def excel():
app = 'Excel'
x1 = win32.gencache.EnsureDispatch('%s.Application' % app)
ss = x1.Wo... | This question is a bit stale, but for those reaching this page from Google (as I did) my solution was accessing the constants via the `win32com.client.constants` object instead of on the application object itself [as suggested by Eric](http://stackoverflow.com/questions/1646230/how-do-i-import-a-com-object-namespace-en... |
How to deploy Python to Windows users? | 1,646,326 | 14 | 2009-10-29T20:28:34Z | 1,646,344 | 11 | 2009-10-29T20:30:41Z | [
"python",
"windows",
"delphi",
"deployment",
"lazarus"
] | I'm soon to launch a [beta app](http://www.bestsellerapp.com/) and this have the option to create custom integration scripts on [Python](http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29).
The app will target [Mac OS X](http://en.wikipedia.org/wiki/Mac%5FOS%5FX) and Windows, and my problem is with Win... | You might try using [py2exe](http://www.py2exe.org/). It creates a .exe file with Python already included! |
How to deploy Python to Windows users? | 1,646,326 | 14 | 2009-10-29T20:28:34Z | 1,647,131 | 10 | 2009-10-29T23:16:58Z | [
"python",
"windows",
"delphi",
"deployment",
"lazarus"
] | I'm soon to launch a [beta app](http://www.bestsellerapp.com/) and this have the option to create custom integration scripts on [Python](http://en.wikipedia.org/wiki/Python%5F%28programming%5Flanguage%29).
The app will target [Mac OS X](http://en.wikipedia.org/wiki/Mac%5FOS%5FX) and Windows, and my problem is with Win... | Copy a [Portable Python](http://www.portablepython.com/) folder out of your installer, into the same folder as your Delphi/Lazarus app. Set all paths appropriately for that. |
How to run django unit-tests on production database? | 1,646,468 | 15 | 2009-10-29T20:50:16Z | 1,648,881 | 45 | 2009-10-30T09:47:11Z | [
"python",
"django",
"unit-testing"
] | i'm starting the TDD development attitude and am writting unit-tests for my django application. I'm aware of fixtures and know that's the way tests should be executed, but for a given test i do need to execute it on the whole database, and json fixture for 10+ million row database is not something i'd like to handle, m... | In case someone googles here searching for the solution for a given problem, here is the skeleton on how to perform unit tests on django production database. Check the django docs section [here](http://docs.djangoproject.com/en/dev/howto/custom-management-commands/#writing-custom-django-admin-commands), for the file/di... |
Is there a way to know if a list of elements is on a larger list without using 'in' keyword? | 1,646,641 | 4 | 2009-10-29T21:23:55Z | 1,646,692 | 7 | 2009-10-29T21:32:04Z | [
"python"
] | I want to do this. I have two python lists, one larger than the other and I want to know is there is a way to check if the elements of the smaller list are in the big list in the exact same order for example:
```
small_list = [4,2,5]
big_list = [1,2,5,7,2,4,2,5,67,8,5,13,45]
```
I tried using the *in* keyword but It ... | ```
def in_list(small, big):
l_sml = len(small)
l_big = len(big)
return any((big[i:i+l_sml]==small for i in xrange(l_big-l_sml+1)))
print in_list([4,2,1], [1,2,3,4,2,1,0,5]) # True
print in_list([1,2,3], [1,2,4]) # False
``` |
Adapt an existing database to a django app | 1,646,786 | 6 | 2009-10-29T21:49:02Z | 1,646,799 | 14 | 2009-10-29T21:51:36Z | [
"python",
"database",
"postgresql",
"django-models",
"django-views"
] | I have a Postgresql databese with data. I want to create a django app with that database.
How can i import the tables to django models and/or views? | Read this: <http://docs.djangoproject.com/en/dev/howto/legacy-databases/>
There is a utility to generate models from your existing database. It works pretty well. |
How can I use Microsoft Word's spelling/grammar checker programmatically? | 1,646,801 | 6 | 2009-10-29T21:52:04Z | 1,647,718 | 8 | 2009-10-30T02:40:36Z | [
"python",
"com",
"ms-word",
"word-2007",
"win32com"
] | I want to process a medium to large number of text snippets using a spelling/grammar checker to get a *rough* approximation and ranking of their "quality." Speed is not really of concern either, so I think the easiest way is to write a script that passes off the snippets to Microsoft Word (2007) and runs its spelling a... | It took some digging, but I think I found a useful solution. Following the advice at <http://www.nabble.com/Edit-a-Word-document-programmatically-td19974320.html> I'm using the [win32com](http://sourceforge.net/projects/pywin32/) module, which allows access to Word's COM objects. The following code demonstrates this ni... |
Is it possible to change an instance's method implementation without changing all other instances of the same class? | 1,647,586 | 9 | 2009-10-30T01:42:06Z | 1,647,616 | 13 | 2009-10-30T02:01:55Z | [
"python"
] | I do not know python very much (never used it before :D), but I can't seem to find anything online. Maybe I just didn't google the right question, but here I go:
I want to change an instance's implementation of a specific method. When I googled for it, I found you could do it, but it changes the implementation for all... | **Everything you wanted to know about [Python Attributes and Methods](http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html).**
Yes, this is an indirect answer, but it demonstrates a number of techniques and explains some of the more intricate details and "magic".
For a "more ... |
How can I send an iCalendar email attachment with Django? | 1,647,597 | 3 | 2009-10-30T01:49:37Z | 1,649,799 | 7 | 2009-10-30T13:24:35Z | [
"python",
"django",
"icalendar"
] | I want to send an iCalendar <http://en.wikipedia.org/wiki/ICalendar> email attachment using Django. Is there an open source library to build an iCalendar file in Python and/or available for Django? | As stated before, there is [vobject](http://vobject.skyhouseconsulting.com/), that is working fine (I have used it recently).
You can find good information about ical, vobject and django in this blog post :
<http://blog.thescoop.org/archives/2007/07/31/django-ical-and-vobject/> |
Common errors when moving a django app from dev to prod? | 1,648,349 | 5 | 2009-10-30T06:42:15Z | 1,648,406 | 7 | 2009-10-30T07:03:38Z | [
"python",
"django",
"production-environment"
] | I am developping a django app on Windows, SQLite and the django dev server . I have deployed it to my host server which is running Linux, Apache, FastCgi, MySQL.
Unfortunately, I have an error returned by the server on the prod while everything ok on the dev machine. I've asked my provider for a pre-production solutio... | Problems I typically have include:
1. Misconfigured productions settings, whether in my production localsettings.py, wsgi/cgi, or apache site files in /etc/sites-available
2. Database differences. I use [South](http://south.aeracode.org/) for migrations and have run into some subtle issues when performing my migration... |
ConfigParser with Unicode items | 1,648,517 | 14 | 2009-10-30T07:52:14Z | 1,648,865 | 17 | 2009-10-30T09:44:13Z | [
"python",
"unicode",
"configparser"
] | my troubles with ConfigParser continue. It seems it doesn't support Unicode very well. The config file is indeed saved as UTF-8, but when ConfigParser reads it it seems to be encoded into something else. I assumed it was latin-1 and I thougt overriding `optionxform` could help:
```
-- configfile.cfg --
[rules]
Häjsa... | The `ConfigParser.readfp()` method can take a file object, have you tried opening the file object with the correct encoding using the codecs module before sending it to ConfigParser like below:
```
cfg.readfp(codecs.open("myconfig", "r", "utf8"))
```
For Python 3.2 or above, [`readfp()`](https://docs.python.org/3/lib... |
How to split a string by commas positioned outside of parenthesis? | 1,648,537 | 16 | 2009-10-30T08:02:09Z | 1,648,626 | 13 | 2009-10-30T08:34:22Z | [
"python",
"regex",
"split"
] | I got a string of such format:
```
"Wilbur Smith (Billy, son of John), Eddie Murphy (John), Elvis Presley, Jane Doe (Jane Doe)"
```
so basicly it's list of actor's names (optionally followed by their role in parenthesis). The role itself can contain comma (actor's name can not, I strongly hope so).
My goal is to spl... | One way to do it is to use `findall` with a regex that greedily matches things that can go between separators. eg:
```
>>> s = "Wilbur Smith (Billy, son of John), Eddie Murphy (John), Elvis Presley, Jane Doe (Jane Doe)"
>>> r = re.compile(r'(?:[^,(]|\([^)]*\))+')
>>> r.findall(s)
['Wilbur Smith (Billy, son of John)', ... |
Given a latitude and longitude, and distance, I want to find a bounding box | 1,648,917 | 4 | 2009-10-30T10:01:38Z | 7,110,219 | 7 | 2011-08-18T15:44:08Z | [
"python",
"geocoding",
"bounding-box"
] | Given a latitude and longitude, and distance, I want to find a bounding box where the distances are less than the given distance.
This questions was asked here: <http://stackoverflow.com/questions/238260/how-to-calculate-the-bounding-box-for-a-given-lat-lng-location>
I donot want this partcularly accurate, so I have ... | This code didn't quite work, it jumps between KM and M.
Fixed code, made names more PEP8 style, and added a simple box object:
```
class BoundingBox(object):
def __init__(self, *args, **kwargs):
self.lat_min = None
self.lon_min = None
self.lat_max = None
self.lon_max = None
def g... |
How to assert that zero or only one of N given arguments is passed | 1,648,956 | 4 | 2009-10-30T10:11:55Z | 1,648,982 | 9 | 2009-10-30T10:18:39Z | [
"python"
] | I have a definition like this
```
def bar(self, foo=None, bar=None, baz=None):
pass
```
I want to make sure a maximum of one of foo, bar, baz is passed. I can do
```
if foo and bar:
raise Ex()
if foo and baz:
raise Ex()
....
```
But there got be something simpler. | How about:
```
initialisers = [foo, bar, baz]
if initialisers.count(None) < len(initialisers) - 1:
raise Ex()
```
It simply counts how many `None` are present. If they're all `None` or only one isn't then fine, otherwise it raises the exception. |
Is it still Python 2.6 versus Python 3? | 1,649,391 | 8 | 2009-10-30T12:00:54Z | 1,649,418 | 9 | 2009-10-30T12:05:16Z | [
"python",
"python-3.x",
"version"
] | G'day,
I'm wanting to go back to Python after not using it for a while and I saw this question ["Python Version for a Newbie"](http://stackoverflow.com/questions/345255/python-version-for-a-newbie) while wondering about getting back into Python 2.6 or Python 3.
Almost all of the questions' answers were along the line... | Yes. Virtually all live production systems will use 2.5/2.6 for a long time yet. There's no point learning 3.0, only to have to downgrade it because your host doesn't support it.
95% of what you will learn in 2.5/2.6 is applicable to 3 anyway. |
Strange Problem with RPy2 | 1,649,503 | 2 | 2009-10-30T12:24:28Z | 1,650,359 | 7 | 2009-10-30T15:06:09Z | [
"python",
"python-idle"
] | After installing RPy2 from
<http://rpy.sourceforge.net/rpy2.html>
I'm trying to use it in Python 2.6 IDLE but I'm getting this error:
```
>>> import rpy2.robjects as robjects
>>> robjects.r['pi']
<RVector - Python:0x0121D8F0 / R:0x022A1760>
```
What I'm doing wrong? | Have you tried looking at the vector that's returned?
```
>>> pi = robjects.r['pi']
>>> pi[0]
3.14159265358979
``` |
Calling types via their name as a string in Python | 1,650,338 | 4 | 2009-10-30T15:02:16Z | 1,650,390 | 12 | 2009-10-30T15:12:11Z | [
"python",
"getattr"
] | I'm aware of using globals(), locals() and getattr to referance things in Python by string (as in [this question](http://stackoverflow.com/questions/3061/calling-a-function-from-a-string-with-the-functions-name-in-python)) but unless I'm missing something obvious I can't seem to use this with calling types.
e.g.:
```... | There are locals,globals, and then builtins.
Perhaps you are looking for the builtin:
```
import __builtin__
getattr(__builtin__,'int')
``` |
Calling types via their name as a string in Python | 1,650,338 | 4 | 2009-10-30T15:02:16Z | 1,650,617 | 7 | 2009-10-30T15:47:16Z | [
"python",
"getattr"
] | I'm aware of using globals(), locals() and getattr to referance things in Python by string (as in [this question](http://stackoverflow.com/questions/3061/calling-a-function-from-a-string-with-the-functions-name-in-python)) but unless I'm missing something obvious I can't seem to use this with calling types.
e.g.:
```... | You've already gotten a solution using builtins, but another worthwhile technique to hold in your toolbag is a dispatch table. If your CSV is designed to be used by multiple applications written in multiple languages, it might look like this:
```
Integer,15
String,34
Float,1.0
Integer,8
```
In such a case you might w... |
How do I create an OpenCV image from a PIL image? | 1,650,568 | 9 | 2009-10-30T15:38:23Z | 1,652,018 | 8 | 2009-10-30T20:06:55Z | [
"python",
"image-processing",
"opencv",
"python-imaging-library"
] | I want to do some image processing with OpenCV (in Python), but I have to start with a PIL `Image` object, so I can't use the `cvLoadImage()` call, since that takes a filename.
This recipe (adapted from <http://opencv.willowgarage.com/wiki/PythonInterface>) does not work because `cvSetData` complains `argument 2 of ty... | The example you tried to adapt is for the new python interface for OpenCV 2.0. This is probably the source of the confusion between the prefixed and non-prefixed function names (`cv.cvSetData()` versus `cv.SetData()`).
OpenCV 2.0 now ships with two sets of python bindings:
* The ["old-style" python wrapper](http://op... |
Whether to use "SET NAMES" | 1,650,591 | 51 | 2009-10-30T15:41:09Z | 1,650,649 | 8 | 2009-10-30T15:53:40Z | [
"php",
"python",
"mysql",
"internationalization"
] | In reading "High performance MySQL" from O'Reilly I've stumbled upon the following
> Another common garbage query is SET
> NAMES UTF8, which is the wrong way to
> do things anyway (it does not change
> the client library's character set; it
> affects only the server).
I'm a bit confused, because I used to put "SET NA... | Not sure about py, but php has [`mysql_set_charset`](http://php.net/manual/en/function.mysql-set-charset.php) now, which states that this is the "preferred way to change the charset [and] using mysql\_query() to execute SET NAMES is not recommended." Note, that this function was introduced for MySQL 5.0.7, so it won't ... |
Whether to use "SET NAMES" | 1,650,591 | 51 | 2009-10-30T15:41:09Z | 1,650,834 | 28 | 2009-10-30T16:18:42Z | [
"php",
"python",
"mysql",
"internationalization"
] | In reading "High performance MySQL" from O'Reilly I've stumbled upon the following
> Another common garbage query is SET
> NAMES UTF8, which is the wrong way to
> do things anyway (it does not change
> the client library's character set; it
> affects only the server).
I'm a bit confused, because I used to put "SET NA... | [`mysql_set_charset()`](http://php.net/manual/en/function.mysql-set-charset.php) would be an option - but an option limited to the [`ext/mysql`](http://www.php.net/manual/en/book.mysql.php). For [`ext/mysqli`](http://www.php.net/manual/en/book.mysqli.php) it is [`mysqli_set_charset`](http://php.net/manual/mysqli.set-ch... |
Whether to use "SET NAMES" | 1,650,591 | 51 | 2009-10-30T15:41:09Z | 14,132,028 | 18 | 2013-01-03T01:49:07Z | [
"php",
"python",
"mysql",
"internationalization"
] | In reading "High performance MySQL" from O'Reilly I've stumbled upon the following
> Another common garbage query is SET
> NAMES UTF8, which is the wrong way to
> do things anyway (it does not change
> the client library's character set; it
> affects only the server).
I'm a bit confused, because I used to put "SET NA... | This answer has an emphasis on php's pdo library because it's so ubiquitous.
A brief reminder - mysql is a client-server architecture. This is significant because there's not only the mysql server where the actual database is, but there's also the seperate mysql client driver, which is the thing that talks to the mysq... |
Designing the storage for a very large game world | 1,650,627 | 7 | 2009-10-30T15:49:22Z | 1,650,647 | 11 | 2009-10-30T15:53:29Z | [
"python",
"sqlite",
"python-3.x",
"python-stackless"
] | I'm starting up game programming again. 10 years ago I was making games in qbasic and I havn't done any game programming since, so I am quite rusty. I have been programming all the time though, I am web developer/DBA/admin now. I have several questions, but I'm going to limit it to one per post.
The game I am working ... | Don't mess with relational databases unless you're forced to use them by external factors.
Look at Python's `pickle`, [shelve](http://docs.python.org/library/shelve.html).
Shelve is fast and scales well. It eliminates messy conversion between Python and non-Python representation.
---
Edit.
More important advice. D... |
Why are default arguments evaluated at definition time in Python? | 1,651,154 | 27 | 2009-10-30T17:16:08Z | 1,651,196 | 7 | 2009-10-30T17:22:21Z | [
"python",
"logic",
"language-design"
] | I had a very difficult time with understanding the root cause of a problem in an algorithm. Then, by simplifying the functions step by step I found out that evaluation of default arguments in Python doesn't behave as I expected.
The code is as follows:
```
class Node(object):
def __init__(self, children = []):
... | The workaround for this, [discussed here](http://www.network-theory.co.uk/docs/pytut/DefaultArgumentValues.html) (and very solid), is:
```
class Node(object):
def __init__(self, children = None):
self.children = [] if children is None else children
```
As for why look for an answer from von Löwis, but it... |
Why are default arguments evaluated at definition time in Python? | 1,651,154 | 27 | 2009-10-30T17:16:08Z | 1,651,220 | 7 | 2009-10-30T17:26:59Z | [
"python",
"logic",
"language-design"
] | I had a very difficult time with understanding the root cause of a problem in an algorithm. Then, by simplifying the functions step by step I found out that evaluation of default arguments in Python doesn't behave as I expected.
The code is as follows:
```
class Node(object):
def __init__(self, children = []):
... | Of course in your situation it is difficult to understand. But you must see, that evaluating default args every time would lay a heavy runtime burden on the system.
Also you should know, that in case of container types this problem may occur -- but you could circumvent it by making the thing explicit:
```
def __init_... |
Why are default arguments evaluated at definition time in Python? | 1,651,154 | 27 | 2009-10-30T17:16:08Z | 1,651,280 | 10 | 2009-10-30T17:36:59Z | [
"python",
"logic",
"language-design"
] | I had a very difficult time with understanding the root cause of a problem in an algorithm. Then, by simplifying the functions step by step I found out that evaluation of default arguments in Python doesn't behave as I expected.
The code is as follows:
```
class Node(object):
def __init__(self, children = []):
... | The issue is this.
It's too expensive to evaluate a function as an initializer **every time the function is called**.
* `0` is a simple literal. Evaluate it once, use it forever.
* `int` is a function (like list) that would have to be evaluated each time it's required as an initializer.
The construct `[]` is literal... |
Why are default arguments evaluated at definition time in Python? | 1,651,154 | 27 | 2009-10-30T17:16:08Z | 1,651,284 | 35 | 2009-10-30T17:37:32Z | [
"python",
"logic",
"language-design"
] | I had a very difficult time with understanding the root cause of a problem in an algorithm. Then, by simplifying the functions step by step I found out that evaluation of default arguments in Python doesn't behave as I expected.
The code is as follows:
```
class Node(object):
def __init__(self, children = []):
... | The alternative would be quite heavyweight -- storing "default argument values" in the function object as "thunks" of code to be executed over and over again every time the function is called without a specified value for that argument -- and would make it much harder to get early binding (binding at def time), which i... |
Python parsing bracketed blocks | 1,651,487 | 19 | 2009-10-30T18:18:26Z | 1,651,562 | 16 | 2009-10-30T18:35:28Z | [
"python",
"parsing",
"text-parsing",
"brackets"
] | What would be the best way in Python to parse out chunks of text contained in matching brackets?
```
"{ { a } { b } { { { c } } } }"
```
should initially return:
```
[ "{ a } { b } { { { c } } }" ]
```
putting that as an input should return:
```
[ "a", "b", "{ { c } }" ]
```
which should return:
```
[ "{ c }" ]
... | Pseudocode:
```
For each string in the array:
Find the first '{'. If there is none, leave that string alone.
Init a counter to 0.
For each character in the string:
If you see a '{', increment the counter.
If you see a '}', decrement the counter.
If the counter reaches 0, break.
... |
Python parsing bracketed blocks | 1,651,487 | 19 | 2009-10-30T18:18:26Z | 1,653,143 | 29 | 2009-10-31T01:50:04Z | [
"python",
"parsing",
"text-parsing",
"brackets"
] | What would be the best way in Python to parse out chunks of text contained in matching brackets?
```
"{ { a } { b } { { { c } } } }"
```
should initially return:
```
[ "{ a } { b } { { { c } } }" ]
```
putting that as an input should return:
```
[ "a", "b", "{ { c } }" ]
```
which should return:
```
[ "{ c }" ]
... | Or this pyparsing version:
```
>>> from pyparsing import nestedExpr
>>> txt = "{ { a } { b } { { { c } } } }"
>>>
>>> nestedExpr('{','}').parseString(txt).asList()
[[['a'], ['b'], [[['c']]]]]
>>>
``` |
Python and factories | 1,651,593 | 5 | 2009-10-30T18:41:06Z | 1,651,707 | 13 | 2009-10-30T18:59:44Z | [
"python",
"oop",
"factory"
] | I cant seem to grasp the proper concepts of a factory.
Can anyone help me code a simple test? I read some texts over the internet and cant code it the same way. Actually i cant understand the process. Copying code is easy, but i need to learn why this wont work.
```
class Factory:
def __init__(self):
sel... | Your code is counter-productive (sorry, I must say it).
The sense of a factory is, that you don't have to know the class of your constructed object at the position where you create it.
The reason is, that object creation creates a gap in object oriented abstraction. You must be concrete in creating the object. But so... |
Python urllib2 Response header | 1,653,591 | 20 | 2009-10-31T06:17:18Z | 2,523,793 | 32 | 2010-03-26T14:04:00Z | [
"python",
"url",
"header",
"response"
] | I'm trying to extract the response header of a URL request. When I use firebug to analyze the response output of a URL request, it returns:
```
Content-Type text/html
```
However when I use the python code:
```
urllib2.urlopen(URL).info()
```
the resulting output returns:
```
Content-Type: video/x-flv
```
I am ne... | Try to request as Firefox does. You can see the request headers in Firebug, so add them to your request object:
```
import urllib2
request = urllib2.Request('http://your.tld/...')
request.add_header('User-Agent', 'some fake agent string')
request.add_header('Referer', 'fake referrer')
...
response = urllib2.urlopen(r... |
If pickling was interrupted, will unpickling necessarily always fail? - Python | 1,653,897 | 4 | 2009-10-31T09:38:19Z | 1,654,390 | 7 | 2009-10-31T13:27:39Z | [
"python"
] | Suppose my attempt to write a pickle object out to disk is incomplete due to a crash. Will an attempt to unpickle the object **always** lead to an exception or is it possible that the fragment that was written out may be interpreted as valid pickle and the error go unnoticed? | Contra the other answers offered, I believe that we *can* make a strong argument about the recoverability of a pickle. That answer is: "Yes, an incomplete pickle *always* leads to an exception."
Why are we able to do this? Because the "pickle" format is in fact a small stack-based language. In a stack-based language y... |
Does Python have an ordered set? | 1,653,970 | 228 | 2009-10-31T10:12:07Z | 1,653,974 | 133 | 2009-10-31T10:15:06Z | [
"python",
"set"
] | Python has an [ordered dictionary](http://www.python.org/dev/peps/pep-0372/), what about an ordered set? | There is an [ordered set](http://code.activestate.com/recipes/576694/) recipe for this which is referred to from the [Python 2 Documentation](https://docs.python.org/2/library/collections.html). This runs on Py2.6 or later and 3.0 or later without any modifications. The interface is almost exactly the same as a normal ... |
Does Python have an ordered set? | 1,653,970 | 228 | 2009-10-31T10:12:07Z | 1,653,978 | 84 | 2009-10-31T10:17:39Z | [
"python",
"set"
] | Python has an [ordered dictionary](http://www.python.org/dev/peps/pep-0372/), what about an ordered set? | ## An ordered set is functionally a special case of an ordered dictionary.
The keys of a dictionary are unique. Thus, if one disregards the values in an ordered dictionary (e.g. by assigning them `None`), then one has essentially an ordered set.
[As of Python 3.1](http://docs.python.org/3.1/whatsnew/3.1.html) there i... |
Does Python have an ordered set? | 1,653,970 | 228 | 2009-10-31T10:12:07Z | 23,225,031 | 20 | 2014-04-22T16:22:53Z | [
"python",
"set"
] | Python has an [ordered dictionary](http://www.python.org/dev/peps/pep-0372/), what about an ordered set? | # Implementations on PyPI
While others have pointed out that there is no built-in implementation of an insertion-order preserving set in Python (yet), I am feeling that this question is missing an answer which states what there is to be found on [PyPI](https://pypi.python.org).
To the best of my knowledge there curre... |
Does Python have an ordered set? | 1,653,970 | 228 | 2009-10-31T10:12:07Z | 25,988,702 | 13 | 2014-09-23T06:52:26Z | [
"python",
"set"
] | Python has an [ordered dictionary](http://www.python.org/dev/peps/pep-0372/), what about an ordered set? | If you're using the ordered set to maintain a sorted order, consider using a sorted set implementation from PyPI. The [sortedcontainers](http://www.grantjenks.com/docs/sortedcontainers/) module provides a [SortedSet](http://www.grantjenks.com/docs/sortedcontainers/sortedset.html) for just this purpose. Some benefits: p... |
Trapping signals in Python | 1,654,215 | 3 | 2009-10-31T12:15:49Z | 1,654,279 | 11 | 2009-10-31T12:45:09Z | [
"python",
"signals"
] | According to the [documentation](http://docs.python.org/library/signal.html):
> There is no way to âblockâ signals temporarily from critical sections (since this is not supported by all Unix flavors).
What stops me using `signal.signal(signum,SIG_IGN)` to block it, then adding the signal back? | What stops you is that, if the signal actually arrives while SIG\_IGN is in place, then it will be ignored and thrown away. When you add the signal back later, it's too late because it's gone and you'll never get to learn that it happened.
Thus, you will have "ignored" (= thrown away) the signal rather than "blocked" ... |
Testing twisted application - Load client | 1,654,566 | 3 | 2009-10-31T14:37:05Z | 1,657,092 | 8 | 2009-11-01T12:47:18Z | [
"python",
"multithreading",
"twisted"
] | I've written a Twisted based server and I'd like to test it using twisted as well.
But I'd like to write a load test starting a bunch of request at the same time.
But I believe that I didn't get the concepts of Twisted, mainly client side, because I'm stucked with this problem:
```
from twisted.internet import r... | The direct cause for your failure is that you attemp to call run() on the reactor multiple times. You are supposed to ever only call run() once. I think you are expecting to have multiple reactors, each in its own thread, but actually you only have one. The bad thing is that having multiple reactors is difficult or imp... |
Python Syntax Highlighting in Microsoft Word | 1,654,635 | 4 | 2009-10-31T15:01:11Z | 1,654,656 | 10 | 2009-10-31T15:07:57Z | [
"python",
"ms-word"
] | Is there any way I can get my Python code syntax highlighted in Microsoft Word? | Use a [pastebin](https://gist.github.com/) that does syntax highlighting, for example:
<https://gist.github.com/anonymous/82cb7f691673e0147edf>
Then copy and paste the syntax highlighted code into Word. Worked perfectly for me. |
erlang on google app engine? | 1,654,759 | 2 | 2009-10-31T15:48:47Z | 1,654,786 | 11 | 2009-10-31T15:57:51Z | [
"python",
"google-app-engine",
"erlang"
] | I know python can be run on GAE
1. what is different erlang and python in lay man term?
2. can erlang run on google app engine ? | Erlang and Python are programming languages, and each language has one or more "runtimes" that allow you to run programs written in those languages. GAE supplies a Python runtime.
GAE has no support for Erlang programs. |
Run an OS X universal binary in 32-bit mode | 1,654,837 | 7 | 2009-10-31T16:18:26Z | 1,654,855 | 16 | 2009-10-31T16:28:24Z | [
"python",
"osx",
"universal-binary"
] | I have a third-party library (the interface to Xerox's Finite State tools) which come as universal binaries with two variants internally: a PPC and an i386 variant. I also have a Python interface to the library (which uses ctypes).
But when I try to run the example code provided with the Python interface I get an erro... | If you are using the apple system python (on snow leopard) you can execute it with
```
arch -i386 python
```
eg:
```
robin-mbp:~ $ arch -i386 /usr/bin/python2.6 -c "import sys; print sys.maxint"
2147483647
```
to start the interpreter in 32 bit mode. There is also an environment variable you can set for the system ... |
Python Scoping/Static Misunderstanding | 1,654,967 | 6 | 2009-10-31T17:11:27Z | 1,654,975 | 8 | 2009-10-31T17:14:37Z | [
"python",
"class",
"scope",
"iteration",
"static-members"
] | I'm really stuck on why the following code block 1 result in output 1 instead of output 2?
**Code block 1:**
```
class FruitContainer:
def __init__(self,arr=[]):
self.array = arr
def addTo(self,something):
self.array.append(something)
def __str__(self):
ret = "["
... | You should never use a mutable value (like []) for a default argument to a method. The value is computed once, and then used for every invocation. When you use an empty list as a default value, that same list is used every time the method is invoked without the argument, even as the value is modified by previous functi... |
Subclassing python's dict, override of __setitem__ doesn't retain new value | 1,655,422 | 2 | 2009-10-31T19:49:39Z | 1,655,427 | 10 | 2009-10-31T19:51:29Z | [
"python",
"subclass",
"dictionary"
] | I'm subclassing dict, but ran into a problem with **setitem** where one assignment works, but another assignment does not. I've boiled it down to the following basic problem:
```
class CustomDict(dict):
def __setitem__(self, key, value):
super(CustomDict, self).__setitem__(key, value)
```
Test 1 fails:
```
data =... | You are constructing new instances of CustomDict on each line. `CustomDict(data)` makes a new instance, which copies `data`.
Try this:
```
cd = CustomData({"message":"foo"})
cd["message"] = "bar"
print cd # prints "{'message': 'bar'}".
``` |
How can I generate random numbers in Python? | 1,655,559 | 13 | 2009-10-31T20:38:36Z | 1,655,619 | 27 | 2009-10-31T20:58:54Z | [
"python",
"random"
] | Are there any built-in libraries in Python or Numpy to generate random numbers based on various common distributions, such as:
* Normal
* Poisson
* Exponential
* Bernoulli
And various others?
Are there any such libraries with multi-variate distributions? | ```
#!/usr/bin/env python
from scipy.stats import bernoulli,poisson,norm,expon
```
bernoulli, poisson, norm, expon and many others are documented [here](http://www.scipy.org/doc/api_docs/SciPy.stats.distributions.html)
```
print(norm.rvs(size=30))
print(bernoulli.rvs(.3,size=30))
print(poisson.rvs(1,2,size=30))
print... |
How do you flush Python sockets? | 1,655,560 | 9 | 2009-10-31T20:38:59Z | 1,655,585 | 17 | 2009-10-31T20:47:32Z | [
"python",
"sockets",
"flush"
] | I've written a server in Python that is meant to send data to the client in the form "Header:Message"
I would like to be able to have each message sent individually so that the client will need to perform minimal work in order to read the "header" and the "message"
Unfortunately, I can't figure out how to properly fl... | I guess you are talking over a TCP connection.
Your approach is flawed. A TCP stream is defined as a stream of bytes. You always have to use some sort of separator and may not rely on the network stack to separate your messages.
If you really need datagram based services switch to UDP. You'll need to handle retransmi... |
How can a recursive regexp be implemented in python? | 1,656,859 | 14 | 2009-11-01T10:48:38Z | 1,657,068 | 15 | 2009-11-01T12:37:59Z | [
"python",
"regex",
"recursion"
] | I'm interested how can be implemented recursive regexp matching in Python (I've not found any examples :( ). For example how would one write expression which matches "bracket balanced" string like "foo(bar(bar(foo)))(foo1)bar1" | You could use [pyparsing](http://pyparsing.wikispaces.com/)
```
#!/usr/bin/env python
from pyparsing import nestedExpr
import sys
astring=sys.argv[1]
if not astring.startswith('('):
astring='('+astring+')'
expr = nestedExpr('(', ')')
result=expr.parseString(astring).asList()[0]
print(result)
```
Running it yield... |
How can a recursive regexp be implemented in python? | 1,656,859 | 14 | 2009-11-01T10:48:38Z | 17,407,483 | 10 | 2013-07-01T14:55:44Z | [
"python",
"regex",
"recursion"
] | I'm interested how can be implemented recursive regexp matching in Python (I've not found any examples :( ). For example how would one write expression which matches "bracket balanced" string like "foo(bar(bar(foo)))(foo1)bar1" | This is an old question, but for the people who come here through searches:
There's an atlernative regex module for python that does support recursive patterns:
<https://pypi.python.org/pypi/regex>
And it has a lot of more nice improvements on `re`. |
Can Django be used with py2exe? | 1,657,063 | 10 | 2009-11-01T12:36:23Z | 1,657,074 | 11 | 2009-11-01T12:40:01Z | [
"python",
"django",
"py2exe"
] | We'd like to create a Django Intranet application for mass market. We only need to support Windows users, and it needs to be very easy for a Windows admin (or "technical user") to deploy (baring in mind that most Windows admins/users have little experience with Python, etc).
Is Django + py2exe the answer? Do we need s... | Yes, you require:
* Python 2.5.2
* Django (svn version at
least 2008-06-05)
* CherryPy (web
server)
* Py2Exe
[Tutorial](http://misunderstandings.wordpress.com/2008/06/26/django-desktop-app/) |
Help sorting: first by this, and then by that | 1,657,242 | 5 | 2009-11-01T14:04:59Z | 1,657,283 | 10 | 2009-11-01T14:21:44Z | [
"python",
"sorting"
] | I have a list of tuples I am trying to sort and could use some help.
The field I want to sort by in the tuples looks like "XXX\_YYY". First, I want to group the XXX values in reverse order, and then, within those groups, I want to place the YYY values in normal sort order. (NOTE: I am just as happy, actually, sorting ... | ```
def my_cmp(x, y):
x1, x2 = x[0].split('_')
y1, y2 = y[0].split('_')
return -cmp(x1, y1) or cmp(x2, y2)
my_list = [
(u'community_news', u'Community: News & Information'),
(u'kf_video', u'KF: Video'),
(u'community_video', u'Community: Video'),
(u'kf_news', u'KF: News & Information'),
(u... |
Help sorting: first by this, and then by that | 1,657,242 | 5 | 2009-11-01T14:04:59Z | 1,657,512 | 8 | 2009-11-01T16:01:42Z | [
"python",
"sorting"
] | I have a list of tuples I am trying to sort and could use some help.
The field I want to sort by in the tuples looks like "XXX\_YYY". First, I want to group the XXX values in reverse order, and then, within those groups, I want to place the YYY values in normal sort order. (NOTE: I am just as happy, actually, sorting ... | Custom *comparison* functions for sorting, as suggested in existing answers, do make it easy to sort in a mix of ascending and descending orders -- but they have serious performance issues and have been removed in Python 3, leaving only the preferred customization approach -- custom **key-extraction** functions... much... |
How do I read two lines from a file at a time using python | 1,657,299 | 61 | 2009-11-01T14:27:27Z | 1,657,318 | 33 | 2009-11-01T14:35:56Z | [
"python"
] | I am coding a python script that parses a text file. The format of this text file is such that each element in the file uses two lines and for convenience I would like to read both lines before parsing. Can this be done in Python?
I would like to some something like:
```
f = open(filename, "r")
for line in f:
lin... | Similar question [here](http://stackoverflow.com/questions/826493/python-mixing-files-and-loops). You can't mix iteration and readline so you need to use one or the other.
```
while True:
line1 = f.readline()
line2 = f.readline()
if not line2: break # EOF
...
``` |
How do I read two lines from a file at a time using python | 1,657,299 | 61 | 2009-11-01T14:27:27Z | 1,657,337 | 18 | 2009-11-01T14:41:06Z | [
"python"
] | I am coding a python script that parses a text file. The format of this text file is such that each element in the file uses two lines and for convenience I would like to read both lines before parsing. Can this be done in Python?
I would like to some something like:
```
f = open(filename, "r")
for line in f:
lin... | use line.next(), eg
```
f=open("file")
for line in f:
print line
nextline=f.next()
print "next line", nextline
....
f.close()
``` |
How do I read two lines from a file at a time using python | 1,657,299 | 61 | 2009-11-01T14:27:27Z | 1,657,385 | 28 | 2009-11-01T15:12:54Z | [
"python"
] | I am coding a python script that parses a text file. The format of this text file is such that each element in the file uses two lines and for convenience I would like to read both lines before parsing. Can this be done in Python?
I would like to some something like:
```
f = open(filename, "r")
for line in f:
lin... | ```
import itertools
with open('a') as f:
for line1,line2 in itertools.izip_longest(*[f]*2):
print(line1,line2)
```
izip\_longest returns an iterator, so it should work well even if the file is very large.
If there are an odd number of lines, then line2 gets the value None on the last iteration.
izip\_lo... |
How do I read two lines from a file at a time using python | 1,657,299 | 61 | 2009-11-01T14:27:27Z | 1,657,503 | 10 | 2009-11-01T16:00:30Z | [
"python"
] | I am coding a python script that parses a text file. The format of this text file is such that each element in the file uses two lines and for convenience I would like to read both lines before parsing. Can this be done in Python?
I would like to some something like:
```
f = open(filename, "r")
for line in f:
lin... | I would proceed in a similar way as [ghostdog74](http://stackoverflow.com/questions/1657299/how-do-i-read-two-lines-from-a-file-at-a-time-using-python/1657337#1657337), only with the try outside and a few modifications:
```
try:
with open(filename) as f:
for line1 in f:
line2 = f.next()
... |
Google Search from a Python App | 1,657,570 | 49 | 2009-11-01T16:21:32Z | 1,657,597 | 71 | 2009-11-01T16:30:16Z | [
"python",
"api",
"google-search-api"
] | I'm trying to run a google search query from a python app. Is there any python interface out there that would let me do this? If there isn't does anyone know which Google API will enable me to do this. Thanks. | There's a simple example [here](http://www.ajaxlines.com/ajax/stuff/article/%5Fgoogle%5Fajax%5Fsearch%5Fapi%5Fexample%5Fpython%5Fcode.php) (peculiarly missing some quotes;-). Most of what you'll see on the web is Python interfaces to the old, discontinued SOAP API -- the example I'm pointing to uses the newer and suppo... |
Google Search from a Python App | 1,657,570 | 49 | 2009-11-01T16:21:32Z | 1,658,018 | 16 | 2009-11-01T19:09:14Z | [
"python",
"api",
"google-search-api"
] | I'm trying to run a google search query from a python app. Is there any python interface out there that would let me do this? If there isn't does anyone know which Google API will enable me to do this. Thanks. | Here is Alex's answer ported to Python3
```
#!/usr/bin/python3
import json
import urllib.request, urllib.parse
def showsome(searchfor):
query = urllib.parse.urlencode({'q': searchfor})
url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&%s' % query
search_response = urllib.request.urlopen(url)
se... |
Google Search from a Python App | 1,657,570 | 49 | 2009-11-01T16:21:32Z | 8,802,156 | 11 | 2012-01-10T10:57:45Z | [
"python",
"api",
"google-search-api"
] | I'm trying to run a google search query from a python app. Is there any python interface out there that would let me do this? If there isn't does anyone know which Google API will enable me to do this. Thanks. | Here's my approach to this: <http://breakingcode.wordpress.com/2010/06/29/google-search-python/>
A couple code examples:
```
# Get the first 20 hits for: "Breaking Code" WordPress blog
from google import search
for url in search('"Breaking Code" WordPress blog', stop=20):
print(url)
# Get the... |
Controlling rsync with Python? | 1,657,614 | 17 | 2009-11-01T16:36:51Z | 1,657,700 | 20 | 2009-11-01T17:15:00Z | [
"python",
"bash",
"automation",
"rsync"
] | I've been wanting to write a python script that would run several instances of rsync in sequence for backing up data to a different computer.
At the moment I just have this text file with the commands I use and I've just been copy-pasting them into the terminal, and it seems kinda silly.
I want to be able to use pyth... | If you'd like to interact with a subprocess in general, you can use [pexpect](http://www.noah.org/wiki/Pexpect) as mentioned elsewhere. But for your particular case, assuming your rsync is running over ssh (the default), then you may want to consider setting up a [passwordless ssh](http://www.debian-administration.org/... |
Controlling rsync with Python? | 1,657,614 | 17 | 2009-11-01T16:36:51Z | 4,514,596 | 7 | 2010-12-22T23:17:44Z | [
"python",
"bash",
"automation",
"rsync"
] | I've been wanting to write a python script that would run several instances of rsync in sequence for backing up data to a different computer.
At the moment I just have this text file with the commands I use and I've just been copy-pasting them into the terminal, and it seems kinda silly.
I want to be able to use pyth... | There's a great Python module written by Colin Stewart called RSyncBackup that's little known and little documented, but very useful.
By default, it doesn't contain any methods for including a password in your rsync commands, so I modified the module and talked about it in this blog post: <http://technofart.blogspot.c... |
Subversion python bindings could not be loaded | 1,657,918 | 20 | 2009-11-01T18:36:09Z | 1,657,981 | 14 | 2009-11-01T18:55:32Z | [
"python",
"windows",
"svn",
"mercurial"
] | This is a but of a part 2 in trying to convert an SVN repository to a Mercurial one
command is:
```
hg convert file://c:/svnrepository
```
but, the output I get is:
```
assuming destination svnrepository-hg
initializing destination svnrepository-hg repository
file://c:/svnrepository does not look like a CVS checkou... | The problem's explained [here](http://mercurial.selenic.com/wiki/ConvertExtension) at heading "Converting from Subversion":
> Subversion's Python bindings are a
> prerequisite. The bindings (generated
> with SWIG) are installed separately on
> Windows, and can be found on
> <http://subversion.tigris.org/> . Note
> tha... |
Subversion python bindings could not be loaded | 1,657,918 | 20 | 2009-11-01T18:36:09Z | 3,410,421 | 21 | 2010-08-04T22:37:32Z | [
"python",
"windows",
"svn",
"mercurial"
] | This is a but of a part 2 in trying to convert an SVN repository to a Mercurial one
command is:
```
hg convert file://c:/svnrepository
```
but, the output I get is:
```
assuming destination svnrepository-hg
initializing destination svnrepository-hg repository
file://c:/svnrepository does not look like a CVS checkou... | I just wanted to bring the actual solution out of the comments to Alex Martelli's answer:
> According to: selenic.com/pipermail/mercurial/2009-May/⦠the subversion bindings are included in tortoisehg. So you just need to enable the convert extension in tortoisehg. â tonfa
>
> Ah ha! Another step forward. I changed... |
Why is there a need to explicitly delete the sys.exc_info() traceback in Python? | 1,658,293 | 9 | 2009-11-01T20:57:14Z | 1,658,335 | 9 | 2009-11-01T21:11:56Z | [
"python"
] | I've seen in different code bases and just read on PyMOTW (see the first Note [here](http://www.doughellmann.com/PyMOTW/sys/exceptions.html)).
The explanation says that a cycle will be created in case the traceback is assigned to a variable from `sys.exc_info()[2]`, but why is that?
How big of a problem is this? Shou... | The traceback contains references to all the active frames, which in turn contain references to all the local variables in those various frames -- those references are a big part of the very job of traceback and frame objects, so that's hardly surprising. So, if you add a reference back to the traceback (or fail to rem... |
Why is there a need to explicitly delete the sys.exc_info() traceback in Python? | 1,658,293 | 9 | 2009-11-01T20:57:14Z | 1,658,336 | 18 | 2009-11-01T21:12:03Z | [
"python"
] | I've seen in different code bases and just read on PyMOTW (see the first Note [here](http://www.doughellmann.com/PyMOTW/sys/exceptions.html)).
The explanation says that a cycle will be created in case the traceback is assigned to a variable from `sys.exc_info()[2]`, but why is that?
How big of a problem is this? Shou... | The Python garbage collector will, eventually, find and delete circular references like the one created by referring to a traceback stack from inside one of the stack frames themselves, so don't go back and rewrite your code. But, going forward, you could follow the advice of
<http://docs.python.org/library/sys.html>
... |
searching within nested list in python | 1,658,505 | 4 | 2009-11-01T21:57:23Z | 1,658,785 | 11 | 2009-11-01T23:30:51Z | [
"python",
"list",
"nested",
"search"
] | I have a list:
```
l = [['en', 60, 'command'],['sq', 34, 'komand']]
```
I want to search for `komand` or `sq` and get `l[1]` returned.
Can I somehow define my own matching function for list searches? | An expression like:
```
next(subl for subl in l if 'sq' in subl)
```
will give you exactly the sublist you're searching for (or raise `StopIteration` if there is no such sublist; if the latter behavior is not what you want, pass `next` a second argument [[e.g, `[]` or `None`, depending on what exactly you want!]] to ... |
Range of valid numpy values | 1,658,714 | 14 | 2009-11-01T23:07:07Z | 1,658,752 | 26 | 2009-11-01T23:19:26Z | [
"python",
"numpy"
] | I'm interested in finding for a particular Numpy type (e.g. np.int64, np.uint32, np.float32, etc.) what the range of all possible valid values is (e.g. np.int32 can store numbers up to 2\*\*31-1). Of course, I guess one can theoretically figure this out for each type, but is there a way to do this at run time to ensure... | Quoting from a numpy dicussion list:
```
That kind of information is available via numpy.finfo() and numpy.iinfo():
In [12]: finfo('d').max
Out[12]: 1.7976931348623157e+308
In [13]: iinfo('i').max
Out[13]: 2147483647
In [14]: iinfo(uint8).max
Out[14]: 255
```
The link is here: [link to numpy discussion group page]... |
Range of valid numpy values | 1,658,714 | 14 | 2009-11-01T23:07:07Z | 1,658,755 | 10 | 2009-11-01T23:20:55Z | [
"python",
"numpy"
] | I'm interested in finding for a particular Numpy type (e.g. np.int64, np.uint32, np.float32, etc.) what the range of all possible valid values is (e.g. np.int32 can store numbers up to 2\*\*31-1). Of course, I guess one can theoretically figure this out for each type, but is there a way to do this at run time to ensure... | You can use [`numpy.iinfo(arg).max`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.iinfo.html) to find the max value for integer types of `arg`, and [`numpy.finfo(arg).max`](http://docs.scipy.org/doc/numpy/reference/generated/numpy.finfo.html) to find the max value for float types of `arg`.
```
>>> numpy.i... |
Random int64 and float64 numbers | 1,658,808 | 8 | 2009-11-01T23:42:29Z | 1,658,874 | 7 | 2009-11-02T00:12:37Z | [
"python",
"random",
"numpy"
] | I'm trying to generate random 64-bit integer values for integers and floats using Numpy, **within the entire range of valid values for that type**. To generate random 32-bit floats, I can use:
```
In [2]: np.random.uniform(low=np.finfo(np.float32).min,high=np.finfo(np.float32).max,size=10)
Out[2]:
array([ 1.47351436... | For integers you could generate 2 32 bit random numbers and combine them:
```
a + (b << 32)
``` |
How to write a memory efficient Python program? | 1,659,659 | 7 | 2009-11-02T06:08:08Z | 1,660,031 | 7 | 2009-11-02T08:31:35Z | [
"python",
"memory",
"memory-management"
] | It's said that Python automatically manages memory. I'm confused because I have a Python program consistently uses more than 2GB of memory.
It's a simple multi-thread binary data downloader and unpacker.
```
def GetData(url):
req = urllib2.Request(url)
response = urllib2.urlopen(req)
data = response.read(... | The major culprit here is as mentioned above the range() call. It will create a list with 15 million members, and that will eat up 200 MB of your memory, and with 15 processes, that's 3GB.
But also don't read in the whole 15MB file into data(), read bit by bit from the response. Sticking those 15MB into a variable wil... |
How to write a memory efficient Python program? | 1,659,659 | 7 | 2009-11-02T06:08:08Z | 1,660,263 | 8 | 2009-11-02T09:40:03Z | [
"python",
"memory",
"memory-management"
] | It's said that Python automatically manages memory. I'm confused because I have a Python program consistently uses more than 2GB of memory.
It's a simple multi-thread binary data downloader and unpacker.
```
def GetData(url):
req = urllib2.Request(url)
response = urllib2.urlopen(req)
data = response.read(... | Like others have said, you need at least the following two changes:
1. Do not create a huge list of integers with `range`
```
# use xrange
for i in xrange(0, count):
# UNPACK FIXED LENGTH OF BINARY DATA HERE
yield (field1, field2, field3)
```
2. do not create a huge string as the full file b... |
read string backwards and terminate at first '/' | 1,660,059 | 3 | 2009-11-02T08:42:14Z | 1,660,081 | 12 | 2009-11-02T08:47:47Z | [
"python",
"path"
] | I want to extract just the file name portion of a path. My code below works, but I'd like to know what the better (pythonic) way of doing this is.
```
filename = ''
tmppath = '/dir1/dir2/dir3/file.exe'
for i in reversed(tmppath):
if i != '/':
filename += str(i)
else:
bre... | Try:
```
#!/usr/bin/python
import os.path
path = '/dir1/dir2/dir3/file.exe'
name = os.path.basename(path)
print name
``` |
Python fetching <title> | 1,660,302 | 3 | 2009-11-02T09:48:59Z | 1,660,336 | 7 | 2009-11-02T09:55:11Z | [
"python",
"urllib2"
] | I want to fetch the title of a webpage which I open using urllib2. What is the best way to do this, to parse the html and find what I need (for now only the -tag but might need more in the future).
Is there a good parsing lib for this purpose? | Yes I would recommend [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/)
If you're getting the title it's simply:
```
soup = BeautifulSoup(html)
myTitle = soup.html.head.title
```
or
```
myTitle = soup('title')
```
Taken from [the documentation](http://www.crummy.com/software/BeautifulSoup/documentatio... |
PyQt and MVC-pattern | 1,660,474 | 16 | 2009-11-02T10:27:34Z | 1,690,593 | 26 | 2009-11-06T21:29:45Z | [
"python",
"design",
"qt",
"pyqt"
] | Please, help me with designing MVC-pattern with PyQt.
I want to split all program at 3 parts:
1. some class that is abstracted from all Qt classes(model)
2. some class that provides data from model to qt-app(controller)
3. Qt-app itself with defined method SignalsToSlots that connect signals with controller.
Is it op... | One of the first things you should do is use Qt4 designer to design your gui and use pyuic4 to generate your python GUI. This will be your view, you NEVER edit these python files by hand. Always make changes using designer, this ensures your View is separate from your model and control.
For the control element, create... |
Nose test script with command line arguments | 1,660,520 | 10 | 2009-11-02T10:41:57Z | 1,661,171 | 12 | 2009-11-02T12:58:25Z | [
"python",
"command-line-arguments",
"nose"
] | I would like to be able to run a nose test script which accepts command line arguments. For example, something along the lines:
test.py
```
import nose, sys
def test():
# do something with the command line arguments
print sys.argv
if __name__ == '__main__':
nose.runmodule()
```
However, whenever I run ... | Alright, I hate "why would you want to do that?" answers just as much as anyone, but I'm going to have to make one here. I hope you don't mind.
I'd argue that doing whatever you're wanting to do isn't within the scope of the framework nose. Nose is intended for *automated* tests. If you have to pass in command-line ar... |
Nose test script with command line arguments | 1,660,520 | 10 | 2009-11-02T10:41:57Z | 16,290,369 | 9 | 2013-04-30T00:26:25Z | [
"python",
"command-line-arguments",
"nose"
] | I would like to be able to run a nose test script which accepts command line arguments. For example, something along the lines:
test.py
```
import nose, sys
def test():
# do something with the command line arguments
print sys.argv
if __name__ == '__main__':
nose.runmodule()
```
However, whenever I run ... | You could use another means of getting stuff into your code:
```
import os
print os.getenv('KEY_THAT_MIGHT_EXIST', default_value)
```
Then just remember to set your environment before running nose. |
Check if object is file-like in Python | 1,661,262 | 49 | 2009-11-02T13:13:57Z | 1,661,326 | 29 | 2009-11-02T13:25:38Z | [
"python",
"file"
] | [File-like objects](http://docs.python.org/library/stdtypes.html#bltin-file-objects) are objects in Python that behave like a real file, e.g. have a read() and a write method(), but have a different implementation. It is and realization of the [Duck Typing](http://en.wikipedia.org/wiki/Duck%5Ftyping) concept.
It is co... | The dominant paradigm here is EAFP: easier to ask forgiveness than permission. Go ahead and use the file interface, then handle the resulting exception, or let them propagate to the caller. |
Check if object is file-like in Python | 1,661,262 | 49 | 2009-11-02T13:13:57Z | 1,661,354 | 26 | 2009-11-02T13:29:29Z | [
"python",
"file"
] | [File-like objects](http://docs.python.org/library/stdtypes.html#bltin-file-objects) are objects in Python that behave like a real file, e.g. have a read() and a write method(), but have a different implementation. It is and realization of the [Duck Typing](http://en.wikipedia.org/wiki/Duck%5Ftyping) concept.
It is co... | It is generally not good practice to have checks like this in your code at all unless you have special requirements.
In Python the typing is dynamic, why do you feel need to check whether the object is file like, rather than just using it as if it was a file and handling the resulting error?
Any check you can do is g... |
Check if object is file-like in Python | 1,661,262 | 49 | 2009-11-02T13:13:57Z | 1,661,454 | 31 | 2009-11-02T13:52:57Z | [
"python",
"file"
] | [File-like objects](http://docs.python.org/library/stdtypes.html#bltin-file-objects) are objects in Python that behave like a real file, e.g. have a read() and a write method(), but have a different implementation. It is and realization of the [Duck Typing](http://en.wikipedia.org/wiki/Duck%5Ftyping) concept.
It is co... | As others have said you should generally avoid such checks. One exception is when the object might legitimately be different types and you want different behaviour depending on the type. The EAFP method doesn't always work here as an object could look like more than one type of duck!
For example an initialiser could t... |
Check if object is file-like in Python | 1,661,262 | 49 | 2009-11-02T13:13:57Z | 6,867,901 | 9 | 2011-07-29T02:04:21Z | [
"python",
"file"
] | [File-like objects](http://docs.python.org/library/stdtypes.html#bltin-file-objects) are objects in Python that behave like a real file, e.g. have a read() and a write method(), but have a different implementation. It is and realization of the [Duck Typing](http://en.wikipedia.org/wiki/Duck%5Ftyping) concept.
It is co... | It's often useful to raise an error by checking a condition, when that error normally wouldn't be raised until much later on. This is especially true for the boundary between 'user-land' and 'api' code.
You wouldn't place a metal detector at a police station on the exit door, you would place it at the entrance! If not... |
Check if object is file-like in Python | 1,661,262 | 49 | 2009-11-02T13:13:57Z | 24,812,058 | 9 | 2014-07-17T19:36:16Z | [
"python",
"file"
] | [File-like objects](http://docs.python.org/library/stdtypes.html#bltin-file-objects) are objects in Python that behave like a real file, e.g. have a read() and a write method(), but have a different implementation. It is and realization of the [Duck Typing](http://en.wikipedia.org/wiki/Duck%5Ftyping) concept.
It is co... | For 3.1+, one of the following:
```
isinstance(something, io.TextIOBase)
isinstance(something, io.BufferedIOBase)
isinstance(something, io.RawIOBase)
isinstance(something, io.IOBase)
```
For 2.x, "file-like object" is too vague a thing to check for, but the documentation for whatever function(s) you're dealing with w... |
Disable boto logging without modifying the boto files | 1,661,275 | 21 | 2009-11-02T13:15:48Z | 1,667,019 | 45 | 2009-11-03T12:23:56Z | [
"python",
"logging",
"amazon-web-services",
"boto"
] | I am using the Boto library to talk to AWS. I want to disable logging. (Or redirect to /dev/null or other file). I cant find an obvious way to do this. I tried this, but that doesn't seem to help.
```
import boto
boto.set_file_logger('boto', 'logs/boto.log')
```
This says it is possible, <http://developer.amazonwebse... | You could try
```
import logging
logging.getLogger('boto').setLevel(logging.CRITICAL)
```
which will suppress all (other than CRITICAL) errors.
Boto uses logging configuration files (e.g. `/etc/boto.cfg`, `~/.boto`) so see if you can configure it to your needs that way.
The `set_file_logger` call simply adds a user... |
matplotlib for R user? | 1,661,479 | 8 | 2009-11-02T14:01:35Z | 1,662,207 | 10 | 2009-11-02T16:14:29Z | [
"python",
"matplotlib",
"scipy",
"data-visualization"
] | I regularly make figures (the exploratory data analysis type) in R. I also program in Python and was wondering if there are features or concepts in matplotlib that would be worth learning. For instance, I am quite happy with R - but its image() function will produce large files with pixelated output, whereas Matlab's e... | This is a tough one to answer.
I recently switched some of my graphing workload from R to matplotlib. In my humble opinion, I find matplotlib's graphs to be prettier (better default colors, they look crisper and more modern). I also think matplotlib renders PNGs a whole lot better.
The real motivation for me though, ... |
Why doesn't Python's mmap work with large files? | 1,661,986 | 39 | 2009-11-02T15:34:22Z | 1,662,149 | 15 | 2009-11-02T16:01:05Z | [
"python",
"performance",
"memory",
"mmap"
] | I am writing a module that amongst other things allows bitwise read access to files. The files can potentially be large (hundreds of GB) so I wrote a simple class that lets me treat the file like a string and hides all the seeking and reading.
At the time I wrote my wrapper class I didn't know about the [mmap module](... | A 32-bit program and operating system can only address a maximum of 32 bits of memory i.e. 4GB. There are other factors that make the total even smaller; for example, Windows reserves between 0.5 and 2GB for hardware access, and of course your program is going to take some space as well.
**Edit:** The obvious thing yo... |
Why doesn't Python's mmap work with large files? | 1,661,986 | 39 | 2009-11-02T15:34:22Z | 1,662,411 | 34 | 2009-11-02T16:52:46Z | [
"python",
"performance",
"memory",
"mmap"
] | I am writing a module that amongst other things allows bitwise read access to files. The files can potentially be large (hundreds of GB) so I wrote a simple class that lets me treat the file like a string and hides all the seeking and reading.
At the time I wrote my wrapper class I didn't know about the [mmap module](... | From IEEE 1003.1:
> The mmap() function shall establish a
> mapping between a process' address
> space and a file, shared memory
> object, or [TYM] typed memory
> object.
It needs all the virtual address space because that's exactly what `mmap()` *does*.
The fact that it isn't *really* running out of memory doesn't ... |
Why doesn't Python's mmap work with large files? | 1,661,986 | 39 | 2009-11-02T15:34:22Z | 1,663,603 | 8 | 2009-11-02T20:48:42Z | [
"python",
"performance",
"memory",
"mmap"
] | I am writing a module that amongst other things allows bitwise read access to files. The files can potentially be large (hundreds of GB) so I wrote a simple class that lets me treat the file like a string and hides all the seeking and reading.
At the time I wrote my wrapper class I didn't know about the [mmap module](... | the mmap module provides all the tools you need to poke around in your large file, but due to the limitations other folks have mentioned, you can't map it ***all at once***. You can map a good sized chunk at once, do some processing and then unmap that and map another. the key arguments to the `mmap` class are `length`... |
Why doesn't Python's mmap work with large files? | 1,661,986 | 39 | 2009-11-02T15:34:22Z | 1,666,666 | 16 | 2009-11-03T11:04:31Z | [
"python",
"performance",
"memory",
"mmap"
] | I am writing a module that amongst other things allows bitwise read access to files. The files can potentially be large (hundreds of GB) so I wrote a simple class that lets me treat the file like a string and hides all the seeking and reading.
At the time I wrote my wrapper class I didn't know about the [mmap module](... | Sorry to answer my own question, but I think the real problem I had was not realising that mmap was a standard POSIX system call with particular characterisatations and limitations and that the Python mmap is supposed just to expose its functionality.
The Python documentation doesn't mention the POSIX mmap and so if y... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.