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
Decoding HTML entities with Python
1,208,916
17
2009-07-30T19:47:34Z
1,209,015
18
2009-07-30T20:05:12Z
[ "python", "unicode", "character-encoding", "content-type", "beautifulsoup" ]
I'm trying to decode HTML entries from here [NYTimes.com](http://www.nytimes.com/2009/07/31/world/middleeast/31adviser.html?%5Fr=1&hp) and I cannot figure out what I am doing wrong. Take for example: ``` "U.S. Adviser’s Blunt Memo on Iraq: Time ‘to Go Home’" ``` I've tried BeautifulSoup, decode('is...
This does work: ``` from BeautifulSoup import BeautifulStoneSoup s = "U.S. Adviser’s Blunt Memo on Iraq: Time ‘to Go Home’" decoded = BeautifulStoneSoup(s, convertEntities=BeautifulStoneSoup.HTML_ENTITIES) ``` If you want a string instead of a Unicode object, you'll need to decode it to an encoding ...
Decoding HTML entities with Python
1,208,916
17
2009-07-30T19:47:34Z
1,209,922
19
2009-07-30T23:18:53Z
[ "python", "unicode", "character-encoding", "content-type", "beautifulsoup" ]
I'm trying to decode HTML entries from here [NYTimes.com](http://www.nytimes.com/2009/07/31/world/middleeast/31adviser.html?%5Fr=1&hp) and I cannot figure out what I am doing wrong. Take for example: ``` "U.S. Adviser’s Blunt Memo on Iraq: Time ‘to Go Home’" ``` I've tried BeautifulSoup, decode('is...
Actually what you have are not HTML entities. There are THREE varieties of those &.....; thingies -- for example `     ` all mean U+00A0 NO-BREAK SPACE. ` ` (the type you have) is a "numeric character reference" (decimal). ` ` is a "numeric character reference" (hexadecimal). ` ` is a...
Decoding HTML entities with Python
1,208,916
17
2009-07-30T19:47:34Z
20,715,131
10
2013-12-21T03:37:21Z
[ "python", "unicode", "character-encoding", "content-type", "beautifulsoup" ]
I'm trying to decode HTML entries from here [NYTimes.com](http://www.nytimes.com/2009/07/31/world/middleeast/31adviser.html?%5Fr=1&hp) and I cannot figure out what I am doing wrong. Take for example: ``` "U.S. Adviser’s Blunt Memo on Iraq: Time ‘to Go Home’" ``` I've tried BeautifulSoup, decode('is...
``` >>> from HTMLParser import HTMLParser >>> print HTMLParser().unescape('U.S. Adviser’s Blunt Memo on Iraq: ' ... 'Time ‘to Go Home’') U.S. Adviser’s Blunt Memo on Iraq: Time ‘to Go Home’ ``` The function is undocumented in Python 2. [It is fixed in Python 3.4+](ht...
Handling Windows-specific exceptions in platform-independent way
1,210,118
5
2009-07-31T00:36:15Z
1,210,193
10
2009-07-31T01:02:51Z
[ "python", "windows", "exception", "exception-handling" ]
Consider the following Python exception: ``` [...] f.extractall() File "C:\Python26\lib\zipfile.py", line 935, in extractall self.extract(zipinfo, path, pwd) File "C:\Python26\lib\zipfile.py", line 923, in extract return self._extract_member(member, path, pwd) File "C:\Python26\lib\zipfile.py", lin...
If you need to catch an exception with a name that might not always exist, then create it: ``` if not getattr(__builtins__, "WindowsError", None): class WindowsError(OSError): pass try: do() except WindowsError, e: print "error" ``` If you're on Windows, you'll use the real WindowsError class and catch t...
No module named _sqlite3
1,210,664
55
2009-07-31T04:21:03Z
1,210,746
8
2009-07-31T04:50:35Z
[ "python", "django", "sqlite", "debian" ]
I am trying to run a [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29) app on my [VPS](http://en.wikipedia.org/wiki/Virtual_private_server) running [Debian](http://en.wikipedia.org/wiki/Debian#Releases) 5. When I run a demo app, it comes back with this error: ``` File "/usr/local/lib/python2.5/site-p...
My \_sqlite3.so is in /usr/lib/python2.5/lib-dynload/\_sqlite3.so. Judging from your paths, you should have the file /usr/local/lib/python2.5/lib-dynload/\_sqlite3.so. Try the following: ``` find /usr/local -name _sqlite3.so ``` If the file isn't found, something may be wrong with your Python installation. If it is,...
No module named _sqlite3
1,210,664
55
2009-07-31T04:21:03Z
2,747,227
54
2010-04-30T19:46:42Z
[ "python", "django", "sqlite", "debian" ]
I am trying to run a [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29) app on my [VPS](http://en.wikipedia.org/wiki/Virtual_private_server) running [Debian](http://en.wikipedia.org/wiki/Debian#Releases) 5. When I run a demo app, it comes back with this error: ``` File "/usr/local/lib/python2.5/site-p...
I had the same problem (building `python2.5` from source on Ubuntu Lucid), and `import sqlite3` threw this same exception. I've installed `libsqlite3-dev` from the package manager, recompiled python2.5, and then the import worked.
No module named _sqlite3
1,210,664
55
2009-07-31T04:21:03Z
19,748,196
8
2013-11-02T23:40:35Z
[ "python", "django", "sqlite", "debian" ]
I am trying to run a [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29) app on my [VPS](http://en.wikipedia.org/wiki/Virtual_private_server) running [Debian](http://en.wikipedia.org/wiki/Debian#Releases) 5. When I run a demo app, it comes back with this error: ``` File "/usr/local/lib/python2.5/site-p...
This is what I did to get it to work. I am using pythonbrew(which is using pip) with python 2.7.5 installed. I first did what Zubair(above) said and ran this command: ``` sudo apt-get install libsqlite3-dev ``` Then I ran this command: ``` pip install pysqlite ``` This fixed the database problem and I got confirm...
No module named _sqlite3
1,210,664
55
2009-07-31T04:21:03Z
24,449,632
16
2014-06-27T10:28:29Z
[ "python", "django", "sqlite", "debian" ]
I am trying to run a [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29) app on my [VPS](http://en.wikipedia.org/wiki/Virtual_private_server) running [Debian](http://en.wikipedia.org/wiki/Debian#Releases) 5. When I run a demo app, it comes back with this error: ``` File "/usr/local/lib/python2.5/site-p...
it's seems your makefile didn't include the appropriate `.so` file. I corrected this problem with the steps below: 1. Install `sqlite-devel` (or `libsqlite3-dev` on some Debian-based systems) 2. re-configured and re-compiled Python with `./configure --enable-loadable-sqlite-extensions && make && make install`
No module named _sqlite3
1,210,664
55
2009-07-31T04:21:03Z
34,129,584
7
2015-12-07T08:50:12Z
[ "python", "django", "sqlite", "debian" ]
I am trying to run a [Django](http://en.wikipedia.org/wiki/Django_%28web_framework%29) app on my [VPS](http://en.wikipedia.org/wiki/Virtual_private_server) running [Debian](http://en.wikipedia.org/wiki/Debian#Releases) 5. When I run a demo app, it comes back with this error: ``` File "/usr/local/lib/python2.5/site-p...
1. Install the `sqlite-devel` package: `yum install sqlite-devel -y` 2. Recompile python from the source: ``` ./configure make make altinstall ```
Simple non-web based bug tracker
1,211,463
9
2009-07-31T09:10:19Z
1,213,232
8
2009-07-31T15:34:22Z
[ "python", "windows", "bug-tracking", "non-web" ]
There's a ton and and a half of questions and even more answers here concerning people looking for bug trackers. However all of them (that I found) seem to be about web based solutions. Since I'm working on a local project where I don't want to set up a web / DB server, and I don't want to use a hosted tracker either, ...
Trac might be a bit too over engineered, but you could still run it locally via tracd on localhost. It's: * opensource. * pure Python * uses sqlite But as I said, might be too complex for your use case. Link: <http://trac.edgewall.org>
Simple non-web based bug tracker
1,211,463
9
2009-07-31T09:10:19Z
1,508,055
8
2009-10-02T06:50:29Z
[ "python", "windows", "bug-tracking", "non-web" ]
There's a ton and and a half of questions and even more answers here concerning people looking for bug trackers. However all of them (that I found) seem to be about web based solutions. Since I'm working on a local project where I don't want to set up a web / DB server, and I don't want to use a hosted tracker either, ...
I'm surprised nobody has mentioned [Roundup](http://roundup.sourceforge.net/). It meets all your criteria, including not requiring a web-based interface (as per your specification, and unlike the accepted answer which suggested Trac). Roundup is: * Open source * Pure Python * Supports SQLite * Not fancy, focuses on ...
Python: high precision time.sleep
1,211,806
27
2009-07-31T10:25:43Z
1,211,827
45
2009-07-31T10:32:42Z
[ "python" ]
can you tell me how can I get a high precision sleep-function in Python2.6 on Win32 and on Linux?
You can use floating-point numbers in [`sleep()`](http://docs.python.org/library/time.html#time.sleep): > The argument may be a floating point number to indicate a more precise sleep time. So ``` time.sleep(0.5) ``` will sleep for half a second. In practice, however, it's unlikely that you will get much more than ...
Python: high precision time.sleep
1,211,806
27
2009-07-31T10:25:43Z
1,212,070
7
2009-07-31T11:38:35Z
[ "python" ]
can you tell me how can I get a high precision sleep-function in Python2.6 on Win32 and on Linux?
Here is a similar question: [how-accurate-is-pythons-time-sleep](http://stackoverflow.com/questions/1133857/how-accurate-is-pythons-time-sleep) On **linux** if you need high accuracy you might want to look into using ctypes to call [nanosleep()](http://linux.die.net/man/2/nanosleep) or [clock\_nanosleep()](http://lin...
Python Interpreter blocks Multithreaded DNS requests?
1,212,716
7
2009-07-31T14:03:56Z
1,212,821
15
2009-07-31T14:23:30Z
[ "python", "multithreading", "network-programming" ]
I just played around a little bit with python and threads, and realized even in a multithreaded script, DNS requests are blocking. Consider the following script: from threading import Thread import socket ``` class Connection(Thread): def __init__(self, name, url): Thread.__init__(self) self._url ...
On some systems, getaddrinfo is not thread-safe. Python believes that some such systems are FreeBSD, OpenBSD, NetBSD, OSX, and VMS. On those systems, Python maintains a lock specifically for the netdb (i.e. getaddrinfo and friends). So if you can't switch operating systems, you'll have to use a different (thread-safe)...
Detecting when a python script is being run interactively in ipython
1,212,779
5
2009-07-31T14:15:58Z
1,212,907
11
2009-07-31T14:37:48Z
[ "python", "interactive", "ipython" ]
Is there a way for a python script to automatically detect whether it is being run interactively or not? Alternatively, can one detect whether ipython is being used versus the regular c python executable? Background: My python scripts generally have a call to exit() in them. From time to time, I run the scripts intera...
I stumbed on the following and it seems to do the trick for me: ``` def in_ipython(): try: __IPYTHON__ except NameError: return False else: return True ```
What is the most compatible way to install python modules on a Mac?
1,213,690
108
2009-07-31T16:58:55Z
1,213,795
122
2009-07-31T17:20:22Z
[ "python", "osx", "module", "packages", "macports" ]
I'm starting to learn python and loving it. I work on a Mac mainly as well as Linux. I'm finding that on Linux (Ubuntu 9.04 mostly) when I install a python module using apt-get it works fine. I can import it with no trouble. On the Mac, I'm used to using Macports to install all the Unixy stuff. However, I'm finding th...
The most popular way to manage python packages (if you're not using your system package manager) is to use setuptools and easy\_install. It is probably already installed on your system. Use it like this: ``` easy_install django ``` easy\_install uses the [Python Package Index](http://pypi.python.org) which is an amaz...
What is the most compatible way to install python modules on a Mac?
1,213,690
108
2009-07-31T16:58:55Z
1,213,823
30
2009-07-31T17:25:10Z
[ "python", "osx", "module", "packages", "macports" ]
I'm starting to learn python and loving it. I work on a Mac mainly as well as Linux. I'm finding that on Linux (Ubuntu 9.04 mostly) when I install a python module using apt-get it works fine. I can import it with no trouble. On the Mac, I'm used to using Macports to install all the Unixy stuff. However, I'm finding th...
Please see [Python OS X development environment](http://stackoverflow.com/questions/1169025/python-os-x-10-5-development-environment). The best way is to use [MacPorts](http://www.macports.org/). Download and install MacPorts, then install Python via MacPorts by typing the following commands in the Terminal: ``` sudo ...
What is the most compatible way to install python modules on a Mac?
1,213,690
108
2009-07-31T16:58:55Z
7,220,022
37
2011-08-28T09:13:47Z
[ "python", "osx", "module", "packages", "macports" ]
I'm starting to learn python and loving it. I work on a Mac mainly as well as Linux. I'm finding that on Linux (Ubuntu 9.04 mostly) when I install a python module using apt-get it works fine. I can import it with no trouble. On the Mac, I'm used to using Macports to install all the Unixy stuff. However, I'm finding th...
Your question is already three years old and there are some details not covered in other answers: Most people I know use [HomeBrew](http://mxcl.github.com/homebrew/) or [MacPorts](https://trac.macports.org/wiki/Python), I prefer MacPorts because of its clean cut of what is a default Mac OS X environment and my develop...
What user do python scripts run as in windows?
1,213,706
21
2009-07-31T17:02:28Z
1,214,935
41
2009-07-31T21:15:18Z
[ "python", "windows", "file-permissions" ]
I'm trying to have python delete some directories and I get access errors on them. I think its that the python user account doesn't have rights? ``` WindowsError: [Error 5] Access is denied: 'path' ``` is what I get when I run the script. I've tried ``` shutil.rmtree os.remove os.rmdir ``` they all return the...
We've had issues removing files and directories on Windows, even if we had just copied them, if they were set to 'readonly'. `shutil.rmtree()` offers you sort of exception handlers to handle this situation. You call it and provide an exception handler like this: ``` import errno, os, stat, shutil def handleRemoveRead...
Remove ppc from compilation flags in python setup scripts
1,214,133
7
2009-07-31T18:34:03Z
5,808,548
17
2011-04-27T18:07:07Z
[ "python", "python-imaging-library" ]
I'm trying to install PIL on an Intel Mac OS X Leopard machine. Unfortunately, "setup.py build" thinks it should be compiling for ppc. ``` gcc -arch ppc -arch i386 -isysroot /Developer/SDKs/MacOSX10.4u.sdk -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -fno-common -dynamic -DNDEBUG -g -O3 -DHAVE...
The solution that worked for me was: ARCHFLAGS="-arch i386 -arch x86\_64" python setup.py build Just pass the values for the flag right in the command line.
Django transaction.commit_on_success not rolling back transaction
1,214,143
2
2009-07-31T18:35:29Z
1,214,406
8
2009-07-31T19:26:34Z
[ "python", "mysql", "django", "transactions" ]
I'm trying to use Django transactions on MySQL with [the `commit_on_success` decorator](http://docs.djangoproject.com/en/dev/topics/db/transactions/#django-db-transaction-commit-on-success). According to the documentation, "If the function raises an exception, though, Django will roll back the transaction." However, th...
From <http://docs.djangoproject.com/en/dev/ref/databases/>: "The default engine is MyISAM [1]. The main drawback of MyISAM is that it doesn't currently support transactions or foreign keys. On the plus side, it's currently the only engine that supports full-text indexing and searching. "The InnoDB engine is fully tra...
Basic Python dictionary question
1,214,422
2
2009-07-31T19:28:50Z
1,214,443
16
2009-07-31T19:32:22Z
[ "python", "dictionary" ]
I have a dictionary with one key and two values and I want to set each value to a separate variable. d= {'key' : ('value1, value2'), 'key2' : ('value3, value4'), 'key3' : ('value5, value6')} I tried d[key][0] in the hope it would return "value1" but instead it return "v" Any suggestions?
A better solution is to store your value as a two-tuple: ``` d = {'key' : ('value1', 'value2')} ``` That way you don't have to split every time you want to access the values.
Allowing the " - " character in usernames in the Django Admin interface
1,214,453
7
2009-07-31T19:33:23Z
1,214,660
17
2009-07-31T20:18:53Z
[ "python", "django", "django-admin" ]
In our webapp we needed to allow dashes "-" in our usernames. I've enabled that for the consumer signup process just fine with this regex r'^[\w-]+$' How can I tell the admin app so that I can edit usernames in auth > users to allows the "-" character in usernames? Currently I am unable to edit any usernames with dash...
This should be as simple as overriding the behavior of the User ModelAdmin class. In one of your apps, in `admin.py` include the following code. ``` from django.contrib import admin from django import forms from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from django.contrib....
How to get environment from a subprocess in Python
1,214,496
12
2009-07-31T19:44:22Z
2,214,292
21
2010-02-06T18:53:31Z
[ "python", "environment-variables", "subprocess", "popen" ]
I want to call a process via a python program, however, this process need some specific environment variables that are set by another process. How can I get the first process environment variables to pass them to the second? This is what the program look like: ``` import subprocess subprocess.call(['proc1']) # this ...
Here's an example of how you can extract environment variables from a batch or cmd file without creating a wrapper script. Enjoy. ``` from __future__ import print_function import sys import subprocess import itertools def validate_pair(ob): try: if not (len(ob) == 2): print("Unexpected result:...
Filtering dictionaries and creating sub-dictionaries based on keys/values in Python?
1,214,968
5
2009-07-31T21:22:52Z
1,215,039
9
2009-07-31T21:44:29Z
[ "python", "list", "dictionary", "filter" ]
Ok, I'm stuck, need some help from here on... If I've got a main dictionary like this: ``` data = [ {"key1": "value1", "key2": "value2", "key1": "value3"}, {"key1": "value4", "key2": "value5", "key1": "value6"}, {"key1": "value1", "key2": "value8", "key1": "value9"} ] ``` Now, I need to go through that dictionary...
Here is a not so pretty way of doing it. The result is a generator, but if you really want a list you can surround it with a call to `list()`. Mostly it doesn't matter. The predicate is a function which decides for each key/value pair if a dictionary in the list is going to cut it. The default one accepts all. If no k...
oauth google using python
1,215,033
11
2009-07-31T21:42:37Z
5,592,986
19
2011-04-08T09:14:37Z
[ "python", "oauth" ]
i am fairly new to programming for web. and i want to start from scratch here. i tried to search the net but ended up completely confused. now what i want to learn is how to authenticate a google account through a python script. can anyone please provide me with a code fragment or any example. thanks a lot in advance.
I spent a whole day on coding this, after several failed attempts over the past few weeks. This only gets you as far as the first step, but it does so without any external libraries. And yes, I know it's close to two years after the OP, but from what I could see it still needed to be done. ``` #!/usr/bin/python 'demo ...
How might I remove duplicate lines from a file?
1,215,208
17
2009-07-31T22:37:44Z
1,215,234
23
2009-07-31T22:43:14Z
[ "python", "text", "file-io" ]
I have a file with one column. How to delete repeated lines in a file?
If you're on \*nix, try running the following command: ``` sort <file name> | uniq ```
How might I remove duplicate lines from a file?
1,215,208
17
2009-07-31T22:37:44Z
1,215,244
45
2009-07-31T22:46:20Z
[ "python", "text", "file-io" ]
I have a file with one column. How to delete repeated lines in a file?
On Unix/Linux, use the `uniq` command, as per David Locke's answer, or `sort`, as per William Pursell's comment. If you need a Python script: ``` lines_seen = set() # holds lines already seen outfile = open(outfilename, "w") for line in open(infilename, "r"): if line not in lines_seen: # not a duplicate o...
How might I remove duplicate lines from a file?
1,215,208
17
2009-07-31T22:37:44Z
1,216,544
10
2009-08-01T12:51:25Z
[ "python", "text", "file-io" ]
I have a file with one column. How to delete repeated lines in a file?
``` uniqlines = set(open('/tmp/foo').readlines()) ``` this will give you the list of unique lines. writing that back to some file would be as easy as: ``` bar = open('/tmp/bar', 'w').writelines(set(uniqlines)) bar.close() ```
How to list all class properties
1,215,408
9
2009-07-31T23:58:46Z
1,215,428
14
2009-08-01T00:05:19Z
[ "python", "serialization", "properties" ]
I have class SomeClass with properties. For example `id` and `name`: ``` class SomeClass(object): def __init__(self): self.__id = None self.__name = None def get_id(self): return self.__id def set_id(self, value): self.__id = value def get_name(self): return s...
``` property_names=[p for p in dir(SomeClass) if isinstance(getattr(SomeClass,p),property)] ```
How to list all class properties
1,215,408
9
2009-07-31T23:58:46Z
1,215,609
17
2009-08-01T01:45:03Z
[ "python", "serialization", "properties" ]
I have class SomeClass with properties. For example `id` and `name`: ``` class SomeClass(object): def __init__(self): self.__id = None self.__name = None def get_id(self): return self.__id def set_id(self, value): self.__id = value def get_name(self): return s...
``` import inspect def isprop(v): return isinstance(v, property) propnames = [name for (name, value) in inspect.getmembers(SomeClass, isprop)] ``` `inspect.getmembers` gets inherited members as well (and selects members by a predicate, here we coded `isprop` because it's not among the many predefined ones in modul...
Can a Python function take a generator and return generators to subsets of its generated output?
1,215,464
4
2009-08-01T00:24:45Z
1,215,600
8
2009-08-01T01:39:01Z
[ "python", "generator" ]
Let's say I have a generator function like this: ``` import random def big_gen(): i = 0 group = 'a' while group != 'd': i += 1 yield (group, i) if random.random() < 0.20: group = chr(ord(group) + 1) ``` Example output might be: ('a', 1), ('a', 2), ('a', 3), ('a', 4), ('a', 5), ('a', 6), ('a', ...
Sure, this does what you want: ``` import itertools import operator def main(): for let, gen in itertools.groupby(big_gen(), key=operator.itemgetter(0)): secgen = itertools.imap(operator.itemgetter(1), gen) printer(let, secgen) ``` `groupby` does the bulk of the work here -- the `key=` just tells it what f...
Ubuntu + virtualenv = a mess? virtualenv hates dist-packages, wants site-packages
1,215,610
15
2009-08-01T01:45:22Z
1,215,627
9
2009-08-01T01:52:29Z
[ "python", "ubuntu", "setuptools", "virtualenv" ]
Can someone please explain to me what is going on with python in ubuntu 9.04? I'm trying to spin up `virtualenv`, and the `--no-site-packages` flag seems to do nothing with ubuntu. I installed `virtualenv 1.3.3` with `easy_install` (which I've upgraded to `setuptools 0.6c9`) and everything seems to be installed to `/u...
I'd be tempted to hack it by making site-packages a link to dist-packages, but I guess this might affect other cases where you want to install some extension other than from the ubuntu dist. I can't think of another answer to 1 except tweaking virtualenv's sources (with both ubuntu and virtualenv being so popular I wou...
Ubuntu + virtualenv = a mess? virtualenv hates dist-packages, wants site-packages
1,215,610
15
2009-08-01T01:45:22Z
1,558,028
16
2009-10-13T03:09:20Z
[ "python", "ubuntu", "setuptools", "virtualenv" ]
Can someone please explain to me what is going on with python in ubuntu 9.04? I'm trying to spin up `virtualenv`, and the `--no-site-packages` flag seems to do nothing with ubuntu. I installed `virtualenv 1.3.3` with `easy_install` (which I've upgraded to `setuptools 0.6c9`) and everything seems to be installed to `/u...
I believe Mike Orr's answer from [the virtual-env mailing list](http://groups.google.com/group/python-virtualenv/browse_thread/thread/1412994580f0a2c6/17271fcd6a6e747e?lnk=gst&q=ubuntu+virtualenv#17271fcd6a6e747e) seems to be the best. Note the OP published this question in both places. **Original content of mail:** ...
Is it safe to replace a self object by another object of the same type in a method?
1,216,356
11
2009-08-01T10:42:21Z
1,216,361
21
2009-08-01T10:45:18Z
[ "python" ]
I would like to replace an object instance by another instance inside a method like this: ``` class A: def method1(self): self = func(self) ``` The object is retrieved from a database.
It is unlikely that replacing the 'self' variable will accomplish whatever you're trying to do, that couldn't just be accomplished by storing the result of func(self) in a different variable. 'self' is effectively a local variable only defined for the duration of the method call, used to pass in the instance of the cla...
Python: sorting a dictionary of lists
1,217,251
21
2009-08-01T19:07:17Z
1,217,269
26
2009-08-01T19:15:11Z
[ "python", "list", "sorting", "dictionary" ]
Still learning python (finally!) and can't quite wrap my head around this one yet. What I want to do is sort a dictionary of lists by value using the third item in the list. It's easy enough sorting a dictionary by value when the value is just a single number or string, but this list thing has me baffled. Example: ``...
Here is one way to do this: ``` >>> sorted(myDict.items(), key=lambda e: e[1][2]) [('item2', [8, 2, 3]), ('item1', [7, 1, 9]), ('item3', [9, 3, 11])] ``` The [`key` argument](http://wiki.python.org/moin/HowTo/Sorting#Sortingbykeys) of the `sorted` function lets you derive a sorting key for each element of the list. ...
PyOpenGL + Pygame capped to 60 FPS in Fullscreen
1,217,939
2
2009-08-02T01:22:31Z
1,218,102
7
2009-08-02T03:46:05Z
[ "python", "fullscreen", "pygame", "pyopengl" ]
I'm currently working on a game engine written in pygame and I wanted to add OpenGL support. I wrote a test to see how to make pygame and OpenGL work together, and when it's running in windowed mode, it runs between 150 and 200 fps. When I run it full screen (all I did was add the FULLSCREEN flag when I set up the win...
As frou pointed out, this would be due to Pygame waiting for the vertical retrace when you update the screen by calling `display.flip()`. As the [Pygame `display` documentation](http://www.pygame.org/docs/ref/display.html#pygame.display.flip) notes, if you set the display mode using the `HWSURFACE` or the `DOUBLEBUF` f...
How do I forbid easy_install from zipping eggs?
1,218,058
11
2009-08-02T03:07:06Z
1,218,426
14
2009-08-02T08:25:36Z
[ "python", "setuptools", "easy-install" ]
What must I put into `distutils.cfg` to prevent easy\_install from ever installing a zipped egg? The compression is a nice thought, but I like to be able to grep through and debug that code. I pulled in some dependencies with `python setup.py develop .` A closer look reveals that also accepts the --always-unzip flag. ...
the option is zip-ok, so put the following in your distutils.cfg: ``` [easy_install] # i don't like having zipped files. zip_ok = 0 ```
python's sum() and non-integer values
1,218,710
15
2009-08-02T11:27:41Z
1,218,735
13
2009-08-02T11:42:10Z
[ "python", "list", "sum" ]
Is there a simple and quick way to use sum() with non-integer values? So I can use it like this: ``` class Foo(object): def __init__(self,bar) self.bar=bar mylist=[Foo(3),Foo(34),Foo(63),200] result=sum(mylist) # result should be 300 ``` I tried overriding `__add__` and `__int__` etc, but I don't have f...
You may also need to implement the `__radd__` function, which represents "reverse add" and is called when the arguments can't be resolved in the "forward" direction. For example, `x + y` is evaluated as `x.__add__(y)` if possible, but if that doesn't exist then Python tries `y.__radd__(x)`. Since the `sum()` function ...
python's sum() and non-integer values
1,218,710
15
2009-08-02T11:27:41Z
1,218,742
18
2009-08-02T11:45:03Z
[ "python", "list", "sum" ]
Is there a simple and quick way to use sum() with non-integer values? So I can use it like this: ``` class Foo(object): def __init__(self,bar) self.bar=bar mylist=[Foo(3),Foo(34),Foo(63),200] result=sum(mylist) # result should be 300 ``` I tried overriding `__add__` and `__int__` etc, but I don't have f...
Its a bit tricky - the sum() function takes the start and adds it to the next and so on You need to implement the `__radd__` method: ``` class T: def __init__(self,x): self.x = x def __radd__(self, other): return other + self.x test = (T(1),T(2),T(3),200) print sum(test) ```
Segment a list in Python
1,218,793
8
2009-08-02T12:14:15Z
1,218,810
15
2009-08-02T12:26:09Z
[ "python", "list", "segments" ]
I am looking for an python inbuilt function (or mechanism) to segment a list into required segment lengths (without mutating the input list). Here is the code I already have: ``` >>> def split_list(list, seg_length): ... inlist = list[:] ... outlist = [] ... ... while inlist: ... outlist.appen...
You can use list comprehension: ``` >>> seg_length = 3 >>> a = range(10) >>> [a[x:x+seg_length] for x in range(0,len(a),seg_length)] [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]] ```
Multiple versions of Python on OS X Leopard
1,218,891
21
2009-08-02T13:23:32Z
1,219,166
20
2009-08-02T16:09:49Z
[ "python", "osx", "osx-leopard", "zope" ]
I currently have multiple versions of Python installed on my Mac, the one that came with it, a version I downloaded recently from python.org, an older version used to run Zope locally and another version that Appengine is using. It's kind of a mess. Any recommendations of using one version of python to rule them all? H...
There's nothing inherently wrong with having multiple versions of Python around. Sometimes it's a necessity when using applications with version dependencies. Probably the biggest issue is dealing with site-package dependencies which may vary from app to app. Tools like [`virtualenv`](http://pypi.python.org/pypi/virtua...
Multiple versions of Python on OS X Leopard
1,218,891
21
2009-08-02T13:23:32Z
1,219,486
9
2009-08-02T18:27:39Z
[ "python", "osx", "osx-leopard", "zope" ]
I currently have multiple versions of Python installed on my Mac, the one that came with it, a version I downloaded recently from python.org, an older version used to run Zope locally and another version that Appengine is using. It's kind of a mess. Any recommendations of using one version of python to rule them all? H...
Ian Bicking's [virtualenv](http://pypi.python.org/pypi/virtualenv) allows me to have isolated Pythons for each application I build, and lets me decide whether or not to include the global site-packages in the isolated Python environment. I haven't tried it with Zope, but I'm guessing that the following should work nic...
How to get the biggest numbers out from huge amount of numbers?
1,218,922
10
2009-08-02T13:43:21Z
1,218,945
27
2009-08-02T13:54:27Z
[ "python", "sorting", "max", "minimum" ]
I'd like to get the largest 100 elements out from a list of at least 100000000 numbers. I could sort the entire list and just take the last 100 elements from the sorted list, but that would be very expensive in terms of both memory and time. Is there any existing easy, pythonic way of doing this? What I want is foll...
The heapq module in the standard library offers the nlargest() function to do this: ``` top100 = heapq.nlargest(100, iterable [,key]) ``` It won't sort the entire list, so you won't waste time on the elements you don't need.
Can I redirect the stdout in python into some sort of string buffer?
1,218,933
76
2009-08-02T13:47:50Z
1,218,951
121
2009-08-02T13:57:41Z
[ "python", "stream", "stdout", "redirect" ]
I'm using python's `ftplib` to write a small FTP client, but some of the functions in the package don't return string output, but print to `stdout`. I want to redirect `stdout` to an object which I'll be able to read the output from. I know `stdout` can be redirected into any regular file with: ``` stdout = open("fil...
``` from cStringIO import StringIO import sys old_stdout = sys.stdout sys.stdout = mystdout = StringIO() # blah blah lots of code ... sys.stdout = old_stdout # examine mystdout.getvalue() ```
Can I redirect the stdout in python into some sort of string buffer?
1,218,933
76
2009-08-02T13:47:50Z
1,220,002
30
2009-08-02T22:10:07Z
[ "python", "stream", "stdout", "redirect" ]
I'm using python's `ftplib` to write a small FTP client, but some of the functions in the package don't return string output, but print to `stdout`. I want to redirect `stdout` to an object which I'll be able to read the output from. I know `stdout` can be redirected into any regular file with: ``` stdout = open("fil...
Just to add to Ned's answer above: you can use this to redirect output to **any object that implements a write(str) method**. This can be used to good effect to "catch" stdout output in a GUI application. Here's a silly example in PyQt: ``` import sys from PyQt4 import QtGui class OutputWindow(QtGui.QPlainTextEdit)...
Can I redirect the stdout in python into some sort of string buffer?
1,218,933
76
2009-08-02T13:47:50Z
22,434,594
16
2014-03-16T08:18:22Z
[ "python", "stream", "stdout", "redirect" ]
I'm using python's `ftplib` to write a small FTP client, but some of the functions in the package don't return string output, but print to `stdout`. I want to redirect `stdout` to an object which I'll be able to read the output from. I know `stdout` can be redirected into any regular file with: ``` stdout = open("fil...
There is [contextlib.redirect\_stdout() function](http://docs.python.org/3.4/library/contextlib.html#contextlib.redirect_stdout) in Python 3.4: ``` import io from contextlib import redirect_stdout with io.StringIO() as buf, redirect_stdout(buf): print('redirected') output = buf.getvalue() ``` Here's [code ex...
How do I do database transactions with psycopg2/python db api?
1,219,326
17
2009-08-02T17:26:17Z
1,219,376
21
2009-08-02T17:47:18Z
[ "python", "database", "postgresql" ]
Im fiddling with psycopg2 , and while there's a .commit() and .rollback() there's no .begin() or similar to start a transaction , or so it seems ? I'd expect to be able to do ``` db.begin() # possible even set the isolation level here curs = db.cursor() cursor.execute('select etc... for update') ... cursor.execute('up...
Use `db.set_isolation_level(n)`, assuming `db` is your connection object. As Federico wrote [here](https://web.archive.org/web/20100828225638/http://lists.initd.org/pipermail/psycopg/2004-February/002577.html), the meaning of `n` is: ``` 0 -> autocommit 1 -> read committed 2 -> serialized (but not officially supported...
How do I do database transactions with psycopg2/python db api?
1,219,326
17
2009-08-02T17:26:17Z
1,265,499
10
2009-08-12T11:03:28Z
[ "python", "database", "postgresql" ]
Im fiddling with psycopg2 , and while there's a .commit() and .rollback() there's no .begin() or similar to start a transaction , or so it seems ? I'd expect to be able to do ``` db.begin() # possible even set the isolation level here curs = db.cursor() cursor.execute('select etc... for update') ... cursor.execute('up...
The `BEGIN` with python standard DB API is always implicit. When you start working with the database the driver issues a `BEGIN` and after any `COMMIT` or `ROLLBACK` another `BEGIN` is issued. A python DB API compliant with the specification should always work this way (not only the postgresql). You can change this se...
Python Matplotlib hangs when asked to plot a second chart (after closing first chart window)
1,219,394
5
2009-08-02T17:53:36Z
1,787,772
7
2009-11-24T04:25:16Z
[ "python", "matplotlib" ]
Weird behaviour, I'm sure it's me screwing up, but I'd like to get to the bottom of what's happening: I am running the following code to create a very simple graph window using matplotlib: ``` >>> import matplotlib.pyplot as plt >>> fig = plt.figure() >>> ax = fig.add_subplot(111) >>> ax.plot((1, 3, 1)) [<matplotlib....
Three months late to the party, but I found a suggestion in the matlibplot documentation to use draw() rather than show(); the former apparently just does a render of the current plot, while the latter starts up all the interactive tools, which is where the problems seem to start. It's not terribly prominently placed ...
java and python equivalent of php's foreach($array as $key => $value)
1,219,548
11
2009-08-02T19:02:46Z
1,219,563
30
2009-08-02T19:07:31Z
[ "java", "php", "python", "associative-array" ]
In php, one can handle a list of state names and their abbreviations with an associative array like this: ``` <?php $stateArray = array( "ALABAMA"=>"AL", "ALASKA"=>"AK", // etc... "WYOMING"=>"WY" ); foreach ($stateArray as $stateName => $stateAbbreviation){ print "T...
in Python: ``` for key, value in stateDict.items(): # .iteritems() in Python 2.x print "The abbreviation for %s is %s." % (key, value) ``` in Java: ``` Map<String,String> stateDict; for (Map.Entry<String,String> e : stateDict.entrySet()) System.out.println("The abbreviation for " + e.getKey() + " is " + e.g...
Python GTK Drag and Drop - Get URL
1,219,863
4
2009-08-02T21:09:50Z
1,221,896
8
2009-08-03T11:47:36Z
[ "python", "drag-and-drop", "gtk", "gdk" ]
I'm creating a small app must be able to receive URLs. If the apps window is open, I should be able to drag a link from a browser and drop it into the app - and the app will save the URL to a database. I'm creating this in Python/GTk. But I am a bit confused about the drag and drop functionality in it. So, how do it? ...
You must fetch the data yourself. Here's a simple working example that will set a label to the url dropped: ``` #!/usr/local/env python import pygtk pygtk.require('2.0') import gtk def motion_cb(wid, context, x, y, time): l.set_text('\n'.join([str(t) for t in context.targets])) context.drag_status(gtk.gdk.AC...
Creating Date Intervals in Python
1,220,872
2
2009-08-03T06:19:56Z
1,220,895
7
2009-08-03T06:33:27Z
[ "python", "mysql" ]
I want to use a for loop to print every date between 2 dates. Actually going to merge this with a MySQL query to pass the date into the query itself and into the filename of the output. So, how can I change this: ``` sum = 0 for i in range(1,11): print sum sum += i ``` To this? ``` InputDate = '2009-01-01' for i ...
This will work: ``` import datetime a = datetime.date(2009, 1, 1) b = datetime.date(2009, 7, 1) one_day = datetime.timedelta(1) day = a while day <= b: # do important stuff day += one_day ```
Barchart with vertical labels in python/matplotlib
1,221,108
29
2009-08-03T07:46:13Z
1,221,218
40
2009-08-03T08:32:27Z
[ "python", "charts", "matplotlib", "bar-chart" ]
I'm using matplotlib to generate a (vertical) barchart. The problem is my labels are rather long. Is there any way to display them vertically, either in the bar or above it or below it?
Do you mean something like this: ``` >>> from matplotlib import * >>> plot(xrange(10)) >>> yticks(xrange(10), rotation='vertical') ``` ? In general, to show any text in matplotlib with a vertical orientation, you can add the keyword `rotation='vertical'`. For further options, you can look at help(matplotlib.pyplot....
Find unique elements in tuples in a python list
1,221,775
3
2009-08-03T11:15:37Z
1,221,802
22
2009-08-03T11:24:26Z
[ "python", "list", "set", "tuples" ]
Is there a better way to do this in python, or rather: Is this a good way to do it? ``` x = ('a', 'b', 'c') y = ('d', 'e', 'f') z = ('g', 'e', 'i') l = [x, y, z] s = set([e for (_, e, _) in l]) ``` I looks somewhat ugly but does what i need without writing a complex "get\_unique\_elements\_from\_tuple\_list" functi...
That's fine, that's what sets are for. One thing I would change is this: ``` s = set(e[1] for e in l) ``` as it enhances readability. Note that I also turned the list comprehension into a generator expression; no need to create a temporary list.
Is there a good html parser like HtmlAgilityPack (.NET) for Python?
1,222,222
2
2009-08-03T12:58:05Z
1,222,233
8
2009-08-03T13:00:12Z
[ "python", "html", "parsing" ]
I'm looking for a good html parser like HtmlAgilityPack (open-source .NET project: <http://www.codeplex.com/htmlagilitypack>), but for using with Python. Anyone knows?
Use [Beautiful Soup](http://www.crummy.com/software/BeautifulSoup/) like everyone does.
Is there a good html parser like HtmlAgilityPack (.NET) for Python?
1,222,222
2
2009-08-03T12:58:05Z
1,222,991
8
2009-08-03T15:31:44Z
[ "python", "html", "parsing" ]
I'm looking for a good html parser like HtmlAgilityPack (open-source .NET project: <http://www.codeplex.com/htmlagilitypack>), but for using with Python. Anyone knows?
Others have recommended BeautifulSoup, but it's much better to use [lxml](http://codespeak.net/lxml/). Despite its name, it is also for parsing and scraping HTML. It's much, much faster than BeautifulSoup, and it even handles "broken" HTML better than BeautifulSoup (their claim to fame). It has a compatibility API for ...
List Comprehensions in Python : efficient selection in a list
1,222,677
7
2009-08-03T14:30:18Z
1,222,717
8
2009-08-03T14:38:39Z
[ "python", "list-comprehension" ]
Let's suppose that I have a list of elements, and I want to select only some of them, according to a certain function (for example a *distance* to an other element). I want to have as a result a list of tuple, with the distance and the element. So, I wrote the following code ``` result = [ ( myFunction(C), C) for C i...
Sure, the difference between the following two: ``` [f(x) for x in list] ``` and this: ``` (f(x) for x in list) ``` is that the first will generate the list in memory, whereas the second is a new generator, with lazy evaluation. So, simply write the "unfiltered" list as a generator instead. Here's your code, with ...
Should I Start With Python 3.0?
1,222,782
11
2009-08-03T14:52:17Z
1,222,843
18
2009-08-03T15:00:58Z
[ "python", "python-3.x" ]
Recently I decided to expand my programming horizons and learn the python programming language. While I have used python a little bit for classes in college and for a project or two at work I am by no means an expert. My question is as follows: should I bother with the 2.x releases or should I jump straight to 3.0? I a...
Absolutely not 3.0 - 3.1 is out and is stabler, better, faster in every respect; it makes absolutely no sense to start with 3.0 at this time, if you want to take up the 3 series it should on all accounts be 3.1. As for 2.6 vs 3.1, 3.1 is a better language (especially because some cruft was removed that had accumulated...
Should I Start With Python 3.0?
1,222,782
11
2009-08-03T14:52:17Z
1,225,173
8
2009-08-03T23:53:05Z
[ "python", "python-3.x" ]
Recently I decided to expand my programming horizons and learn the python programming language. While I have used python a little bit for classes in college and for a project or two at work I am by no means an expert. My question is as follows: should I bother with the 2.x releases or should I jump straight to 3.0? I a...
Short answer: Start with Python 2.6. Why: Programming is more fun and useful when you can leverage the work of others. This means using 3rd party libraries often. Many of the popular libraries for Python don't have 3.x support yet. PIL and NumPy/SciPy come to mind. My favorite interpreter, ipython, also doesn't work w...
Should I Start With Python 3.0?
1,222,782
11
2009-08-03T14:52:17Z
1,540,468
7
2009-10-08T21:02:30Z
[ "python", "python-3.x" ]
Recently I decided to expand my programming horizons and learn the python programming language. While I have used python a little bit for classes in college and for a project or two at work I am by no means an expert. My question is as follows: should I bother with the 2.x releases or should I jump straight to 3.0? I a...
Use 3.1 Why? 1) Because as long as everyone is still using 2.6, the libraries will have less reasons to migrate to 3.1. As long as those libraries are not ported to 3.1, you are stuck with the choice of either not using the strengths of 3.1, or only doing the jobs half way by using the hackish solution of using a bac...
GIL in Python 3.1
1,222,929
14
2009-08-03T15:18:55Z
1,222,957
22
2009-08-03T15:25:03Z
[ "python", "multithreading", "gil" ]
Does anybody knows fate of Global Interpreter Lock in Python 3.1 against C++ multithreading integration
GIL is still there in CPython 3.1; the [Unladen Swallow](http://code.google.com/p/unladen-swallow/) projects aims (among many other performance boosts) to eventually remove it, but it's still a way from its goals, and is working on 2.6 first with the intent of eventually porting to 3.x for whatever x will be current by...
GIL in Python 3.1
1,222,929
14
2009-08-03T15:18:55Z
1,225,350
9
2009-08-04T01:17:51Z
[ "python", "multithreading", "gil" ]
Does anybody knows fate of Global Interpreter Lock in Python 3.1 against C++ multithreading integration
The GIL will not affect your code which does not use python objects. In Numpy, we release the GIL for computational code (linear algebra calls, etc...), and the underlying code can use multithreading freely (in fact, those are generally 3rd party libraries which do not know anything about python)
GIL in Python 3.1
1,222,929
14
2009-08-03T15:18:55Z
2,137,581
12
2010-01-26T04:51:43Z
[ "python", "multithreading", "gil" ]
Does anybody knows fate of Global Interpreter Lock in Python 3.1 against C++ multithreading integration
Significant changes will occur in the GIL for Python 3.2. Take a look at the [What's New for Python 3.2](http://docs.python.org/dev/py3k/whatsnew/3.2.html#multi-threading), and [the thread that initiated it in the mailing list](http://mail.python.org/pipermail/python-dev/2009-October/093359.html). While the changes do...
How to write native newline character to a file descriptor in Python?
1,223,289
18
2009-08-03T16:30:43Z
1,223,303
37
2009-08-03T16:33:16Z
[ "python" ]
The `os.write` function can be used to writes bytes into a *file descriptor* (not file object). If I execute *`os.write(fd, '\n')`*, only the LF character will be written into the file, even on Windows. I would like to have CRLF in the file on Windows and only LF in Linux. What is the best way to achieve this? I'm u...
Use this ``` import os os.write(fd, os.linesep) ```
How to write native newline character to a file descriptor in Python?
1,223,289
18
2009-08-03T16:30:43Z
1,223,313
8
2009-08-03T16:36:00Z
[ "python" ]
The `os.write` function can be used to writes bytes into a *file descriptor* (not file object). If I execute *`os.write(fd, '\n')`*, only the LF character will be written into the file, even on Windows. I would like to have CRLF in the file on Windows and only LF in Linux. What is the best way to achieve this? I'm u...
How about `os.write(<file descriptor>, os.linesep)`? (`import os` is unnecessary because you seem to have already imported it, otherwise you'd be getting errors using `os.write` to begin with.)
Lightweight markup language for Python
1,223,741
4
2009-08-03T18:02:54Z
1,223,981
8
2009-08-03T18:49:43Z
[ "python", "html", "markup" ]
Programming a Python web application, I want to create a text area where the users can enter text in a lightweight markup language. The text will be imported to a html template and viewed on the page. Today I use this command to create the textarea, which allows users to enter any (html) text: ``` my_text = cgidata.ge...
Use the python [markdown](http://www.freewisdom.org/projects/python-markdown/Using%5Fas%5Fa%5FModule) implementation ``` import markdown mode = "remove" # or "replace" or "escape" md = markdown.Markdown(safe_mode=mode) html = md.convert(text) ``` It is very flexible, you can use various extensions, create your own et...
How to stop WSGI from hanging apache
1,223,927
8
2009-08-03T18:38:40Z
1,224,993
12
2009-08-03T22:49:06Z
[ "python", "django", "apache", "mod-wsgi" ]
I have django running through WSGI like this : ``` <VirtualHost *:80> WSGIScriptAlias / /home/ptarjan/django/django.wsgi WSGIDaemonProcess ptarjan processes=2 threads=15 display-name=%{GROUP} WSGIProcessGroup ptarjan Alias /media /home/ptarjan/django/mysite/media/ </VirtualHost> ``` But if in python I...
It is not 'deadlock-timeout' you want as specified by another, that is for a very special purpose which will not help in this case. As far as trying to use mod\_wsgi features, you instead want the 'inactivity-timeout' option for WSGIDaemonProcess directive. Even then, this is not a complete solution. This is because ...
How can I merge fields in a CSV string using Python?
1,223,967
2
2009-08-03T18:47:30Z
1,223,982
10
2009-08-03T18:49:56Z
[ "python", "database", "string", "csv" ]
I am trying to merge three fields in each line of a CSV file using Python. This would be simple, except some of the fields are surrounded by double quotes and include commas. Here is an example: ``` ,,Joe,Smith,New Haven,CT,"Moved from Portland, CT",,goo, ``` Is there a simple algorithm that could merge fields 7-9 fo...
Something like this? ``` import csv source= csv.reader( open("some file","rb") ) dest= csv.writer( open("another file","wb") ) for row in source: result= row[:6] + [ row[6]+row[7]+row[8] ] + row[9:] dest.writerow( result ) ``` --- **Example** ``` >>> data=''',,Joe,Smith,New Haven,CT,"Moved from Portland, CT...
Check for a module in Python without using exceptions
1,224,585
3
2009-08-03T20:55:47Z
1,224,911
7
2009-08-03T22:20:54Z
[ "python", "module", "python-module" ]
I can check for a module in Python doing something like: ``` try: import some_module except ImportError: print "No some_module!" ``` But I don't want to use try/except. Is there a way to accomplish this? (it should work on Python 2.5.x.) **Note:** The reason for no using try/except is arbitrary, it is just becau...
It takes trickery to perform the request (and one `raise` statement is in fact inevitable because it's the one and only way specified in the PEP 302 for an import hook to say "I don't deal with this path item"!), but the following would avoid any `try`/`except`: ``` import sys sentinel = object() class FakeLoader(ob...
Trying to import module with the same name as a built-in module causes an import error
1,224,741
48
2009-08-03T21:34:46Z
1,224,760
66
2009-08-03T21:38:47Z
[ "python", "python-import" ]
I have a module that conflicts with a built-in module. For example, a `myapp.email` module defined in `myapp/email.py`. I can reference `myapp.email` anywhere in my code without issue. However, I need to reference the built-in email module from my email module. ``` # myapp/email.py from email import message_from_stri...
You will want to read about [Absolute and Relative Imports](http://docs.python.org/whatsnew/2.5.html#pep-328-absolute-and-relative-imports) which addresses this very problem. Use: ``` from __future__ import absolute_import ``` Using that, any unadorned package name will always refer to the top level package. You will...
Create properties using lambda getter and setter
1,224,962
3
2009-08-03T22:39:33Z
1,224,977
14
2009-08-03T22:44:28Z
[ "python", "lambda", "properties" ]
I have something like this: ``` class X(): def __init__(self): self.__name = None def _process_value(self, value): # do something pass def get_name(self): return self.__name def set_name(self, value): self.__name = self._process_value(value) name = proper...
Your problem is that lambda's body must be an expression and assignment is a statement (a strong, deep distinction in Python). If you insist on perpetrating `lambda`s you'll meet many such cases and learn the workarounds (there's usually one, though not always), such as, in this case: ``` name = property(lambda self: ...
Python: How to import part of a namespace
1,225,481
3
2009-08-04T02:25:08Z
1,225,522
9
2009-08-04T02:46:04Z
[ "python", "import", "namespaces" ]
I have a structure such this works : ``` import a.b.c a.b.c.foo() ``` and this also works : ``` from a.b import c c.foo() ``` but this doesn't work : ``` from a import b.c b.c.foo() ``` nor does : ``` from a import b b.c.foo() ``` How can I do the import so that `b.c.foo()` works?
Just rename it: ``` from a.b import c as BAR BAR.foo() ```
Checking email with Python
1,225,586
38
2009-08-04T03:15:46Z
1,225,592
14
2009-08-04T03:18:24Z
[ "python", "email" ]
I am interested to trigger a certain action upon receiving an email from specific address with specific subject. In order to be able to do so I need to implement monitoring of my mailbox, checking every incoming mail (in particular, i use gmail). what is the easiest way to do that? Thank you, Sasha
Gmail provides an atom [feed](https://mail.google.com/mail/feed/atom) for new email messages. You should be able to monitor this by authenticating with py cURL (or some other net library) and pulling down the feed. Making a GET request for each new message should mark it as read, so you won't have to keep track of whic...
Checking email with Python
1,225,586
38
2009-08-04T03:15:46Z
1,225,707
7
2009-08-04T04:17:40Z
[ "python", "email" ]
I am interested to trigger a certain action upon receiving an email from specific address with specific subject. In order to be able to do so I need to implement monitoring of my mailbox, checking every incoming mail (in particular, i use gmail). what is the easiest way to do that? Thank you, Sasha
While not Python-specific, I've always loved [procmail](http://www.procmail.org/) wherever I could install it...! Just use as some of your action lines for conditions of your choice `| pathtoyourscript` (vertical bar AKA pipe followed by the script you want to execute in those cases) and your mail gets piped, under th...
Checking email with Python
1,225,586
38
2009-08-04T03:15:46Z
1,231,136
52
2009-08-05T04:04:04Z
[ "python", "email" ]
I am interested to trigger a certain action upon receiving an email from specific address with specific subject. In order to be able to do so I need to implement monitoring of my mailbox, checking every incoming mail (in particular, i use gmail). what is the easiest way to do that? Thank you, Sasha
Gmail provides the ability to connect over POP, which you can turn on in the gmail settings panel. Python can make connections over POP pretty easily: ``` import poplib from email import parser pop_conn = poplib.POP3_SSL('pop.gmail.com') pop_conn.user('username') pop_conn.pass_('password') #Get messages from server: ...
Inserting the same value multiple times when formatting a string
1,225,637
67
2009-08-04T03:42:20Z
1,225,648
30
2009-08-04T03:46:06Z
[ "python", "string", "format" ]
I have a string of this form ``` s='arbit' string='%s hello world %s hello world %s' %(s,s,s) ``` All the %s in string have the same value (i.e. s). Is there a better way of writing this? (Rather than listing out s three times)
``` incoming = 'arbit' result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming} ``` You may like to have a read of this to get an understanding: [String Formatting Operations](http://docs.python.org/library/stdtypes.html#string-formatting).
Inserting the same value multiple times when formatting a string
1,225,637
67
2009-08-04T03:42:20Z
1,225,656
127
2009-08-04T03:49:01Z
[ "python", "string", "format" ]
I have a string of this form ``` s='arbit' string='%s hello world %s hello world %s' %(s,s,s) ``` All the %s in string have the same value (i.e. s). Is there a better way of writing this? (Rather than listing out s three times)
You can use [advanced string formatting](http://www.python.org/dev/peps/pep-3101/), available in Python 2.6 and Python 3.x: ``` incoming = 'arbit' result = '{0} hello world {0} hello world {0}'.format(incoming) ```
Inserting the same value multiple times when formatting a string
1,225,637
67
2009-08-04T03:42:20Z
1,225,681
13
2009-08-04T03:59:59Z
[ "python", "string", "format" ]
I have a string of this form ``` s='arbit' string='%s hello world %s hello world %s' %(s,s,s) ``` All the %s in string have the same value (i.e. s). Is there a better way of writing this? (Rather than listing out s three times)
You can use the dictionary type of formatting: ``` s='arbit' string='%(key)s hello world %(key)s hello world %(key)s' % {'key': s,} ```
Inserting the same value multiple times when formatting a string
1,225,637
67
2009-08-04T03:42:20Z
1,225,724
10
2009-08-04T04:26:12Z
[ "python", "string", "format" ]
I have a string of this form ``` s='arbit' string='%s hello world %s hello world %s' %(s,s,s) ``` All the %s in string have the same value (i.e. s). Is there a better way of writing this? (Rather than listing out s three times)
Depends on what you mean by better. This works if your goal is removal of redundancy. ``` s='foo' string='%s bar baz %s bar baz %s bar baz' % (3*(s,)) ```
multiprocess or threading in python?
1,226,584
31
2009-08-04T09:47:19Z
1,226,759
7
2009-08-04T10:31:42Z
[ "python", "multithreading", "multiprocess" ]
I have a python application that grabs a collection of data and for each piece of data in that collection it performs a task. The task takes some time to complete as there is a delay involved. Because of this delay, I don't want each piece of data to perform the task subsequently, I want them to all happen in parallel....
For small collections of data, simply create subprocesses with [subprocess.Popen](http://docs.python.org/library/subprocess.html#subprocess.Popen). Each subprocess can simply get it's piece of data from stdin or from command-line arguments, do it's processing, and simply write the result to an output file. When the s...
multiprocess or threading in python?
1,226,584
31
2009-08-04T09:47:19Z
1,226,873
7
2009-08-04T11:06:41Z
[ "python", "multithreading", "multiprocess" ]
I have a python application that grabs a collection of data and for each piece of data in that collection it performs a task. The task takes some time to complete as there is a delay involved. Because of this delay, I don't want each piece of data to perform the task subsequently, I want them to all happen in parallel....
You might consider looking into [Stackless Python](http://www.stackless.com/). If you have control over the function that takes a long time, you can just throw some `stackless.schedule()`s in there (saying yield to the next coroutine), or else you can [set Stackless to preemptive multitasking](http://www.stackless.com/...
multiprocess or threading in python?
1,226,584
31
2009-08-04T09:47:19Z
1,227,204
29
2009-08-04T12:26:14Z
[ "python", "multithreading", "multiprocess" ]
I have a python application that grabs a collection of data and for each piece of data in that collection it performs a task. The task takes some time to complete as there is a delay involved. Because of this delay, I don't want each piece of data to perform the task subsequently, I want them to all happen in parallel....
If you are truly compute bound, using the [multiprocessing module](http://docs.python.org/library/multiprocessing.html#module-multiprocessing) is probably the lightest weight solution (in terms of both memory consumption and implementation difficulty.) If you are I/O bound, using the [threading module](http://docs.pyt...
multiprocess or threading in python?
1,226,584
31
2009-08-04T09:47:19Z
2,137,311
9
2010-01-26T03:13:17Z
[ "python", "multithreading", "multiprocess" ]
I have a python application that grabs a collection of data and for each piece of data in that collection it performs a task. The task takes some time to complete as there is a delay involved. Because of this delay, I don't want each piece of data to perform the task subsequently, I want them to all happen in parallel....
Tasks runs like sequentially but you have the illusion that are run in parallel. Tasks are good when you use for file or connection I/O and because are lightweights. Multiprocess with Pool may be the right solution for you because processes runs in parallel so are very good with intensive computing because each proces...
Substitutions inside links in reST / Sphinx
1,227,037
16
2009-08-04T11:49:27Z
5,808,741
18
2011-04-27T18:26:10Z
[ "python", "documentation", "substitution", "restructuredtext", "python-sphinx" ]
I am using Sphinx to document a webservice that will be deployed in different servers. The documentation is full of URL examples for the user to click and they should just work. My problem is that the host, port and deployment root will vary and the documentation will have to be re-generated for every deployment. I tr...
New in Sphinx v1.0: sphinx.ext.extlinks – Markup to shorten external links <http://sphinx.pocoo.org/ext/extlinks.html> The extension adds one new config value: **extlinks** This config value must be a dictionary of external sites, mapping unique short alias names to a base URL and a prefix. For example, to creat...
Compare object instances for equality by their attributes in Python
1,227,121
106
2009-08-04T12:09:38Z
1,227,152
29
2009-08-04T12:15:43Z
[ "python", "object" ]
What is the best way to compare two instances of some object for equality in Python? I'd like to be able to do something like Example: ``` doc1 = ErrorDocument(path='/folder',title='Page') doc2 = ErrorDocument(path='/folder',title='Page') if doc1 == doc2: # this should be True #do something ``` **EDIT:** To fu...
You override the [rich comparison operators](https://docs.python.org/2.7/reference/datamodel.html#object.__lt__) in your object. ``` class MyClass: def __lt__(self, other): # return comparison def __le__(self, other) # return comparison def __eq__(self, other) # return comparison def __ne__(self,...
Compare object instances for equality by their attributes in Python
1,227,121
106
2009-08-04T12:09:38Z
1,227,325
144
2009-08-04T12:47:34Z
[ "python", "object" ]
What is the best way to compare two instances of some object for equality in Python? I'd like to be able to do something like Example: ``` doc1 = ErrorDocument(path='/folder',title='Page') doc2 = ErrorDocument(path='/folder',title='Page') if doc1 == doc2: # this should be True #do something ``` **EDIT:** To fu...
As usual with Python, it's [kiss](http://en.wikipedia.org/wiki/KISS_principle) : ``` class Test(object): def __init__(self, attr1, attr2): self.attr1 = attr1 self.attr2 = attr2 def __str__(self): return str(self.__dict__) def __eq__(self, other): return self.__dict__ == ...
python ctype recursive structures
1,228,158
7
2009-08-04T15:25:03Z
1,228,447
14
2009-08-04T16:12:55Z
[ "python", "dll", "recursion", "structure", "ctypes" ]
I've developped a DLL for a driver in C. I wrote a test program in C++ and the DLL works fine. Now I'd like to interract with this DLL using Python. I've successfully hidden most of the user defined C structures but there is one point where I have to use C structures. I'm rather new to python so I may get things wrong...
You almost certainly want to declare next\_command as a pointer. Having a structure that contains itself isn't possible (in any language). I think this is what you want: ``` class EthercatDatagram(Structure): pass EthercatDatagram._fields_ = [ ("header", EthercatDatagramHeader), ("packet_data_length", c_i...
Change one character in a string in Python?
1,228,299
172
2009-08-04T15:48:39Z
1,228,327
16
2009-08-04T15:52:27Z
[ "python" ]
What is the easiest way in Python to replace a character in a string like: ``` text = "abcdefg"; text[1] = "Z"; ^ ```
Python strings are immutable, you change them by making a copy. The easiest way to do what you want is probably. ``` text = "Z" + text[1:] ``` The text[1:] return the string in text from position 1 to the end, positions count from 0 so '1' is the second character. edit: You can use the same string slicing techniqu...
Change one character in a string in Python?
1,228,299
172
2009-08-04T15:48:39Z
1,228,332
71
2009-08-04T15:53:00Z
[ "python" ]
What is the easiest way in Python to replace a character in a string like: ``` text = "abcdefg"; text[1] = "Z"; ^ ```
``` new = text[:1] + 'Z' + text[2:] ```
Change one character in a string in Python?
1,228,299
172
2009-08-04T15:48:39Z
1,228,597
246
2009-08-04T16:41:07Z
[ "python" ]
What is the easiest way in Python to replace a character in a string like: ``` text = "abcdefg"; text[1] = "Z"; ^ ```
Don't modify strings. Work with them as lists; turn them into strings only when needed. ``` >>> s = list("Hello zorld") >>> s ['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd'] >>> s[6] = 'W' >>> s ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'] >>> "".join(s) 'Hello World' ``` Python strings are immuta...
Change one character in a string in Python?
1,228,299
172
2009-08-04T15:48:39Z
21,459,305
7
2014-01-30T14:34:49Z
[ "python" ]
What is the easiest way in Python to replace a character in a string like: ``` text = "abcdefg"; text[1] = "Z"; ^ ```
Starting with python 2.6 and python 3 you can use bytearrays which are mutable (can be changed element-wise unlike strings): ``` s = "abcdefg" b_s = bytearray(s) b_s[1] = "Z" s = str(b_s) print s aZcdefg ``` edit: Changed str to s edit2: As Two-Bit Alchemist mentioned in the comments, this code does not work with un...
Change one character in a string in Python?
1,228,299
172
2009-08-04T15:48:39Z
22,149,018
52
2014-03-03T14:15:24Z
[ "python" ]
What is the easiest way in Python to replace a character in a string like: ``` text = "abcdefg"; text[1] = "Z"; ^ ```
## Fastest method? There are two ways. For the speed seekers I recommend 'Method 2' **Method 1** Given by this [answer](http://stackoverflow.com/a/1228597/2571620) ``` text = 'abcdefg' new = list(text) new[6] = 'W' ''.join(new) ``` Which is pretty slow compared to 'Method 2' ``` timeit.timeit("text = 'abcdefg'; s...
Retrieving the return value of a Python script
1,228,550
2
2009-08-04T16:31:22Z
1,228,569
7
2009-08-04T16:35:14Z
[ "c#", "python" ]
I have an external C# program which executes a Python script using the `Process` class. My script returns a numerical code and I want to retrieve it from my C# program. Is this possible? The problem is, I'm getting the return code of `python.exe` instead of the code returned from my script. (For example, `3`.)
The interpreter does not return the value at the top of Python's stack, unless you do this: ``` if __name__ == "__main__": sys.exit(main()) ``` or if you make a call to `sys.exit` elsewhere. [Here's a lot more documentation on this issue.](http://www.artima.com/weblogs/viewpost.jsp?thread=4829)
Problem with Twisted python - sending binary data
1,228,722
5
2009-08-04T17:02:17Z
1,228,952
8
2009-08-04T17:46:56Z
[ "python", "file", "twisted", "send" ]
What I'm trying to do is fairly simple: send a file from client to server. First, the client sends information about the file - the size of it that is. Then it sends the actual file. This is what I've done so far: Server.py ``` from twisted.internet import reactor, protocol from twisted.protocols.basic import LineRe...
You've set your server to raw mode with setRawMode(), so the callback rawDataReceived is being called with the incoming data (not lineReceived). If you print the data you receive in rawDataReceived, you see everything including the file content, but as you call pickle to deserialize the data, it's being ignored. Eithe...
With Python, can I keep a persistent dictionary and modify it?
1,229,068
5
2009-08-04T18:10:52Z
1,229,099
15
2009-08-04T18:17:27Z
[ "python", "dictionary", "persistence", "object-persistence" ]
So, I want to store a dictionary in a persistent file. Is there a way to use regular dictionary methods to add, print, or delete entries from the dictionary in that file? It seems that I would be able to use cPickle to store the dictionary and load it, but I'm not sure where to take it from there.
If your keys (not necessarily the values) are strings, the [shelve](http://docs.python.org/library/shelve.html) standard library module does what you want pretty seamlessly.
Parsing empty options in Python
1,229,146
4
2009-08-04T18:32:47Z
1,229,667
8
2009-08-04T20:11:30Z
[ "python", "optparse", "optionparser" ]
I have an application that allows you to send event data to a custom script. You simply lay out the command line arguments and assign what event data goes with what argument. The problem is that there is no real flexibility here. Every option you map out is going to be used, but not every option will necessarily have d...
Sorry, misunderstood the question with my first answer. You can accomplish the ability to have optional arguments to command line flags use the *callback* action type when you define an option. Use the following function as a call back (you will likely wish to tailor to your needs) and configure it for each of the flag...
Convert list of floats into buffer in Python?
1,229,202
5
2009-08-04T18:43:04Z
1,229,314
7
2009-08-04T19:01:30Z
[ "python", "list", "floating-point", "buffer" ]
I am playing around with PortAudio and Python. ``` data = getData() stream.write( data ) ``` I want my stream to play sound data, that is represented in Float32 values. Therefore I use the following function: ``` def getData(): data = [] for i in range( 0, 1024 ): data.append( 0.25 * math.sin( math.r...
``` import struct def getData(): data = [] for i in range( 0, 1024 ): data.append( 0.25 * math.sin( math.radians( i ) ) ) return struct.pack('f'*len(data), *data) ```
Unicode utf-8/utf-16 encoding in Python
1,229,414
4
2009-08-04T19:22:40Z
1,229,481
7
2009-08-04T19:35:04Z
[ "python", "unicode", "encoding", "decoding" ]
In python: ``` u'\u3053\n' ``` Is it utf-16? I'm not really aware of all the unicode/encoding stuff, but this type of thing is coming up in my dataset, like if I have `a=u'\u3053\n'`. `print` gives an exception and decoding gives an exception. ``` a.encode("utf-16") > '\xff\xfeS0\n\x00' a.encode("utf-8") > '\xe3\x...
It's a unicode character that doesn't seem to be displayable in your terminals encoding. `print` tries to encode the unicode object in the encoding of your terminal and if this can't be done you get an exception. On a terminal that can display utf-8 you get: ``` >>> print u'\u3053' こ ``` Your terminal doesn't seem...
Decode complex JSON in Python
1,230,347
5
2009-08-04T23:05:07Z
1,230,459
9
2009-08-04T23:38:45Z
[ "php", "python", "json", "simplejson" ]
Hey, I have a JSON object created in PHP, that JSON object contains another escaped JSON string in one of it's cells: ``` php > $insidejson = array('foo' => 'bar','foo1' => 'bar1'); php > $arr = array('a' => array('a1'=>json_encode($insidejson))); php > echo json_encode($arr); {"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"b...
Try prefixing your string with 'r' to make it a raw string: ``` # Python 2.6.2 >>> import json >>> s = r'{"a":{"a1":"{\"foo\":\"bar\",\"foo1\":\"bar1\"}"}}' >>> json.loads(s) {u'a': {u'a1': u'{"foo":"bar","foo1":"bar1"}'}} ``` What Alex says below is true: you can just double the slashes. (His answer was not posted w...