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
How to install MySQLdb (Python data access library to MySQL) on Mac OS X?
1,448,429
81
2009-09-19T12:04:41Z
19,769,044
8
2013-11-04T13:46:27Z
[ "python", "mysql", "osx" ]
I'm a Python newbie, but I've just spent a day working out how to get MySQLdb working properly, and the universe according to google includes numerous references to what a PITA it is, and an inordinate number of guides that seem to be outdated. Given that this site is intended to address these sorts of problems, and I ...
Install pip: ``` sudo easy_install pip ``` Install brew: ``` ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)" ``` Install mysql: ``` brew install mysql ``` Install MySQLdb ``` sudo pip install MySQL-python ``` If you have compilation problems, try editing the ~/.profile file like in o...
variable length of %s with the % operator in python
1,448,820
18
2009-09-19T15:56:38Z
1,448,834
44
2009-09-19T16:03:17Z
[ "python" ]
I'm trying to do this: ``` max_title_width = max([len(text) for text in columns]) for column in columns: print "%10s, blah" % column ``` But I want to replace the `10` with the value of `max_title_width`. How do I do this in the most pythonic way possible?
This is a carryover from the C formatting markup: ``` print "%*s, blah" % (max_title_width,column) ``` If you want left-justified text (for entries shorter than `max_title_width`), put a '-' before the '\*'. ``` >>> text = "abcdef" >>> print "<%*s>" % (len(text)+2,text) < abcdef> >>> print "<%-*s>" % (len(text)+2,t...
variable length of %s with the % operator in python
1,448,820
18
2009-09-19T15:56:38Z
1,448,842
22
2009-09-19T16:04:59Z
[ "python" ]
I'm trying to do this: ``` max_title_width = max([len(text) for text in columns]) for column in columns: print "%10s, blah" % column ``` But I want to replace the `10` with the value of `max_title_width`. How do I do this in the most pythonic way possible?
You have the new strings formatting methods from Python 3 and Python 2.6. > Starting in Python 2.6, the built-in str and unicode classes provide the ability to do complex variable substitutions and value formatting via the str.format() method described in PEP 3101. The Formatter class in the string module allows you t...
How to install MySQLdb package? (ImportError: No module named setuptools)
1,449,130
39
2009-09-19T18:07:44Z
1,449,170
15
2009-09-19T18:28:15Z
[ "python", "mysql", "installation" ]
I am trying to install MySQLdb package. I found the source code [here](https://sourceforge.net/projects/mysql-python/files/). I did the following: ``` gunzip MySQL-python-1.2.3c1.tar.gz tar xvf MySQL-python-1.2.3c1.tar cd MySQL-python-1.2.3c1 python setup.py build ``` As the result I got the following: ``` Tracebac...
If MySQLdb's now distributed in a way that requires `setuptools`, your choices are either to download the latter (e.g. from [here](http://pypi.python.org/pypi/setuptools)) or refactor MySQLdb's setup.py to bypass `setuptools` (maybe just importing `setup` and `Extension` from plain `distutils` instead might work, but y...
How to install MySQLdb package? (ImportError: No module named setuptools)
1,449,130
39
2009-09-19T18:07:44Z
4,319,894
11
2010-11-30T23:47:30Z
[ "python", "mysql", "installation" ]
I am trying to install MySQLdb package. I found the source code [here](https://sourceforge.net/projects/mysql-python/files/). I did the following: ``` gunzip MySQL-python-1.2.3c1.tar.gz tar xvf MySQL-python-1.2.3c1.tar cd MySQL-python-1.2.3c1 python setup.py build ``` As the result I got the following: ``` Tracebac...
I resolved this issue on centos5.4 by running the following command to install setuptools yum install python-setuptools I hope that helps.
How to install MySQLdb package? (ImportError: No module named setuptools)
1,449,130
39
2009-09-19T18:07:44Z
9,675,988
27
2012-03-12T22:57:07Z
[ "python", "mysql", "installation" ]
I am trying to install MySQLdb package. I found the source code [here](https://sourceforge.net/projects/mysql-python/files/). I did the following: ``` gunzip MySQL-python-1.2.3c1.tar.gz tar xvf MySQL-python-1.2.3c1.tar cd MySQL-python-1.2.3c1 python setup.py build ``` As the result I got the following: ``` Tracebac...
After trying many suggestions, simply using `sudo apt-get install python-mysqldb` worked for me. More info: [Getting "Error loading MySQLdb module: No module named MySQLdb" - have tried previously posted solutions](http://stackoverflow.com/questions/2952187/getting-error-loading-mysqldb-module-no-module-named-mysqldb-...
How to install setuptools?
1,449,396
5
2009-09-19T20:03:14Z
1,452,826
8
2009-09-21T03:54:43Z
[ "python", "setuptools" ]
I'm trying to install setuptools. When I run "sh setuptools-0.6c9-py2.4.egg" I get the following message: > Permission denied: > '/usr/lib/python2.4/site-packages/test-easy-install-26338.write-test' It is expectable, since I do not have root permissions on the system. Some how I came to the idea of creating a "Virtua...
Just adding extra detail to what already have been said. 1. Download `tar.gz` of the latest version of [virtualenv](http://pypi.python.org/pypi/virtualenv). 2. Unpack it. 3. You don't even need to install it, just run `virtualenv.py`, for example: `virtualenv-1.3.3/virtualenv.py mypyenv` `mypyenv` virtual ...
How do I install Python packages on Windows?
1,449,494
89
2009-09-19T20:52:58Z
1,449,498
20
2009-09-19T20:54:53Z
[ "python", "pip" ]
I'm having a hard time setting up python packages. EasyInstall from [SetupTools](http://pypi.python.org/pypi/setuptools) is supposed to help that, but they don't have an executable for Python 2.6. For instance to install Mechanize, I'm just supposed to put the Mechanize folder in C:\Python24\Lib\site-packages accordin...
You don't need the executable for setuptools. You can download the source code, unpack it, traverse to the downloaded directory and run `python setup.py install` in the command prompt
How do I install Python packages on Windows?
1,449,494
89
2009-09-19T20:52:58Z
1,449,704
51
2009-09-19T22:40:01Z
[ "python", "pip" ]
I'm having a hard time setting up python packages. EasyInstall from [SetupTools](http://pypi.python.org/pypi/setuptools) is supposed to help that, but they don't have an executable for Python 2.6. For instance to install Mechanize, I'm just supposed to put the Mechanize folder in C:\Python24\Lib\site-packages accordin...
[This](http://web.archive.org/web/20120625104458/http://blog.sadphaeton.com/2009/01/20/python-development-windows-part-2-installing-easyinstallcould-be-easier.html) is a good tutorial on how to get `easy_install` on windows. The short answer: add `C:\Python26\Scripts` (or whatever python you have installed) to your PAT...
How do I install Python packages on Windows?
1,449,494
89
2009-09-19T20:52:58Z
13,445,682
11
2012-11-18T23:22:03Z
[ "python", "pip" ]
I'm having a hard time setting up python packages. EasyInstall from [SetupTools](http://pypi.python.org/pypi/setuptools) is supposed to help that, but they don't have an executable for Python 2.6. For instance to install Mechanize, I'm just supposed to put the Mechanize folder in C:\Python24\Lib\site-packages accordin...
As I [wrote elsewhere](http://stackoverflow.com/questions/11453866/python-modules-names-vs-the-name-of-the-actual-package) > Packaging in Python is dire. The root cause is that the language ships without a package manager. > > Fortunately, there is one package manager for Python, called [Pip](http://www.pip-installer....
How do I install Python packages on Windows?
1,449,494
89
2009-09-19T20:52:58Z
15,626,784
121
2013-03-25T23:34:12Z
[ "python", "pip" ]
I'm having a hard time setting up python packages. EasyInstall from [SetupTools](http://pypi.python.org/pypi/setuptools) is supposed to help that, but they don't have an executable for Python 2.6. For instance to install Mechanize, I'm just supposed to put the Mechanize folder in C:\Python24\Lib\site-packages accordin...
The [accepted answer](http://stackoverflow.com/a/1449704/1438393) is outdated. So first, [`pip`](https://pypi.python.org/pypi/pip) is preferred over `easy_install`, ([Why use pip over easy\_install?](http://stackoverflow.com/questions/3220404/why-use-pip-over-easy-install)). Then follow these steps to install `pip` on ...
How do I install Python packages on Windows?
1,449,494
89
2009-09-19T20:52:58Z
23,833,666
36
2014-05-23T15:56:04Z
[ "python", "pip" ]
I'm having a hard time setting up python packages. EasyInstall from [SetupTools](http://pypi.python.org/pypi/setuptools) is supposed to help that, but they don't have an executable for Python 2.6. For instance to install Mechanize, I'm just supposed to put the Mechanize folder in C:\Python24\Lib\site-packages accordin...
Newer versions of Python for Windows come with the *pip* package manager. [(source)](https://pip.pypa.io/en/latest/installing/) > pip is already installed if you're using Python 2 >=2.7.9 or Python 3 >=3.4 Use that to install packages: ``` cd C:/Python/Scripts/ pip.exe install <package-name> ```
Getting SVN revision number into a program automatically
1,449,935
16
2009-09-20T00:33:45Z
1,454,120
24
2009-09-21T11:43:56Z
[ "python", "svn", "revision" ]
I have a python project under SVN, and I'm wanting to display the version number when it is run. Is there any way of doing this (such as automatically running a short script on commit which could update a version file, or querying an SVN repository in Python?)
I'm not sure about the Python specifics, but if put the string $Revision$ into your file somewhere and you have enable-auto-props=true in your SVN config, it'll get rewritten to something like $Revision: 144$. You could then parse this in your script. There are [a number of property keywords you can use in this way](h...
Getting SVN revision number into a program automatically
1,449,935
16
2009-09-20T00:33:45Z
1,812,153
13
2009-11-28T10:06:25Z
[ "python", "svn", "revision" ]
I have a python project under SVN, and I'm wanting to display the version number when it is run. Is there any way of doing this (such as automatically running a short script on commit which could update a version file, or querying an SVN repository in Python?)
Similar to, but a little more pythonic than the PHP answer; put this in your module's `__init__.py`: ``` __version__ = filter(str.isdigit, "$Revision: 13 $") ``` and make sure you add the Revision property: ``` svn propset svn:keywords Revision __init__.py ```
Delete many elements of list (python)
1,450,111
10
2009-09-20T02:18:34Z
1,450,120
7
2009-09-20T02:25:05Z
[ "python", "list" ]
I have a list L. I can delete element i by doing: ``` del L[i] ``` But what if I have a set of non contiguous indexes to delete? ``` I=set([i1, i2, i3,...]) ``` Doing: ``` for i in I: del L[i] ``` Won't work. Any ideas?
``` for i in I: del L[i] ``` won't work, because (depending on the order) you may invalidate the iterator -- this will usually show up as some items which you intended to delete remaining in the list. It's always safe to delete items from the list in the reverse order of their indices. The easiest way to do this ...
Delete many elements of list (python)
1,450,111
10
2009-09-20T02:18:34Z
1,450,175
28
2009-09-20T03:04:55Z
[ "python", "list" ]
I have a list L. I can delete element i by doing: ``` del L[i] ``` But what if I have a set of non contiguous indexes to delete? ``` I=set([i1, i2, i3,...]) ``` Doing: ``` for i in I: del L[i] ``` Won't work. Any ideas?
> Eine Minuten bitte, Ich hap eine > kleine Problemo avec diese Religione. > -- Eddie Izzard (doing his impression > of Martin Luther) Deleting by reverse-iterating over a list to preserve the iterator *is* a common solution to this problem. But another solution is to change this into a different problem. Instead of d...
Proxy with urllib2
1,450,132
56
2009-09-20T02:30:24Z
1,450,142
12
2009-09-20T02:34:39Z
[ "python", "proxy", "urllib2" ]
I open urls with: `site = urllib2.urlopen('http://google.com')` And what I want to do is connect the same way with a proxy I got somewhere telling me: `site = urllib2.urlopen('http://google.com', proxies={'http':'127.0.0.1'})` but that didn't work either. I know urllib2 has something like a proxy handler, but I ca...
You have to install a ProxyHandler ``` urllib2.install_opener( urllib2.build_opener( urllib2.ProxyHandler({'http': '127.0.0.1'}) ) ) urllib2.urlopen('http://www.google.com') ```
Proxy with urllib2
1,450,132
56
2009-09-20T02:30:24Z
1,450,154
107
2009-09-20T02:49:35Z
[ "python", "proxy", "urllib2" ]
I open urls with: `site = urllib2.urlopen('http://google.com')` And what I want to do is connect the same way with a proxy I got somewhere telling me: `site = urllib2.urlopen('http://google.com', proxies={'http':'127.0.0.1'})` but that didn't work either. I know urllib2 has something like a proxy handler, but I ca...
``` proxy = urllib2.ProxyHandler({'http': '127.0.0.1'}) opener = urllib2.build_opener(proxy) urllib2.install_opener(opener) urllib2.urlopen('http://www.google.com') ```
Change the focus from one Text widget to another
1,450,180
8
2009-09-20T03:06:06Z
1,451,343
10
2009-09-20T15:57:10Z
[ "python", "text", "tabs", "tkinter" ]
I'm new to Python and I'm trying to create a simple GUI using Tkinter. So often in many user interfaces, hitting the tab button will change the focus from one Text widget to another. Whenever I'm in a Text widget, tab only indents the text cursor. Does anyone know if this is configurable? If not, can `PyQt` or any ot...
This is very easy to do with Tkinter. There are a couple of things that have to happen to make this work. First, you need to make sure that the standard behavior *doesn't* happen. That is, you don't want tab to both insert a tab and move focus to the next widget. By default events are processed by a specific widget pr...
Modifying locals in Python
1,450,275
10
2009-09-20T04:03:29Z
1,450,341
11
2009-09-20T05:09:33Z
[ "python", "locals" ]
locals is a built in function that returns a dictionary of local values. The documentation says: > Warning > > The contents of this dictionary should > not be modified; changes may not > affect the values of local variables > used by the interpreter. Unfortunately, exec has the same problem in Python 3.0. Is there an...
I just tested exec and it works in Python 2.6.2 ``` >>> def test(): ... exec "a = 5" ... print a ... >>> test() 5 ``` If you are using Python 3.x, it does not work anymore because locals are optimized as an array at runtime, instead of using a dictionary. When Python detects the "exec statement", it will for...
How do you read from stdin in Python?
1,450,393
854
2009-09-20T05:48:07Z
1,450,396
117
2009-09-20T05:51:00Z
[ "python", "stdin" ]
I'm trying to do some of the [code golf](http://en.wikipedia.org/wiki/Code_golf) challenges, but they all require the input to be taken from `stdin`. How do I get that in Python?
Here's from [Learning Python](http://oreilly.com/catalog/lpython/chapter/ch09.html#16308): ``` import sys data = sys.stdin.readlines() print "Counted", len(data), "lines." ``` On Unix, you could test it by doing something like: ``` % cat countlines.py | python countlines.py Counted 3 lines. ``` On Windows or DOS, ...
How do you read from stdin in Python?
1,450,393
854
2009-09-20T05:48:07Z
1,450,398
433
2009-09-20T05:53:17Z
[ "python", "stdin" ]
I'm trying to do some of the [code golf](http://en.wikipedia.org/wiki/Code_golf) challenges, but they all require the input to be taken from `stdin`. How do I get that in Python?
There's a few ways to do it. * [`sys.stdin`](http://docs.python.org/library/sys.html#sys.stdin) is a file-like object on which you can call functions `read` or `readlines` if you want to read everything or you want to read everything and split it by newline automatically. (You need to `import sys` for this to work.) *...
How do you read from stdin in Python?
1,450,393
854
2009-09-20T05:48:07Z
1,454,400
637
2009-09-21T13:01:14Z
[ "python", "stdin" ]
I'm trying to do some of the [code golf](http://en.wikipedia.org/wiki/Code_golf) challenges, but they all require the input to be taken from `stdin`. How do I get that in Python?
You could use the [`fileinput`](http://docs.python.org/library/fileinput.html) module: ``` import fileinput for line in fileinput.input(): pass ``` [`fileinput`](http://docs.python.org/library/fileinput.html) will loop through all the lines in the input specified as file names given in command-line arguments, or...
How do you read from stdin in Python?
1,450,393
854
2009-09-20T05:48:07Z
3,289,051
210
2010-07-20T10:30:06Z
[ "python", "stdin" ]
I'm trying to do some of the [code golf](http://en.wikipedia.org/wiki/Code_golf) challenges, but they all require the input to be taken from `stdin`. How do I get that in Python?
``` import sys for line in sys.stdin: print line ```
How do you read from stdin in Python?
1,450,393
854
2009-09-20T05:48:07Z
5,185,255
127
2011-03-03T19:05:48Z
[ "python", "stdin" ]
I'm trying to do some of the [code golf](http://en.wikipedia.org/wiki/Code_golf) challenges, but they all require the input to be taken from `stdin`. How do I get that in Python?
Python also has built-in functions `input()` and `raw_input()`. See the Python documentation under [Built-in Functions](http://docs.python.org/library/functions.html) or the Stack-Overflow documentation under [User Input](http://stackoverflow.com/documentation/python/809/python-3-vs-python-2/3552/user-input#t=201607212...
How do you read from stdin in Python?
1,450,393
854
2009-09-20T05:48:07Z
7,608,205
75
2011-09-30T09:08:09Z
[ "python", "stdin" ]
I'm trying to do some of the [code golf](http://en.wikipedia.org/wiki/Code_golf) challenges, but they all require the input to be taken from `stdin`. How do I get that in Python?
The answer proposed by others: ``` for line in sys.stdin: print line ``` is very simple and pythonic, but it must be noted that the script will wait until EOF before starting to iterate on the lines of input. This means that `tail -f error_log | myscript.py` will not process lines as expected. The correct script ...
How do you read from stdin in Python?
1,450,393
854
2009-09-20T05:48:07Z
11,887,913
26
2012-08-09T16:31:57Z
[ "python", "stdin" ]
I'm trying to do some of the [code golf](http://en.wikipedia.org/wiki/Code_golf) challenges, but they all require the input to be taken from `stdin`. How do I get that in Python?
This will echo standard input to standard output: ``` import sys line = sys.stdin.readline() while line: print line, line = sys.stdin.readline() ```
How do you read from stdin in Python?
1,450,393
854
2009-09-20T05:48:07Z
17,927,520
19
2013-07-29T15:04:35Z
[ "python", "stdin" ]
I'm trying to do some of the [code golf](http://en.wikipedia.org/wiki/Code_golf) challenges, but they all require the input to be taken from `stdin`. How do I get that in Python?
Building on all the anwers using `sys.stdin`, you can also do something like the following to read from an argument file if at least one argument exists, and fall back to stdin otherwise: ``` import sys f = open(sys.argv[1]) if len(sys.argv) > 1 else sys.stdin for line in f: # Do your stuff ``` and use it as ...
How do you read from stdin in Python?
1,450,393
854
2009-09-20T05:48:07Z
24,855,121
8
2014-07-20T21:33:46Z
[ "python", "stdin" ]
I'm trying to do some of the [code golf](http://en.wikipedia.org/wiki/Code_golf) challenges, but they all require the input to be taken from `stdin`. How do I get that in Python?
You can read from stdin and then store inputs into **"data"** as follows: ``` data = "" for line in sys.stdin: data += line ```
How to get the name of a running Python script?
1,450,478
4
2009-09-20T06:59:54Z
1,450,485
10
2009-09-20T07:04:33Z
[ "python" ]
How do I get the name of a running Python script? I tried `os.__file__` but that returns the name of the file where `os` resides.
``` >> import os >> import sys >> print sys.argv[0] ``` or if you just want the script and not the full path ``` >> >> print os.path.basename(sys.argv[0]) ```
How to get the name of a running Python script?
1,450,478
4
2009-09-20T06:59:54Z
1,450,693
17
2009-09-20T10:01:22Z
[ "python" ]
How do I get the name of a running Python script? I tried `os.__file__` but that returns the name of the file where `os` resides.
Use ``` thisFile = __file__ ``` It's magic!
Python: removing characters except digits from string
1,450,897
72
2009-09-20T12:14:17Z
1,450,900
104
2009-09-20T12:18:48Z
[ "python", "string" ]
How can i remove all characters except numbers from string?
Use `re.sub`, like so: ``` >>> import re >>> re.sub("\D", "", "aas30dsa20") '3020' ``` `\D` matches any non-digit character so, the code above, is essentially replacing every non-digit character for the empty string. Or you can use `filter`, like so (in Python 2k): ``` >>> filter(lambda x: x.isdigit(), "aas30dsa20"...
Python: removing characters except digits from string
1,450,897
72
2009-09-20T12:14:17Z
1,450,911
9
2009-09-20T12:23:17Z
[ "python", "string" ]
How can i remove all characters except numbers from string?
along the lines of bayer's answer: ``` ''.join(i for i in s if i.isdigit()) ```
Python: removing characters except digits from string
1,450,897
72
2009-09-20T12:14:17Z
1,450,912
11
2009-09-20T12:24:05Z
[ "python", "string" ]
How can i remove all characters except numbers from string?
You can use filter: ``` filter(lambda x: x.isdigit(), "dasdasd2313dsa") ``` On python3.0 you have to join this (kinda ugly :( ) ``` ''.join(filter(lambda x: x.isdigit(), "dasdasd2313dsa")) ```
Python: removing characters except digits from string
1,450,897
72
2009-09-20T12:14:17Z
1,450,913
44
2009-09-20T12:24:18Z
[ "python", "string" ]
How can i remove all characters except numbers from string?
``` s=''.join(i for i in s if i.isdigit()) ``` Another generator variant.
Python: removing characters except digits from string
1,450,897
72
2009-09-20T12:14:17Z
1,451,407
77
2009-09-20T16:37:19Z
[ "python", "string" ]
How can i remove all characters except numbers from string?
In Python 2.\*, by far the fastest approach is the `.translate` method: ``` >>> x='aaa12333bb445bb54b5b52' >>> import string >>> all=string.maketrans('','') >>> nodigs=all.translate(all, string.digits) >>> x.translate(all, nodigs) '1233344554552' >>> ``` `string.maketrans` makes a translation table (a string of lengt...
Python's json module, converts int dictionary keys to strings
1,450,957
56
2009-09-20T12:52:40Z
1,450,981
41
2009-09-20T13:08:01Z
[ "python", "json" ]
I have found that when the following is run, python's json module (included since 2.6) converts int dictionary keys to strings. ``` >>> import json >>> releases = {1: "foo-v0.1"} >>> json.dumps(releases) '{"1": "foo-v0.1"}' ``` Is there any easy way to preserve the key as an int, without needing to parse the string o...
No, there is no such thing as a Number key in JavaScript. All object properties are converted to String. ``` var a= {1: 'a'}; for (k in a) alert(typeof k); // 'string' ``` This can lead to some curious-seeming behaviours: ``` a[999999999999999999999]= 'a'; // this even works on Array alert(a[10000000000000000000...
Python's json module, converts int dictionary keys to strings
1,450,957
56
2009-09-20T12:52:40Z
1,451,857
43
2009-09-20T19:56:46Z
[ "python", "json" ]
I have found that when the following is run, python's json module (included since 2.6) converts int dictionary keys to strings. ``` >>> import json >>> releases = {1: "foo-v0.1"} >>> json.dumps(releases) '{"1": "foo-v0.1"}' ``` Is there any easy way to preserve the key as an int, without needing to parse the string o...
This is one of those subtle differences among various mapping collections that can bite you. In Python (and apparently in Lua) the keys to a mapping (dictionary or table, respectively) are object references. In Python they must be immutable types, or they must be objects which implement a `__hash__` method. (The Lua d...
Python's json module, converts int dictionary keys to strings
1,450,957
56
2009-09-20T12:52:40Z
3,742,888
14
2010-09-18T18:17:49Z
[ "python", "json" ]
I have found that when the following is run, python's json module (included since 2.6) converts int dictionary keys to strings. ``` >>> import json >>> releases = {1: "foo-v0.1"} >>> json.dumps(releases) '{"1": "foo-v0.1"}' ``` Is there any easy way to preserve the key as an int, without needing to parse the string o...
Alternatively you can also try converting dictionary to a list of [(k1,v1),(k2,v2)] format while encoding it using json, and converting it back to dictionary after decoding it back. ``` >>>> import json >>>> json.dumps(releases.items()) '[[1, "foo-v0.1"]]' >>>> releases = {1: "foo-v0.1"} >>>> releases == dict(json...
Security concerns with a Python PAM module?
1,451,224
12
2009-09-20T15:02:52Z
1,451,379
16
2009-09-20T16:20:40Z
[ "python", "security", "pam", "suid" ]
I'm interested in writing a PAM module that would make use of a popular authentication mechanism for Unix logins. Most of my past programming experience has been in Python, and the system I'm interacting with already has a Python API. I googled around and found [pam\_python](http://pam-python.sourceforge.net/), which a...
The security concerns that you mention aren't, per se, about "allowing the user to invoke Python code" which runs with high access levels, but allowing the user to exercise any form of *control* over the running of such code -- most obviously by injecting or altering the code itself, but, more subtly, also by controlli...
Python: How to find presence of every list item in string
1,451,390
3
2009-09-20T16:28:05Z
1,451,910
9
2009-09-20T20:14:12Z
[ "python", "list", "path" ]
What is the most pythonic way to find presence of every directory name `['spam', 'eggs']` in path e.g. `"/home/user/spam/eggs"` Usage example (doesn't work but explains my case): ``` dirs = ['spam', 'eggs'] path = "/home/user/spam/eggs" if path.find(dirs): print "All dirs are present in the path" ``` Thanks
### [`set.issubset`](http://docs.python.org/library/stdtypes.html#set.issubset): ``` >>> set(['spam', 'eggs']).issubset('/home/user/spam/eggs'.split('/')) True ```
Python MySQL - SELECTs work but not DELETEs?
1,451,782
7
2009-09-20T19:22:23Z
1,451,914
11
2009-09-20T20:14:52Z
[ "python", "mysql", "select", "sql-delete" ]
I'm new to Python and Python's MySQL adapter. I'm not sure if I'm missing something obvious here: ``` db = MySQLdb.connect(# db details omitted) cursor = self.db.cursor() # WORKS cursor.execute("SELECT site_id FROM users WHERE username=%s", (username)) record = cursor.fetchone() # DOES NOT SEEM TO WORK cursor.execut...
I'd guess that you are using a storage engine that supports transactions (e.g. InnoDB) but you don't call `db.commit()` after the DELETE. The effect of the DELETE is discarded if you don't commit. See <http://mysql-python.sourceforge.net/FAQ.html#my-data-disappeared-or-won-t-go-away>: > Starting with 1.2.0, MySQLdb d...
Evaluation of boolean expressions in Python
1,452,489
5
2009-09-21T01:15:21Z
1,452,492
7
2009-09-21T01:17:14Z
[ "python", "object", "boolean" ]
What truth value do objects evaluate to in Python? **Related Questions** * [Boolean Value of Objects in Python](http://stackoverflow.com/questions/1087135/boolean-value-of-objects-in-python): Discussion about overriding the way it is evaluated
**Update**: Removed all duplicate infomation with Meder's post For custom objects in Python < 3.0 `__nonzero__` to change how it is evaluated. In Python 3.0 this is `__bool__` ([Reference](http://stackoverflow.com/questions/1087135/boolean-value-of-objects-in-python/1087166#1087166) by e-satis) It is important to und...
Evaluation of boolean expressions in Python
1,452,489
5
2009-09-21T01:15:21Z
1,452,500
15
2009-09-21T01:21:22Z
[ "python", "object", "boolean" ]
What truth value do objects evaluate to in Python? **Related Questions** * [Boolean Value of Objects in Python](http://stackoverflow.com/questions/1087135/boolean-value-of-objects-in-python): Discussion about overriding the way it is evaluated
> Any object can be tested for truth > value, for use in an if or while > condition or as operand of the Boolean > operations below. The following values > are considered false: > > * None > * False > * zero of any numeric type, for example, `0`, `0L`, `0.0`, `0j`. > * any empty sequence, for example, `''`, `()`, `[]`....
How to rapidly build a Web Application?
1,452,652
3
2009-09-21T02:44:48Z
1,452,670
7
2009-09-21T02:48:41Z
[ "java", "php", "python", "ruby-on-rails" ]
To build a Web Application, what kind of open source web application frameworks / technologies are currently present that would be: * Faster to learn. * Ease of use. * Have widgets for rapid development(From a GUI perspective). * Database integration. I would want this web app to communicate to a Java client. I am no...
There is no single "right" answer to this question. As a Java programmer of some 10+ years when asked this question my usual answer is... PHP. There are several reasons for this: * Low resource usage (Apache, nginx); * Cheaper hosting; * Really low barrier to entry; * It's really Web-oriented rather than being general...
How to rapidly build a Web Application?
1,452,652
3
2009-09-21T02:44:48Z
1,452,739
8
2009-09-21T03:13:51Z
[ "java", "php", "python", "ruby-on-rails" ]
To build a Web Application, what kind of open source web application frameworks / technologies are currently present that would be: * Faster to learn. * Ease of use. * Have widgets for rapid development(From a GUI perspective). * Database integration. I would want this web app to communicate to a Java client. I am no...
[Django](http://www.djangoproject.com/) has a few notable 'rapid' items including [automatically generated administrative interface](http://images.google.com/images?hl=en&client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&hs=0Ku&q=django%20admin&um=1&ie=UTF-8&sa=N&tab=wi), bundled ORM (lowers dev time by not having to...
Creating Simultaneous Loops in Python
1,452,694
3
2009-09-21T02:59:57Z
1,452,709
10
2009-09-21T03:04:48Z
[ "python", "loops" ]
I want to create a loop who has this sense: ``` for i in xrange(0,10): for k in xrange(0,10): z=k+i print z where the output should be 0 2 4 6 8 10 12 14 16 18 ```
The [`itertools`](http://docs.python.org/library/itertools.html) module contains an [`izip`](http://docs.python.org/library/itertools.html#itertools.izip) function that combines iterators in the desired way: ``` from itertools import izip for (i, k) in izip(xrange(0,10), xrange(0,10)): print i+k ```
Creating Simultaneous Loops in Python
1,452,694
3
2009-09-21T02:59:57Z
1,452,711
11
2009-09-21T03:05:18Z
[ "python", "loops" ]
I want to create a loop who has this sense: ``` for i in xrange(0,10): for k in xrange(0,10): z=k+i print z where the output should be 0 2 4 6 8 10 12 14 16 18 ```
You can use [`zip`](http://docs.python.org/library/functions.html#zip) to turn multiple lists (or iterables) into pairwise\* tuples: ``` >>> for a,b in zip(xrange(10), xrange(10)): ... print a+b ... 0 2 4 6 8 10 12 14 16 18 ``` But `zip` will not scale as well as `izip` (that sth mentioned) on larger sets. `zip`...
Is there an C++ equivalent to Python's "import bigname as b"?
1,452,883
4
2009-09-21T04:18:50Z
1,452,891
12
2009-09-21T04:24:32Z
[ "c++", "python", "namespaces", "alias" ]
I've always liked Python's ``` import big_honkin_name as bhn ``` so you can then just use `bhn.thing` rather than the considerably more verbose `big_honkin_name.thing` in your source. I've seen two type of namespace use in C++ code, either: ``` using namespace big_honkin_name; // includes fn(). int a = fn (27); ```...
[StackOverflow to the rescue!](http://stackoverflow.com/questions/75538/hidden-features-of-c/78484#78484) Yes you can. In short: ``` namespace bhn = big_honkin_name; ```
Is there an C++ equivalent to Python's "import bigname as b"?
1,452,883
4
2009-09-21T04:18:50Z
1,452,905
11
2009-09-21T04:28:42Z
[ "c++", "python", "namespaces", "alias" ]
I've always liked Python's ``` import big_honkin_name as bhn ``` so you can then just use `bhn.thing` rather than the considerably more verbose `big_honkin_name.thing` in your source. I've seen two type of namespace use in C++ code, either: ``` using namespace big_honkin_name; // includes fn(). int a = fn (27); ```...
``` namespace bhn = big_honkin_name; ``` There's another way to use namespaces too: ``` using big_honkin_name::fn; int a = fn(27); ```
Why doesn't a python dict.update() return the object?
1,452,995
56
2009-09-21T05:20:43Z
1,453,011
24
2009-09-21T05:29:52Z
[ "python", "language-features", "language-design", "monads" ]
I 'm trying to do : ``` award_dict = { "url" : "http://facebook.com", "imageurl" : "http://farm4.static.flickr.com/3431/3939267074_feb9eb19b1_o.png", "count" : 1, } def award(name, count, points, desc_string, my_size, parent) : if my_size > count : a = { "name" : name, ...
Python's API, by convention, distinguishes between procedures and functions. Functions compute new values out of their parameters (including any target object); procedures modify objects and don't return anything (i.e. they return None). So procedures have side effects, functions don't. update is a procedure, hence it ...
Why doesn't a python dict.update() return the object?
1,452,995
56
2009-09-21T05:20:43Z
1,453,013
105
2009-09-21T05:31:28Z
[ "python", "language-features", "language-design", "monads" ]
I 'm trying to do : ``` award_dict = { "url" : "http://facebook.com", "imageurl" : "http://farm4.static.flickr.com/3431/3939267074_feb9eb19b1_o.png", "count" : 1, } def award(name, count, points, desc_string, my_size, parent) : if my_size > count : a = { "name" : name, ...
Python's mostly implementing a pragmatically tinged flavor of [command-query separation](http://en.wikipedia.org/wiki/Command-query%5Fseparation): mutators return `None` (with pragmatically induced exceptions such as `pop`;-) so they can't possibly be confused with accessors (and in the same vein, assignment is not an ...
Should I create mapper objects or use the declarative syntax in SQLAlchemy?
1,453,219
32
2009-09-21T07:19:43Z
1,453,881
19
2009-09-21T10:39:11Z
[ "python", "sqlalchemy" ]
There are two (three, but I'm not counting [Elixir](http://elixir.ematia.de/trac/wiki), as its not "official") ways to define a persisting object with [SQLAlchemy](http://www.sqlalchemy.org): ### [Explicit syntax for mapper objects](http://www.sqlalchemy.org/docs/05/mappers.html) ``` from sqlalchemy import Table, Col...
"What I'm not completely sure, is which approach is more maintainable for a business application?" Can't be answered in general. However, consider this. The Django ORM is strictly declarative -- and people like that. SQLAlchemy does several things, not all of which are relevant to all problems. 1. SQLAlchemy creat...
Should I create mapper objects or use the declarative syntax in SQLAlchemy?
1,453,219
32
2009-09-21T07:19:43Z
1,453,888
13
2009-09-21T10:40:24Z
[ "python", "sqlalchemy" ]
There are two (three, but I'm not counting [Elixir](http://elixir.ematia.de/trac/wiki), as its not "official") ways to define a persisting object with [SQLAlchemy](http://www.sqlalchemy.org): ### [Explicit syntax for mapper objects](http://www.sqlalchemy.org/docs/05/mappers.html) ``` from sqlalchemy import Table, Col...
In our team we settled on declarative syntax. Rationale: * `metadata` is trivial to get to, if needed: `User.metadata`. * Your `User` class, by virtue of subclassing `Base`, has a nice ctor that takes kwargs for all fields. Useful for testing and otherwise. E.g.: `user=User(name='doe', password='42')`. So no need to ...
How to markup form fields with <div class='field_type'> in Django
1,453,488
6
2009-09-21T08:53:04Z
1,504,903
16
2009-10-01T16:08:35Z
[ "python", "django", "django-forms", "django-templates", "django-models" ]
I wasn't able to find a way to identify the type of a field in a django template. My solution was to create a simple filter to access the field and widget class names. I've included the code below in case it's helpful for someone else. Is there a better approach? ``` ## agency/tagutils/templatetags/fieldtags.py #####...
``` class MyForm(forms.Form): myfield = forms.CharField(widget=forms.TextInput(attrs={'class' : 'myfieldclass'})) ``` or, with a ModelForm ``` class MyForm(forms.ModelForm): class Meta: model = MyModel widgets = { 'myfield': forms.TextInput(attrs={'class': 'myfieldclass'}), ...
How to filter query in sqlalchemy by year (datetime column)
1,453,591
12
2009-09-21T09:23:09Z
1,453,610
18
2009-09-21T09:27:11Z
[ "python", "sqlalchemy" ]
I have table in sqlalchemy 0.4 that with types.DateTime column: ``` Column("dfield", types.DateTime, index=True) ``` I want to select records, that has specific year in this column, using model. How to do this? I though it should be done like this: ``` selected_year = 2009 my_session = model.Session() my_query = my_...
sqlalchemy.extract('year', model.MyRecord.dfield) == selected\_year
python error "list indices must be integers" , they ARE integers
1,453,882
4
2009-09-21T10:39:25Z
1,453,925
12
2009-09-21T10:47:02Z
[ "python" ]
I am having a problem. I have an array of 31 elements called colors. I also have another array with integer numbers that vary between 0 and 31, this is called c. I want to produce a new array where the values in c are now the corresponding values in colors. I write: > > newarray=colors[c] but get the error message "...
array of integers != integer list indices must be integers - you've given a list of integers. You probably want a list comprehension: ``` newarray = [ colors[i] for i in c ] ``` But you really ought to learn the language properly before using it. It's not like python takes a long time to learn. EDIT: If you're st...
Python: Does a dict value pointer store its key?
1,454,437
2
2009-09-21T13:09:43Z
1,454,441
7
2009-09-21T13:10:53Z
[ "python", "dictionary" ]
I'm wondering if there is a built-in way to do this... Take this simple code for example: ``` D = {'one': objectA(), 'two': objectB(), 'three': objectC()} object_a = D['one'] ``` I believe `object_a` is just pointing at the `objectA()` created on the first line, and knows nothing about the dictionary `D`, but my ques...
I think no. Consider the case of adding a single object to a (large) number of different dictionaries. It would become quite expensive for Python to track that for you, it would cost a lot for a feature not used by most.
do properties work on django model fields?
1,454,727
25
2009-09-21T14:13:17Z
1,454,856
12
2009-09-21T14:39:02Z
[ "python", "django", "properties", "models" ]
I think the best way to ask this question is with some code... can I do this? (**edit**: ANSWER: no) ~~``` class MyModel(models.Model): foo = models.CharField(max_length = 20) bar = models.CharField(max_length = 20) def get_foo(self): if self.bar: ...
A model field is already property, so I would say you have to do it the second way to avoid a name clash. When you define foo = property(..) it actually overrides the foo = models.. line, so that field will no longer be accessible. You will need to use a different name for the property and the field. In fact, if you ...
do properties work on django model fields?
1,454,727
25
2009-09-21T14:13:17Z
12,358,707
10
2012-09-10T20:08:16Z
[ "python", "django", "properties", "models" ]
I think the best way to ask this question is with some code... can I do this? (**edit**: ANSWER: no) ~~``` class MyModel(models.Model): foo = models.CharField(max_length = 20) bar = models.CharField(max_length = 20) def get_foo(self): if self.bar: ...
As mentioned, a correct alternative to implementing your own django.db.models.Field class, one should use - **db\_column** argument and a custom (or hidden) class attribute. I am just rewriting the code in the edit by @Jiaaro following more strict conventions for OOP in python (e.g. if \_foo should be actually hidden):...
Allowing user to rollback from db audit trail with SQLAlchemy
1,454,874
4
2009-09-21T14:42:21Z
1,455,056
7
2009-09-21T15:18:37Z
[ "python", "sqlalchemy", "audit", "rollback" ]
I'm starting to use SQLAlchemy for a new project where I was planning to implement an audit trail similar to the one proposed on this quiestions: * <http://stackoverflow.com/questions/328898/implementing-audit-trail-for-objects-in-c> * <http://stackoverflow.com/questions/315240/audit-trails-and-implementing-sox-hipaa-...
Although I haven't used SQLAlchemy specifically, I can give you some general tips that can be easily implemented in any ORM: * Separate out the versioned item into two tables, say `Document` and `DocumentVersion`. `Document` stores information that will never change between versions, and `DocumentVersion` stores infor...
Flow control in threading.Thread
1,454,941
3
2009-09-21T14:56:40Z
1,455,015
7
2009-09-21T15:11:17Z
[ "python", "multithreading", "control", "flow" ]
I Have run into a few examples of managing threads with the threading module (using Python 2.6). What I am trying to understand is how is this example calling the "run" method and where. I do not see it anywhere. The ThreadUrl class gets instantiated in the main() function as "t" and this is where I would normally exp...
Per the [pydoc](http://docs.python.org/library/threading.html#threading.Thread.start): > `Thread.start()` > > Start the thread’s activity. > > It must be called at most once per thread object. It arranges for the > object’s run() method to be invoked in > a separate thread of control. > > This method will raise a ...
How to define properties in __init__
1,454,984
4
2009-09-21T15:04:02Z
1,455,009
9
2009-09-21T15:10:31Z
[ "python", "properties", "constructor" ]
I whish to define properties in a class from a member function. Below is some test code showing how I would like this to work. However I don't get the expected behaviour. ``` class Basket(object): def __init__(self): # add all the properties for p in self.PropNames(): setattr(self, p, property(lambda ...
You need to set the properties on the class (ie: `self.__class__`), not on the object (ie: `self`). For example: ``` class Basket(object): def __init__(self): # add all the properties setattr(self.__class__, 'Apple', property(lambda s : 'Apple') ) setattr(self.__class__, 'Pear', property(lambda s : 'Pea...
How to set ignorecase flag for part of regular expression in Python?
1,455,160
2
2009-09-21T15:35:55Z
1,455,303
7
2009-09-21T16:01:10Z
[ "python", "regex" ]
Is it possible to implement in Python something like this simple one: ``` #!/usr/bin/perl my $a = 'Use HELLO1 code'; if($a =~ /(?i:use)\s+([A-Z0-9]+)\s+(?i:code)/){ print "$1\n"; } ``` Letters of token in the middle of string are always capital. Letters of the rest of words can have any case (USE, use, Use, CODE,...
As far as I could find, the python regular expression engine does not support partial ignore-case. Here is a solution using a case-insensitive regular expression, which then tests if the token is uppercase afterward. ``` #! /usr/bin/env python import re token_re = re.compile(r'use\s+([a-z0-9]+)\s+code', re.IGNORECAS...
Python-based Gallery web applications?
1,455,224
6
2009-09-21T15:46:55Z
1,455,282
7
2009-09-21T15:58:34Z
[ "python", "web-applications", "gallery" ]
I'm trying to cut my last dependencies on PHP and MySQL. The last stumbling block is a image gallery I set up for a client a while ago. The whole website is built around [Django](http://www.djangoproject.com/) and [Zine](http://zine.pocoo.org/), except for the image gallery, which is based on [plogger](http://www.plogg...
There is [django-photo-gallery](http://code.google.com/p/django-photo-gallery), [django photo album](http://bitbucket.org/kmike/django-photo-albums/) and another [django-photo-gallery](http://www.ohloh.net/p/django-photo-gallery) (don't know if its the same one.) Anything else, and you'll have to make your own.
FFMPEG and Pythons subprocess
1,455,532
6
2009-09-21T16:49:40Z
1,455,726
8
2009-09-21T17:26:42Z
[ "python", "ffmpeg", "subprocess" ]
I'm trying to write a gui for `FFMPEG`. I'm using pythons subprocess to create a ffmpeg process for every conversion I want. This works fine, but I'd also like a way to get the progress of the conversion, whether it failed or not etc. I figured I could do this by accessing the process's stdout like so: Calling `subpro...
I've often noticed problems reading standard output (or even standard error!) with subprocess, due to buffering issues that are hard to defeat. My favorite solution, when I do need to read such stdout/stderr from the subprocess, is to switch to using, instead of `subprocess`, [`pexpect`](http://pexpect.sourceforge.net/...
Printing tuple with string formatting in Python
1,455,602
59
2009-09-21T17:03:45Z
1,455,623
112
2009-09-21T17:07:07Z
[ "python" ]
So, i have this problem. I got tuple (1,2,3) which i should print with string formatting. eg. ``` tup = (1,2,3) print "this is a tuple %something" % (tup) ``` and this should print tuple representation with brackets, like > This is a tuple (1,2,3) But I get `TypeError: not all arguments converted during string form...
``` >>> thetuple = (1, 2, 3) >>> print "this is a tuple: %s" % (thetuple,) this is a tuple: (1, 2, 3) ``` Making a singleton tuple with the tuple of interest as the only item, i.e. the `(thetuple,)` part, is the key bit here.
Printing tuple with string formatting in Python
1,455,602
59
2009-09-21T17:03:45Z
1,455,632
16
2009-09-21T17:08:40Z
[ "python" ]
So, i have this problem. I got tuple (1,2,3) which i should print with string formatting. eg. ``` tup = (1,2,3) print "this is a tuple %something" % (tup) ``` and this should print tuple representation with brackets, like > This is a tuple (1,2,3) But I get `TypeError: not all arguments converted during string form...
``` >>> tup = (1, 2, 3) >>> print "Here it is: %s" % (tup,) Here it is: (1, 2, 3) >>> ``` Note that `(tup,)` is a tuple containing a tuple. The outer tuple is the argument to the % operator. The inner tuple is its content, which is actually printed. `(tup)` is an expression in brackets, which when evaluated results i...
Printing tuple with string formatting in Python
1,455,602
59
2009-09-21T17:03:45Z
11,130,859
18
2012-06-21T02:41:20Z
[ "python" ]
So, i have this problem. I got tuple (1,2,3) which i should print with string formatting. eg. ``` tup = (1,2,3) print "this is a tuple %something" % (tup) ``` and this should print tuple representation with brackets, like > This is a tuple (1,2,3) But I get `TypeError: not all arguments converted during string form...
Note that the `%` syntax is obsolete. Use `str.format`, which is simpler and more readable: ``` t = 1,2,3 print 'This is a tuple {0}'.format(t) ```
Can we run google app engine on ubuntu/windows and serve web application
1,455,800
4
2009-09-21T17:41:39Z
1,455,832
8
2009-09-21T17:48:18Z
[ "python", "google-app-engine", "task" ]
I see google provide SDK and utilties to develop and run the web application in development (developer-pc) and port them to google app engine live (at google server). Can we use google app engine to run the local web application without using google infrastructure? Basically I want a decent job scheduler and persiste...
You can run App Engine apps on top of [appscale](http://code.google.com/p/appscale/) which in turn does run on Eucalyptus, Xen, and other clustering solutions you can deploy on Ubuntu (not sure about there being any Windows support) -- looks like it may require substantial system installation, configuration, and admini...
Dealing with db.Timeout on Google App Engine
1,456,070
4
2009-09-21T18:33:05Z
1,733,871
7
2009-11-14T10:13:08Z
[ "python", "google-app-engine" ]
I'm testing my application (on [Google App Engine](http://en.wikipedia.org/wiki/Google%5FApp%5FEngine) live servers) and the way I've written it I have about 40 db.GqlQuery() statements in my code (mostly part of classes). I keep getting db.Timeout *very often* though. How do I deal with this? I was going to surround...
Here's a decorator to retry on db.Timeout, adapted from one from Kay framework: ``` import logging, time from google.appengine.ext import db def retry_on_timeout(retries=3, interval=1.0, exponent=2.0): """A decorator to retry a given function performing db operations.""" def _decorator(func): def _wra...
Two way/reverse map
1,456,373
50
2009-09-21T19:27:35Z
1,456,392
14
2009-09-21T19:31:55Z
[ "python" ]
I'm doing this switchboard thing in python where I need to keep track of who's talking to whom, so if Alice --> Bob, then that implies that Bob --> Alice. Yes, I could populate two hash maps, but I'm wondering if anyone has an idea to do it with one. Or suggest another data structure. There are no multiple conversat...
I would just populate a second hash, with ``` reverse_map = dict((reversed(item) for item in forward_map.items())) ```
Two way/reverse map
1,456,373
50
2009-09-21T19:27:35Z
1,456,461
26
2009-09-21T19:47:24Z
[ "python" ]
I'm doing this switchboard thing in python where I need to keep track of who's talking to whom, so if Alice --> Bob, then that implies that Bob --> Alice. Yes, I could populate two hash maps, but I'm wondering if anyone has an idea to do it with one. Or suggest another data structure. There are no multiple conversat...
In your special case you can store both in one dictionary: ``` relation = {} relation['Alice'] = 'Bob' relation['Bob'] = 'Alice' ``` Since what you are describing is a symmetric relationship. `A -> B => B -> A`
Two way/reverse map
1,456,373
50
2009-09-21T19:27:35Z
13,276,237
48
2012-11-07T18:53:25Z
[ "python" ]
I'm doing this switchboard thing in python where I need to keep track of who's talking to whom, so if Alice --> Bob, then that implies that Bob --> Alice. Yes, I could populate two hash maps, but I'm wondering if anyone has an idea to do it with one. Or suggest another data structure. There are no multiple conversat...
You can create your own dictionary type by subclassing `dict` and adding the logic that you want. Here's a basic example: ``` class TwoWayDict(dict): def __setitem__(self, key, value): # Remove any previous connections with these values if key in self: del self[key] if value in ...
Return a random word from a word list in python
1,456,617
6
2009-09-21T20:19:28Z
1,456,645
17
2009-09-21T20:24:48Z
[ "python" ]
I would like to retrieve a random word from a file using python, but I do not believe my following method is best or efficient. Please assist. ``` import fileinput import _random file = [line for line in fileinput.input("/etc/dictionaries-common/words")] rand = _random.Random() print file[int(rand.random() * len(file)...
The random module defines choice(), which does what you want: ``` import random words = [line.strip() for line in open('/etc/dictionaries-common/words')] print(random.choice(words)) ``` Note also that this assumes that each word is by itself on a line in the file. If the file is very big, or if you perform this oper...
Return a random word from a word list in python
1,456,617
6
2009-09-21T20:19:28Z
1,456,761
9
2009-09-21T20:47:46Z
[ "python" ]
I would like to retrieve a random word from a file using python, but I do not believe my following method is best or efficient. Please assist. ``` import fileinput import _random file = [line for line in fileinput.input("/etc/dictionaries-common/words")] rand = _random.Random() print file[int(rand.random() * len(file)...
Another solution is to use [getline](http://docs.python.org/library/linecache.html#linecache.getline) ``` import linecache import random line_number = random.randint(0, total_num_lines) linecache.getline('/etc/dictionaries-common/words', line_number) ``` From the documentation: > The linecache module allows one to g...
Return a random word from a word list in python
1,456,617
6
2009-09-21T20:19:28Z
1,457,124
9
2009-09-21T22:00:26Z
[ "python" ]
I would like to retrieve a random word from a file using python, but I do not believe my following method is best or efficient. Please assist. ``` import fileinput import _random file = [line for line in fileinput.input("/etc/dictionaries-common/words")] rand = _random.Random() print file[int(rand.random() * len(file)...
``` >>> import random >>> random.choice(list(open('/etc/dictionaries-common/words'))) 'jaundiced\n' ``` It is efficient human-time-wise. btw, your implementation coincides with the one from stdlib's [`random.py`](http://svn.python.org/view/python/trunk/Lib/random.py?view=markup): ``` def choice(self, seq): """C...
Python Eval: What's wrong with this code?
1,456,760
2
2009-09-21T20:47:37Z
1,456,802
11
2009-09-21T20:55:24Z
[ "python", "eval", "syntax-error" ]
I'm trying to write a very simple Python utility for personal use that counts the number of lines in a text file for which a predicate specified at the command line is true. Here's the code: ``` import sys pred = sys.argv[2] if sys.argv[1] == "stdin" : handle = sys.stdin else : handle = open(sys.argv[1]) resu...
Try using exec instead of eval. The difference between the 2 is explained [here](http://www.ibiblio.org/g2swap/byteofpython/read/exec-statement.html)
Nose unable to find tests in ubuntu
1,457,104
39
2009-09-21T21:55:22Z
1,457,852
47
2009-09-22T02:24:24Z
[ "python", "nose", "nosetests" ]
Is there any reason why Nose wouldn't be able to find tests in Ubuntu 9.04? I'm using nose 0.11.1 with python 2.5.4. I can run tests only if I explicitly specify the filename. If I don't specify the filename it just says 0 tests. The same project runs tests fine on my Mac, so i'm quite stumped.
This behavior is almost certainly because your files are not named in accordance with nose's test matching behavior. From [the nose docs](https://nose.readthedocs.org/en/latest/usage.html#extended-usage): > nose collects tests automatically from python source files, directories and packages found in its working direct...
Nose unable to find tests in ubuntu
1,457,104
39
2009-09-21T21:55:22Z
1,579,787
70
2009-10-16T18:57:16Z
[ "python", "nose", "nosetests" ]
Is there any reason why Nose wouldn't be able to find tests in Ubuntu 9.04? I'm using nose 0.11.1 with python 2.5.4. I can run tests only if I explicitly specify the filename. If I don't specify the filename it just says 0 tests. The same project runs tests fine on my Mac, so i'm quite stumped.
The other thing which *always* gets me with `nose` is that it won't run tests in executable files. I'm not exactly sure why that would make a difference across Mac/Ubuntu, but it's worth a shot. Make sure that the scripts didn't somehow get `chmod +x`'d on the Mac… And if they did, fix them with `chmod -x $(find tes...
Nose unable to find tests in ubuntu
1,457,104
39
2009-09-21T21:55:22Z
5,644,762
14
2011-04-13T05:22:34Z
[ "python", "nose", "nosetests" ]
Is there any reason why Nose wouldn't be able to find tests in Ubuntu 9.04? I'm using nose 0.11.1 with python 2.5.4. I can run tests only if I explicitly specify the filename. If I don't specify the filename it just says 0 tests. The same project runs tests fine on my Mac, so i'm quite stumped.
I can confirm that as @david-wolever said, they **cannot** be executable on Ubuntu. Run ``` nosetests -vv --collect-only ``` to see full details on which files were examined.
Nose unable to find tests in ubuntu
1,457,104
39
2009-09-21T21:55:22Z
7,410,349
25
2011-09-14T01:34:38Z
[ "python", "nose", "nosetests" ]
Is there any reason why Nose wouldn't be able to find tests in Ubuntu 9.04? I'm using nose 0.11.1 with python 2.5.4. I can run tests only if I explicitly specify the filename. If I don't specify the filename it just says 0 tests. The same project runs tests fine on my Mac, so i'm quite stumped.
I had the same problem. My tests ran just fine in Windows, but not in Ubuntu. In Ubuntu, if you run: ``` nosetests -vv --collect-only ``` You'll probably see that it's skipping your test file because it's an executable: \_Tools/LintControlFiles/test\_HgLint.py **is executable; skipped** In order to get nose to cons...
Get every combination of strings
1,457,814
3
2009-09-22T02:09:25Z
1,457,836
8
2009-09-22T02:17:59Z
[ "python", "string", "combinatorics" ]
I had a combinatorics assignment that involved getting every word with length less than or equal to 6 from a specific combination of strings. In this case, it was S = { 'a', 'ab', 'ba' }. The professor just started listing them off, but I thought it would be easier solved with a program. The only problem is that I can...
Assuming you DO mean combinations (no repetitions, order does not matter): ``` import itertools S = [ 'a', 'ab', 'ba' ] for i in range(len(S)+1): for c in itertools.combinations(S, i): cc = ''.join(c) if len(cc) <= 6: print c ``` emits all the possibilities: ``` () ('a',) ('ab',) ('ba',) ('a', 'ab'...
Python serializable objects json
1,458,450
22
2009-09-22T06:37:10Z
1,458,716
42
2009-09-22T08:06:26Z
[ "python", "json", "serializable" ]
``` class gpagelet: """ Holds 1) the pagelet xpath, which is a string 2) the list of pagelet shingles, list """ def __init__(self, parent): if not isinstance( parent, gwebpage): raise Exception("Parent must be an instance of gwebpage") self.parent = parent # ...
Write your own encoder and decoder, which can be very simple like `return __dict__` e.g. here is a encoder to dump totally recursive tree structure, you can enhance it or use as it is for your own purpose ``` import json class Tree(object): def __init__(self, name, childTrees=None): self.name = name ...
Python serializable objects json
1,458,450
22
2009-09-22T06:37:10Z
11,023,172
12
2012-06-13T20:57:33Z
[ "python", "json", "serializable" ]
``` class gpagelet: """ Holds 1) the pagelet xpath, which is a string 2) the list of pagelet shingles, list """ def __init__(self, parent): if not isinstance( parent, gwebpage): raise Exception("Parent must be an instance of gwebpage") self.parent = parent # ...
[jsonpickle](http://jsonpickle.github.com/) FOR THE WIN! (Just had this same question... json pickle handles recursive/nested object graphs as well as short circuits for cyclical object graphs).
How can I protect myself from a zip bomb?
1,459,080
39
2009-09-22T09:36:21Z
1,459,154
19
2009-09-22T09:57:29Z
[ "java", "python", "security", "compression", "zip" ]
I just read about [zip bombs](http://en.wikipedia.org/wiki/Zip%5Fbomb), i.e. zip files that contain very large amount of highly compressible data (00000000000000000...). When opened they fill the server's disk. How can I detect a zip file is a zip bomb **before** unzipping it? **UPDATE** Can you tell me how is this ...
Try this in Python: ``` import zipfile z = zipfile.ZipFile('c:/a_zip_file') print 'total files size=', sum(e.file_size for e in z.infolist()) z.close() ```
How can I protect myself from a zip bomb?
1,459,080
39
2009-09-22T09:36:21Z
1,459,369
17
2009-09-22T10:50:22Z
[ "java", "python", "security", "compression", "zip" ]
I just read about [zip bombs](http://en.wikipedia.org/wiki/Zip%5Fbomb), i.e. zip files that contain very large amount of highly compressible data (00000000000000000...). When opened they fill the server's disk. How can I detect a zip file is a zip bomb **before** unzipping it? **UPDATE** Can you tell me how is this ...
Zip is, erm, an "interesting" format. A robust solution is to stream the data out, and stop when you have had enough. In Java, use `ZipInputStream` rather than `ZipFile`. The latter also requires you to store the data in a temporary file, which is also not the greatest of ideas.
pyparsing - load ABNF?
1,459,371
9
2009-09-22T10:50:31Z
1,459,981
9
2009-09-22T13:04:07Z
[ "python", "parsing", "pyparsing" ]
can pyparsing read ABNF from a file instead of having to define it in terms of python objects? If not, is there something which can do similar (load an ABNF file into a parser object)
See [this example](http://pyparsing.wikispaces.com/file/view/ebnf.py "EBNF parser") submitted by Seo Sanghyeon, which reads EBNF and parses it (using pyparsing) to create a pyparsing parser.
Why does Python keep a reference count on False and True?
1,460,454
20
2009-09-22T14:33:04Z
1,460,492
20
2009-09-22T14:39:43Z
[ "python", "reference-counting", "python-c-api" ]
I was looking at the source code to the hasattr built-in function and noticed a couple of lines that piqued my interest: ``` Py_INCREF(Py_False); return Py_False; ... Py_INCREF(Py_True); return Py_True; ``` Aren't `Py_False` and `Py_True` global values? Just out of sheer curiosity, why is Python keeping a reference...
It's to make all object handling uniform. If I'm writing C code that handles a return value from a function, I have to increment and decrement the reference count on that object. If the function returns me True, I don't want to have to check to see if it's one of those special objects to know whether to manipulate its ...
How can I get the element of a list that has a minimum/maximum property in Python?
1,460,512
2
2009-09-22T14:43:06Z
1,460,531
13
2009-09-22T14:46:56Z
[ "python", "list" ]
I have the following array in Python: ``` points_list = [point0, point1, point2] ``` where each of `points_list` is of the type: ``` class point: __init__(self, coord, value): self.coord = numpy.array(coord) self.value = value # etc... ``` And a function: ``` def distance(x,y): return numpy...
Have you tried this? ``` min(points_list, key=lambda x: distance(x, point_a)) ``` **To answer a question in comment**: `lambda` is indeed necessary here since [function specified as a `key` argument needs to accept only a single argument](http://docs.python.org/3.1/library/functions.html#min). *However*, since your ...
How to decompile a regex?
1,460,686
14
2009-09-22T15:09:24Z
1,460,695
8
2009-09-22T15:11:01Z
[ "python", "regex" ]
Is there any way to decompile a regular expression once compiled?
``` r = re.compile('some[pattern]'); print r.pattern ```
How to decompile a regex?
1,460,686
14
2009-09-22T15:09:24Z
1,460,699
32
2009-09-22T15:11:31Z
[ "python", "regex" ]
Is there any way to decompile a regular expression once compiled?
Compiled regular expression objects have a "pattern" attribute which gives the original text pattern. ``` >>> import re >>> regex = re.compile('foo (?:bar)*') >>> regex.pattern 'foo (?:bar)*' ```
Installing Mercurial on Mac OS X 10.6 Snow Leopard
1,461,374
13
2009-09-22T17:13:09Z
1,462,607
8
2009-09-22T21:08:11Z
[ "python", "osx", "mercurial", "osx-snow-leopard" ]
# Installing Mercurial on Mac OS X 10.6 Snow Leopard I installed Mercurial 1.3.1 on Mac OS X 10.6 Snow Leopard from source using the following: ``` cd ~/src curl -O http://mercurial.selenic.com/release/mercurial-1.3.1.tar.gz tar -xzvf mercurial-1.3.1.tar.gz cd mercurial-1.3.1 make all sudo make install ``` This inst...
Especially since you have Python 2.6 available you can do something like `python setup.py install --user`, which will install Mercurial with ~/.local as prefix. You don't have to change the PYTHONPATH for this but only add ~/.local/bin to your PATH. Regarding advantages and disadvantages: That all depends on what your...
Installing Mercurial on Mac OS X 10.6 Snow Leopard
1,461,374
13
2009-09-22T17:13:09Z
1,490,705
7
2009-09-29T05:28:44Z
[ "python", "osx", "mercurial", "osx-snow-leopard" ]
# Installing Mercurial on Mac OS X 10.6 Snow Leopard I installed Mercurial 1.3.1 on Mac OS X 10.6 Snow Leopard from source using the following: ``` cd ~/src curl -O http://mercurial.selenic.com/release/mercurial-1.3.1.tar.gz tar -xzvf mercurial-1.3.1.tar.gz cd mercurial-1.3.1 make all sudo make install ``` This inst...
Install mercurial - or any Python package in general - into your user home directory. Thus you can access them from any Python (of same version) or any virtualenv. See [PEP 370](http://www.python.org/dev/peps/pep-0370/) for details. ``` $ cd mercurial-x.y.z/ $ python2.6 setup.py install --user $ ~/.local/bin/hg ... ``...
Installing Mercurial on Mac OS X 10.6 Snow Leopard
1,461,374
13
2009-09-22T17:13:09Z
2,565,094
13
2010-04-02T05:11:21Z
[ "python", "osx", "mercurial", "osx-snow-leopard" ]
# Installing Mercurial on Mac OS X 10.6 Snow Leopard I installed Mercurial 1.3.1 on Mac OS X 10.6 Snow Leopard from source using the following: ``` cd ~/src curl -O http://mercurial.selenic.com/release/mercurial-1.3.1.tar.gz tar -xzvf mercurial-1.3.1.tar.gz cd mercurial-1.3.1 make all sudo make install ``` This inst...
Why need to use macports? python `easy_install` is the easiest way and error free: ``` easy_install -U mercurial ``` *It's just a simple gold bullet, all the time.*
Is it Pythonic for a function to return an iterable or non-iterable depending on its input?
1,461,392
6
2009-09-22T17:16:57Z
1,461,415
11
2009-09-22T17:21:40Z
[ "python", "return-value" ]
(Title and contents updated after reading Alex's answer) In general I believe that it's considered bad form (un-Pythonic) for a function to sometimes return an iterable and sometimes a single item depending on its parameters. For example `struct.unpack` always returns a tuple even if it contains only one item. I'm t...
If you are going to be returning iterators sometimes, and single objects on others, I'd say return always an iterator, so you don't have to think about it. Generaly, you would use that function in a context that expects an iterator, so if you'd have to check if it where a list to iterate or an object to do just one ti...
Jinja2 If Statement
1,461,484
7
2009-09-22T17:34:57Z
1,461,505
10
2009-09-22T17:39:19Z
[ "python", "jinja2" ]
The code below is a sample form I'm using to learn jinja2. As written, it returns an error saying that it doesn't recognize the {% endif %} tag. Why does this happen? ``` <html> Name: {{ name }} Print {{ num }} times Color: {{ color }} {% if convert_to_upper %}Case: Upper {% elif not convert_to_upper %}Case: Lower{% ...
I think you have your lines mixed up. Your `endif` comese before `endfilter` whereas `if` is before `filter`. That's just a syntax error.
How to improve performance of python cgi that reads a big file and returns it as a download?
1,462,330
2
2009-09-22T20:17:00Z
1,463,235
9
2009-09-22T23:53:29Z
[ "python", "cgi", "performance", "mod-wsgi" ]
I have this python cgi script that checks if it hasn't been accessed to many times from the same IP, and if everything is ok, reads a big file form disk (11MB) and then returns it as a download. It works,but performance sucks. The bottleneck seems to be reading this huge file over and over: ``` def download_demo(): ...
Use mod\_wsgi and use something akin to: ``` def application(environ, start_response): status = '200 OK' output = 'Hello World!' response_headers = [('Content-type', 'text/plain')] start_response(status, response_headers) file = open('/usr/share/dict/words', 'rb') return environ['wsgi.file_wr...
What are sqlite development headers and how to install them?
1,462,565
10
2009-09-22T20:57:06Z
1,462,624
16
2009-09-22T21:10:39Z
[ "python", "header", "pysqlite" ]
I am trying to install pysqlite and have troubles with that. I found out that the most probable reason of that is missing sqlite headers and I have to install them. However, I have no ideas what these headers are (where I can find them, what they are doing and how to install them). Can anybody, pleas, help me with th...
debian/ubuntu: ``` $ apt-get install libsqlite3-dev # or rpm -i sqlite-devel-something.rpm ``` --- I think a number of interpreters just recompile their small connection libraries on installation, but to do that they need the C .h files in addition to the library to link against. You may already have the library, be...
What are sqlite development headers and how to install them?
1,462,565
10
2009-09-22T20:57:06Z
5,671,345
7
2011-04-15T00:52:50Z
[ "python", "header", "pysqlite" ]
I am trying to install pysqlite and have troubles with that. I found out that the most probable reason of that is missing sqlite headers and I have to install them. However, I have no ideas what these headers are (where I can find them, what they are doing and how to install them). Can anybody, pleas, help me with th...
For me this worked (Redhat/CentOS): $ sudo yum install sqlite-devel