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 do I get IntelliJ to recognize common Python modules?
6,102,908
94
2011-05-23T20:53:57Z
11,590,745
103
2012-07-21T08:41:15Z
[ "python", "intellij-idea" ]
I'm using IntelliJ 10 IDEA Ultimate Edition. I've created a new file Test.py, and IntelliJ has correctly switched to Python parsing mode. (I can confirm this by typing "d", it pops up "def" as a suggestion, and hitting tab correctly gives me "def :") However, when I try this code... ``` import os cwd = os.getcw <Ct...
Just create and add Python SDK ``` File -> Project Structure -> Project -> Project SDK -> new ``` and select the installation path of your Python interpreter (for example, `C:\Python26` in windows and `/usr/bin/python2.7` in Linux) as the home path. Related discussion: <http://devnet.jetbrains.net/thread/286883>
How do I get IntelliJ to recognize common Python modules?
6,102,908
94
2011-05-23T20:53:57Z
29,459,562
15
2015-04-05T16:36:27Z
[ "python", "intellij-idea" ]
I'm using IntelliJ 10 IDEA Ultimate Edition. I've created a new file Test.py, and IntelliJ has correctly switched to Python parsing mode. (I can confirm this by typing "d", it pops up "def" as a suggestion, and hitting tab correctly gives me "def :") However, when I try this code... ``` import os cwd = os.getcw <Ct...
If your Python SDK is properly configured and you are still facing the problem that builtins are not recognized, try this: ``` File -> Invalidate Caches/Restart ```
Python client support for running Hive on top of Amazon EMR
6,103,816
6
2011-05-23T22:36:56Z
6,157,646
8
2011-05-27T21:01:32Z
[ "python", "hive", "boto", "elastic-map-reduce" ]
I've noticed that neither mrjob nor boto supports a Python interface to submit and run Hive jobs on Amazon Elastic MapReduce (EMR). Are there any other Python client libraries that supports running Hive on EMR?
With boto you can do something like this: ``` args1 = [u's3://us-east-1.elasticmapreduce/libs/hive/hive-script', u'--base-path', u's3://us-east-1.elasticmapreduce/libs/hive/', u'--install-hive', u'--hive-versions', u'0.7'] args2 = [u's3://us-east-1.elasticmapreduce/libs/hiv...
How to properly use unit-testing's assertRaises() with NoneType objects?
6,103,825
90
2011-05-23T22:38:25Z
6,103,877
51
2011-05-23T22:46:26Z
[ "python", "unit-testing" ]
I did a simple test case: ``` def setUp(self): self.testListNone = None def testListSlicing(self): self.assertRaises(TypeError, self.testListNone[:1]) ``` and I am expecting test to pass, but I am getting exception: ``` Traceback (most recent call last): self.assertRaises(TypeError, self.testListNone[:1]...
The usual way to use `assertRaises` is to call a function: ``` self.assertRaises(TypeError, test_function, args) ``` to test that the function call test\_function(args) raises a TypeError. The problem with `self.testListNone[:1]` is that Python evaluates the expression immediately, before the `assertRaises` method i...
How to properly use unit-testing's assertRaises() with NoneType objects?
6,103,825
90
2011-05-23T22:38:25Z
6,103,930
66
2011-05-23T22:53:21Z
[ "python", "unit-testing" ]
I did a simple test case: ``` def setUp(self): self.testListNone = None def testListSlicing(self): self.assertRaises(TypeError, self.testListNone[:1]) ``` and I am expecting test to pass, but I am getting exception: ``` Traceback (most recent call last): self.assertRaises(TypeError, self.testListNone[:1]...
The problem is the `TypeError` gets raised 'before' `assertRaises` gets called since the arguments to `assertRaises` need to be evaluated before the method can be called. You need to pass a `lambda` expression like: ``` self.assertRaises(TypeError, lambda: self.testListNone[:1]) ```
How to properly use unit-testing's assertRaises() with NoneType objects?
6,103,825
90
2011-05-23T22:38:25Z
6,103,983
139
2011-05-23T23:00:43Z
[ "python", "unit-testing" ]
I did a simple test case: ``` def setUp(self): self.testListNone = None def testListSlicing(self): self.assertRaises(TypeError, self.testListNone[:1]) ``` and I am expecting test to pass, but I am getting exception: ``` Traceback (most recent call last): self.assertRaises(TypeError, self.testListNone[:1]...
If you are using python2.7 or above you can use the ability of [assertRaises](http://docs.python.org/library/unittest.html#unittest.TestCase.assertRaises) to be use as a context manager and do: ``` with self.assertRaises(TypeError): self.testListNone[:1] ``` If you are using python2.6 another way beside the one g...
Fully parsable dictionary/thesaurus
6,103,907
4
2011-05-23T22:50:12Z
6,105,439
7
2011-05-24T03:38:10Z
[ "python", "parsing", "osx", "dictionary", "words" ]
I'm in the early stages of designing a series of simple word games which I hope will help me learn new words. A crucial part of the ideas that I have is a fully parsable dictionary; I want to be able to use regular expressions to search the dictionary for given words and extract certain other bits of information (e.g. ...
The [nltk wordnet corpus](http://code.google.com/p/nltk/) provides a programmatic interface to a "large lexical database of English words". You can navigate the word graph based on a variety of relationships. It meets the requirements for showing "definition, part-of-speech, synonyms, antonyms, quotes", and "from a dic...
Using a tuples of values in sqlalchemy mapped collection
6,104,059
3
2011-05-23T23:09:22Z
6,104,550
8
2011-05-24T00:28:42Z
[ "python", "sqlalchemy" ]
In a many-to-many relationship, I have some extra data on the association table to describe the relationship (a quantity and a boolean value). I'd like to use a mapped collection to avoid working directly with the association objects, but I can't figure out how to use a tuple for the values in the mapping. As far as I ...
the linked answer has all the components. attribute\_mapped\_collection and association\_proxy can do lots together. First here is the dictionary of string->tuple(int, boolean) (updated for m2m): ``` from sqlalchemy import Integer, Boolean, String, Column, create_engine, \ ForeignKey from sqlalchemy.orm import Ses...
I don't understand this python __del__ behaviour
6,104,535
16
2011-05-24T00:24:44Z
6,104,568
22
2011-05-24T00:31:45Z
[ "python", "del" ]
Can someone explain why the following code behaves the way it does: ``` import types class Dummy(): def __init__(self, name): self.name = name def __del__(self): print "delete",self.name d1 = Dummy("d1") del d1 d1 = None print "after d1" d2 = Dummy("d2") def func(self): print "func calle...
You cannot assume that `__del__` will ever be called - it is not a place to hope that resources are automagically deallocated. If you want to make sure that a (non-memory) resource is released, you should make a `release()` or similar method and then call that explicitly (or use it in a [context manager](http://docs.py...
I don't understand this python __del__ behaviour
6,104,535
16
2011-05-24T00:24:44Z
6,104,605
7
2011-05-24T00:37:48Z
[ "python", "del" ]
Can someone explain why the following code behaves the way it does: ``` import types class Dummy(): def __init__(self, name): self.name = name def __del__(self): print "delete",self.name d1 = Dummy("d1") del d1 d1 = None print "after d1" d2 = Dummy("d2") def func(self): print "func calle...
Instead of **del**, you can use the `with` operator. <http://effbot.org/zone/python-with-statement.htm> just like with filetype objects, you could something like ``` with Dummy('d1') as d: #stuff #d is guaranteed to be out of scope ```
I don't understand this python __del__ behaviour
6,104,535
16
2011-05-24T00:24:44Z
6,165,533
11
2011-05-29T02:04:09Z
[ "python", "del" ]
Can someone explain why the following code behaves the way it does: ``` import types class Dummy(): def __init__(self, name): self.name = name def __del__(self): print "delete",self.name d1 = Dummy("d1") del d1 d1 = None print "after d1" d2 = Dummy("d2") def func(self): print "func calle...
I'm providing my own answer because, while I appreciate the advice to avoid \_\_ del\_\_, my question was how to get it to work properly for the code sample provided. **Short version:** The following code uses weakref to avoid the circular reference. I thought I'd tried this before posting the question, but I guess I ...
How to compare a list of lists/sets in python?
6,105,777
16
2011-05-24T04:46:59Z
6,105,826
22
2011-05-24T04:54:36Z
[ "python", "list", "compare", "set", "tuples" ]
What is the easiest way to compare the 2 lists/sets and output the differences? Are there any built in functions that will help me compare nested lists/sets? Inputs: ``` First_list = [['Test.doc, '1a1a1a', 1111], ['Test2.doc, '2b2b2b', 2222], ['Test3.doc, '3c3c3c', 3333] ] ...
So you want the difference between two lists of items. ``` first_list = [['Test.doc', '1a1a1a', 1111], ['Test2.doc', '2b2b2b', 2222], ['Test3.doc', '3c3c3c', 3333]] secnd_list = [['Test.doc', '1a1a1a', 1111], ['Test2.doc', '2b2b2b', 2222], ['Test3.doc', '8p8p...
How to rename a file and preserve creation date in Python
6,106,303
3
2011-05-24T05:59:00Z
6,107,220
7
2011-05-24T07:43:26Z
[ "python", "filesystems" ]
I know that the creation date isn't stored in the filesystem itself, but I'm encountering the problem that when I use `os.rename`, it's updating the creation date of the files I'm working with. Is it possible to rename a file without changing its original creation date?
As said by Tudor you should use [os.stat()](http://docs.python.org/library/os.html#os.stat) and [os.utime()](http://docs.python.org/library/os.html#os.utime). ``` stat = os.stat(myfile) // your code - rename access and modify your file os.utime(my_new_file, (stat.st_atime, stat.st_mtime)) ``` try this.
How to receive arguments via shell pipe in python?
6,106,437
8
2011-05-24T06:17:16Z
6,106,504
15
2011-05-24T06:23:18Z
[ "python", "linux", "shell", "pipe" ]
I would like to do something like this: ``` find -name "foo*" | python main.py ``` and access all the files that were found by the find program. How do I access that in Python?
``` import sys for line in sys.stdin: print line ```
How can I set default values for SafeConfigParser?
6,107,149
13
2011-05-24T07:35:23Z
6,107,377
16
2011-05-24T08:00:11Z
[ "python", "data-structures", "default", "default-value", "configparser" ]
I have a config file as follows: ``` [job] mailto=bob logFile=blahDeBlah.txt ``` I want to read the options using `SafeConfigParser`: ``` values = {} config = ConfigParser.SafeConfigParser() try: config.read(configFile) jobSection = 'job' values['mailto'] = config.get( jobSection, 'mailto' ) values...
Use the `defaults` parameter to the constructor: ``` # class ConfigParser.SafeConfigParser([defaults[, dict_type]]) # config = ConfigParser.SafeConfigParser({'nothingThere': 'lalalalala'}) ... ... # If the job section has no "nothingThere", "lalalalala" will be returned # config.get(jobSection, 'nothingThere') ```
Sphinx, the best practices
6,107,310
13
2011-05-24T07:52:07Z
6,107,560
9
2011-05-24T08:18:13Z
[ "python", "python-sphinx" ]
I just started to use Sphinx tool to generate a documentation for my code. But I'm a bit confused because it's not as easy as I expected. I create the Sphinx doc using: ``` sphinx-quickstart ``` and then I create my \*.rst files into the "source" folder. Seems like I need to create a \*.rst file for each module I wan...
One simple way to document your application quickly is to just write docstrings into classes and methods as per usual, and then complement them if required in the .rst files. template.rst: ``` Templating ---------- Notes about templating would go here. .. automodule:: myapp.lib.template :members: :undoc-memb...
Sphinx, the best practices
6,107,310
13
2011-05-24T07:52:07Z
6,109,098
9
2011-05-24T10:32:11Z
[ "python", "python-sphinx" ]
I just started to use Sphinx tool to generate a documentation for my code. But I'm a bit confused because it's not as easy as I expected. I create the Sphinx doc using: ``` sphinx-quickstart ``` and then I create my \*.rst files into the "source" folder. Seems like I need to create a \*.rst file for each module I wan...
There is no easier way. Sphinx is not an API doc generator like epydoc, but instead focuses on handwritten documentation. Consequently you need to write a lot of the documents by hand. The advantage is, that you can also write documentation beyond API docs (e.g. tutorials, usage guides, even end user documentation), a...
Which command to use for checking whether python is 64bit or 32bit
6,107,905
16
2011-05-24T08:49:38Z
6,107,982
28
2011-05-24T08:55:57Z
[ "python", "linux", "osx", "32bit-64bit" ]
I am not able to find any command to check if my python is compiled for 32bit system or 64bit system. I tried > python and it only tells the version Also when I go to python download site they have one version of python for linux but two versions for mac i.e 32bit and 64bit.
For Python 2.6 and above, you can use `sys.maxsize` as documented [here](http://docs.python.org/library/platform.html#cross-platform): ``` import sys is_64bits = sys.maxsize > 2**32 ``` UPDATE: I notice that I didn't really answer the question posed. While the above test does accurately tell you whether the interpret...
How do I remove south from a django project
6,107,978
6
2011-05-24T08:55:39Z
6,108,042
10
2011-05-24T09:01:01Z
[ "python", "django", "django-south" ]
I installed south and tried a few changes using it, which didn't exactly work out the way I wanted it to. Thankfully, my data is safe but locked into south. I want to remove south and use syncdb normally now, how do I do that without affecting my data?
Remove `'south'` from INSTALLED\_APPS, remove `south_migrations` table from DB.
Checking for interactive shell in a Python script
6,108,330
10
2011-05-24T09:24:44Z
6,108,504
11
2011-05-24T09:42:00Z
[ "python", "shell", "pipe", "interactive" ]
I need to determine whether the shell which invoked my Python script was in interactive mode or not. If it was in interactive mode, the program should pipe output to less(1) for easy reading. If not, it should simply print its output to stdout, to allow it to be piped away to a printer, file, or a different pager. In ...
This is often works well enough ``` import os, sys if os.isatty(sys.stdout.fileno()): ... ```
How can I view django home page outside my server
6,109,890
3
2011-05-24T11:46:24Z
6,111,790
9
2011-05-24T14:13:27Z
[ "python", "django" ]
I have just installed django with python 2.7. After creating intitial project it says to check at ``` http://127.0.0.1:8000/ ``` But that is my VPS server and i can't open browser there. i tried `http://vpsIPaddress:8000` but it didn't worked
You can start your server with following command: ``` python manage.py runserver 0.0.0.0:12345 ``` Then, the dev server will bind all the possible ip address on your server which is a convenient way for test :)
Quick question regarding format of if-elif statements
6,110,601
2
2011-05-24T12:43:32Z
6,110,659
9
2011-05-24T12:48:02Z
[ "python", "if-statement" ]
If I wanted a group of if elif statements to execute to a single order; for example: ``` if int(one[1]) == solution: ``` and ``` if int(two[1]) == solution: ``` to execute a a single statement: ``` print "Hello World" ``` What would be the best format and syntaxically correct way to input this? I tried: ``` if ...
If you want to print it when **both** conditions are true you have to use `and` ``` if (int(one[1]) == solution) and (int(two[1]) == solution): print "Hello, world" ``` if you want to print it if **one ore more** condition is true you have to use `or` the same way ``` if (int(one[1]) == solution) or (int(two[1])...
How to get the Tkinter Label text?
6,112,482
8
2011-05-24T14:58:19Z
6,113,152
21
2011-05-24T15:48:47Z
[ "python", "tkinter", "label" ]
Im making a list of addresses that the user will select from, and the address text will be returned. I need to use `Tkinter.Label` because the `Tkinter.Listbox` will not allow for newlines. The kicker is there is no `.get()`-like method in the Label class... I know I can do something like: ``` v = StringVar() Label(...
To get the value out of a label you can use the [`cget`](http://effbot.org/tkinterbook/widget.htm#Tkinter.Widget.cget-method) method, which can be used to get the value of *any of the configuration options* (in this case, the option `text`). ``` l = tk.Label(text="hello, world") ... print "the label is", l.cget("text"...
How to override the automatically created docstring data for Boost::Python?
6,114,462
8
2011-05-24T17:33:13Z
6,115,065
16
2011-05-24T18:27:44Z
[ "c++", "python", "boost", "documentation", "boost-python" ]
I am currently working developing a C++-based module for Python. I have found that Boost::Python is working quite well for what I want to accomplish. However, I am now running into some issues with the docstring that is being generated by Boost::Python. Given the following Boost::Python definitions: ``` BOOST_PYTHON_M...
* Use the **boost::python::docstring\_options** class to define your auto-created docstring options. * All **def** functions take a docstring as the last parameter. * All **class\_** definitions take the class docstring as the last parameter I.e.: ``` using boost::python; BOOST_PYTHON_MODULE(foo) { // This will ena...
Converting PNG32 to PNG8 with PIL while preserving transparency
6,114,534
5
2011-05-24T17:39:50Z
6,123,279
10
2011-05-25T10:50:53Z
[ "python", "png", "python-imaging-library" ]
I would like to convert a PNG32 image (with transparency) to PNG8 with Python Image Library. So far I have succeeded converting to PNG8 with a solid background. Below is what I am doing: ``` from PIL import Image im = Image.open("logo_256.png") im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255) i...
After much searching on the net, here is the code to accomplish what I asked for: ``` from PIL import Image im = Image.open("logo_256.png") # PIL complains if you don't load explicitly im.load() # Get the alpha band alpha = im.split()[-1] im = im.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255) # S...
English grammar for parsing in NLTK
6,115,677
36
2011-05-24T19:17:40Z
17,935,542
21
2013-07-29T22:52:35Z
[ "python", "nlp", "grammar", "nltk" ]
Is there a ready-to-use English grammar that I can just load it and use in NLTK? I've searched around examples of parsing with NLTK, but it seems like that I have to manually specify grammar before parsing a sentence. Thanks a lot!
You can take a look at [pyStatParser](https://github.com/emilmont/pyStatParser), a simple python statistical parser that returns NLTK parse Trees. It comes with public treebanks and it generates the grammar model only the first time you instantiate a Parser object (in about 8 seconds). It uses a CKY algorithm and it pa...
English grammar for parsing in NLTK
6,115,677
36
2011-05-24T19:17:40Z
32,466,634
11
2015-09-08T20:25:38Z
[ "python", "nlp", "grammar", "nltk" ]
Is there a ready-to-use English grammar that I can just load it and use in NLTK? I've searched around examples of parsing with NLTK, but it seems like that I have to manually specify grammar before parsing a sentence. Thanks a lot!
My library, [spaCy](http://spacy.io), provides a high performance dependency parser. Installation: ``` pip install spacy python -m spacy.en.download all ``` Usage: ``` from spacy.en import English nlp = English() doc = nlp(u'A whole document.\nNo preprocessing require. Robust to arbitrary formating.') for sent in...
Screenscaping aspx with Python Mechanize - Javascript form submission
6,116,023
6
2011-05-24T19:49:55Z
6,124,393
8
2011-05-25T12:23:08Z
[ "asp.net", "python", "mechanize", "scraperwiki" ]
I'm trying to scrape UK Food Ratings Agency data *aspx* seach results pages (e.,g <http://ratings.food.gov.uk/QuickSearch.aspx?q=po30> ) using Mechanize/Python on scraperwiki ( <http://scraperwiki.com/scrapers/food_standards_agency/> ) but coming up with a problem when trying to follow "next" page links which have the ...
Mechanize doesn´t handle javascript, but for this particular case it isn´t needed. First we open the result page with mechanize ``` url = 'http://ratings.food.gov.uk/QuickSearch.aspx?q=po30' br = mechanize.Browser() br.set_handle_robots(False) br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US;...
Boost::Python- possible to automatically convert from dict --> std::map?
6,116,345
11
2011-05-24T20:19:50Z
6,118,691
18
2011-05-25T01:44:45Z
[ "c++", "python", "boost", "type-conversion", "boost-python" ]
I've got a C++ class, with a member function that can take a small-to-large number of parameters. Lets name those parameters, a-f. All parameters have default values. As a part of the python project I am working on, I want to expose this class to python. Currently, the member function looks something like this: ``` cl...
I think there's a couple of ways that are easier to accomplish than writing your own converter. You can use boost::python's map\_indexing\_suite to do the conversion for you, or you can use keyword arguments in python. I personally prefer keyword arguments, as this is the more "Pythonic" way to do this. So this is you...
DestroyWindow does not close window on Mac using Python and OpenCV
6,116,564
10
2011-05-24T20:38:29Z
15,058,451
18
2013-02-25T00:32:45Z
[ "python", "user-interface", "opencv" ]
My program generates a series of windows using the following code: ``` def display(img, name, fun): global clicked cv.NamedWindow(name, 1) cv.ShowImage(name, img) cv.SetMouseCallback(name, fun, img) while cv.WaitKey(33) == -1: if clicked == 1: clicked = 0 cv.ShowIm...
You need to run `cv.StartWindowThread()` after opening the window. I had the same issue and now this works for me. Hope this helps for future readers. And there is also a `cv2` binding (I advise to use that instead of `cv`). This code works for me: ``` import cv2 as cv import time WINDOW_NAME = "win" image = cv.im...
Python replace multiple strings
6,116,978
102
2011-05-24T21:15:23Z
6,117,042
65
2011-05-24T21:20:23Z
[ "python", "text", "replace" ]
I would like to use the .replace function to replace multiple strings. I currently have ``` string.replace("condition1", "") ``` but would like to have something like ``` string.replace("condition1", "").replace("condition2", "text") ``` although that does not feel like good syntax what is the proper way to do th...
You could just make a nice little looping function. ``` def replace_all(text, dic): for i, j in dic.iteritems(): text = text.replace(i, j) return text ``` where `text` is the complete string and `dic` is a dictionary — each definition is a string that will replace a match to the term. **Note**: in Py...
Python replace multiple strings
6,116,978
102
2011-05-24T21:15:23Z
6,117,124
101
2011-05-24T21:26:54Z
[ "python", "text", "replace" ]
I would like to use the .replace function to replace multiple strings. I currently have ``` string.replace("condition1", "") ``` but would like to have something like ``` string.replace("condition1", "").replace("condition2", "text") ``` although that does not feel like good syntax what is the proper way to do th...
Here is a short example that should do the trick with regular expressions: ``` import re rep = {"condition1": "", "condition2": "text"} # define desired replacements here # use these three lines to do the replacement rep = dict((re.escape(k), v) for k, v in rep.iteritems()) pattern = re.compile("|".join(rep.keys()))...
Python replace multiple strings
6,116,978
102
2011-05-24T21:15:23Z
6,117,393
14
2011-05-24T21:54:14Z
[ "python", "text", "replace" ]
I would like to use the .replace function to replace multiple strings. I currently have ``` string.replace("condition1", "") ``` but would like to have something like ``` string.replace("condition1", "").replace("condition2", "text") ``` although that does not feel like good syntax what is the proper way to do th...
I would like to propose the usage of string templates. Just place the string to be replaced in a dictionary and all is set! Example from [docs.python.org](http://docs.python.org/library/string.html#template-strings) ``` >>> from string import Template >>> s = Template('$who likes $what') >>> s.substitute(who='tim', wh...
Python replace multiple strings
6,116,978
102
2011-05-24T21:15:23Z
9,479,972
45
2012-02-28T10:08:33Z
[ "python", "text", "replace" ]
I would like to use the .replace function to replace multiple strings. I currently have ``` string.replace("condition1", "") ``` but would like to have something like ``` string.replace("condition1", "").replace("condition2", "text") ``` although that does not feel like good syntax what is the proper way to do th...
Here is a variant of the first solution using reduce, in case you like being functional. :) ``` repls = {'hello' : 'goodbye', 'world' : 'earth'} s = 'hello, world' reduce(lambda a, kv: a.replace(*kv), repls.iteritems(), s) ``` martineau's even better version: ``` repls = ('hello', 'goodbye'), ('world', 'earth') s = ...
Python replace multiple strings
6,116,978
102
2011-05-24T21:15:23Z
15,221,068
18
2013-03-05T10:09:12Z
[ "python", "text", "replace" ]
I would like to use the .replace function to replace multiple strings. I currently have ``` string.replace("condition1", "") ``` but would like to have something like ``` string.replace("condition1", "").replace("condition2", "text") ``` although that does not feel like good syntax what is the proper way to do th...
I built this upon F.J.s excellent answer: ``` import re def multiple_replacer(*key_values): replace_dict = dict(key_values) replacement_function = lambda match: replace_dict[match.group(0)] pattern = re.compile("|".join([re.escape(k) for k, v in key_values]), re.M) return lambda string: pattern.sub(re...
Python replace multiple strings
6,116,978
102
2011-05-24T21:15:23Z
15,448,887
11
2013-03-16T11:47:57Z
[ "python", "text", "replace" ]
I would like to use the .replace function to replace multiple strings. I currently have ``` string.replace("condition1", "") ``` but would like to have something like ``` string.replace("condition1", "").replace("condition2", "text") ``` although that does not feel like good syntax what is the proper way to do th...
This is just a more concise recap of F.J and MiniQuark great answers. All you need to achieve **multiple simultaneous string replacements** is the following function: ``` import re def multiple_replace(string, rep_dict): pattern = re.compile("|".join([re.escape(k) for k in rep_dict.keys()]), re.M) return patte...
Problems compiling mod_wsgi in virtualenv
6,116,985
5
2011-05-24T21:15:48Z
6,118,155
7
2011-05-24T23:54:08Z
[ "python", "mod-wsgi", "virtualenv" ]
I'm trying to compile mod\_wsgi (version 3.3), Python 2.6, on a CentOS server - but under `virtualenv`, with no success. I'm getting the error: > /usr/bin/ld: > /home/python26/lib/libpython2.6.a(node.o): > relocation R\_X86\_64\_32 against `a > local symbol' can not be used when > making a shared object; recompile wit...
Relevant parts of the documentation are: <http://code.google.com/p/modwsgi/wiki/InstallationIssues#Mixing_32_Bit_And_64_Bit_Packages> This mentions the -fPIC problem. And: <http://code.google.com/p/modwsgi/wiki/InstallationIssues#Unable_To_Find_Python_Shared_Library> This mentions need to use LD\_RUN\_PATH when sh...
Twisted: Making code non-blocking
6,117,587
19
2011-05-24T22:16:48Z
6,118,510
25
2011-05-25T01:05:23Z
[ "python", "asynchronous", "twisted", "blocking" ]
I'm a bit puzzled about how to write asynchronous code in python/twisted. Suppose (for arguments sake) I am exposing a function to the world that will take a number and return True/False if it is prime/non-prime, so it looks vaguely like this: ``` def IsPrime(numberin): for n in range(2,numberin): if numbe...
I think your current understanding is basically correct. Twisted is just a Python library and the Python code you write to use it executes normally as you would expect Python code to: if you have only a single thread (and a single process), then only one thing happens at a time. Almost no APIs provided by Twisted creat...
INSERT INTO and String Concatenation with Python
6,117,646
8
2011-05-24T22:24:45Z
6,117,845
13
2011-05-24T22:57:33Z
[ "python", "postgis", "psycopg2" ]
I have hit a major speed bump in inserting data in to my DB. You can see from the code below that I am simply building the SQL statement to pass in to the execute command. The values are correct and all is well there but the python interpreter seems to be adding and removing quotes from the params at runtime. This is ...
You are passing the string `ST_GeomFromText('POINT(..)')` as a parameter, and psycopg2 is escaping it. However `ST_GeomFromText(..)` is a PostGIS function, not data you are inserting. To fix this you need to move the `ST_GeomFromText` function into the static SQL. For example: ``` sql = ''' INSERT INTO foo (point_...
Negation in Python
6,117,733
61
2011-05-24T22:38:35Z
6,117,757
18
2011-05-24T22:41:34Z
[ "python", "negation" ]
I'm trying to create a directory if the path doesn't exist, but the ! (not) operator doesn't work. I'm not sure how to negate in Python... What's the correct way to do this? ``` if (!os.path.exists("/usr/share/sounds/blues")): proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"]) proc.wait() ``...
Python prefers English keywords to punctuation. Use `not x`, i.e. `not os.path.exists(...)`. The same thing goes for `&&` and `||` which are `and` and `or` in Python.
Negation in Python
6,117,733
61
2011-05-24T22:38:35Z
6,117,761
7
2011-05-24T22:41:46Z
[ "python", "negation" ]
I'm trying to create a directory if the path doesn't exist, but the ! (not) operator doesn't work. I'm not sure how to negate in Python... What's the correct way to do this? ``` if (!os.path.exists("/usr/share/sounds/blues")): proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"]) proc.wait() ``...
try instead: ``` if not os.path.exists(pathName): do this ```
Negation in Python
6,117,733
61
2011-05-24T22:38:35Z
6,117,762
92
2011-05-24T22:41:50Z
[ "python", "negation" ]
I'm trying to create a directory if the path doesn't exist, but the ! (not) operator doesn't work. I'm not sure how to negate in Python... What's the correct way to do this? ``` if (!os.path.exists("/usr/share/sounds/blues")): proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"]) proc.wait() ``...
The negation operator in Python is `not`. Therefore just replace your `!` with `not`. For your example, do this: ``` if not os.path.exists("/usr/share/sounds/blues") : proc = subprocess.Popen(["mkdir", "/usr/share/sounds/blues"]) proc.wait() ``` --- For your specific example (as Neil said in the comments), ...
Tornado AsyncHTTPClient fetch callback: Extra parameters?
6,117,920
16
2011-05-24T23:09:31Z
6,129,850
21
2011-05-25T19:34:19Z
[ "python", "asynchronous", "tornado" ]
I'm sort of new to this whole async game (mostly been a Django guy), but I was wondering: how can I pass extra parameters to Tornado's AsyncHTTPClient.fetch callback? For example, I'm tracking the number of times a callback has been called (in order to wait until a certain number have executed before working on the dat...
You need to "bind" your additional arguments. Use functools.partial, like this: ``` items = .. iteration = .. cb = functools.partial(self.resp, items, iteration) ``` or you could use lambda, like this: ``` cb = lambda : self.resp(items, iteration) ``` (you probably need to add the signature to def resp(self, items,...
Dynamically add member function to an instance of a class in Python
6,118,592
10
2011-05-25T01:25:39Z
6,118,681
15
2011-05-25T01:42:44Z
[ "python" ]
When I do the following: ``` class C: pass def f( self ): print self a = C() a.f = f a.f() ``` I get the following error at the line a.f(): TypeError: f() takes exactly 1 argument (0 given) The problem appears to be that when f is added to the instance, a, it is treated like a function that is stored inside of...
``` import types class C: pass def f(self): print self a = C() a.f = types.MethodType(f,a) a.f() ```
how to insert a string to pdf using pypdf?
6,119,484
7
2011-05-25T04:16:21Z
6,119,593
7
2011-05-25T04:37:30Z
[ "python", "pypdf" ]
sorry,.. i'am a noob in python.. I need to create a pdf file, without using an existing pdf files.. (pure create a new one) i have googling, and lot of them is merge 2 pdf or create a new file copies from a particular page in another file... what i want to achieve is make a report page (in chart), but for first step...
You want "pisa" or "reportlab" for generating arbitrary PDF documents, not "pypdf". <http://www.xhtml2pdf.com/doc/pisa-en.html> <http://www.reportlab.org>
python : is decorators for method arguments possible?
6,122,496
3
2011-05-25T09:49:11Z
6,122,583
8
2011-05-25T09:56:34Z
[ "python", "methods", "arguments", "decorator" ]
Is it possible to decorate method arguments? Something like: ``` class SampleEntity (BaseEntity) : def someOperation (self, @Param(type="int", unit="MB")i, str) : pass ``` Basically I want the developer to be able to specify metadata about the class, properties, methods, arguments etc which I can process ...
No, but in Python 3 you can use [annotations](http://www.python.org/dev/peps/pep-3107/). ``` def func(arg: Param(type = 'int', unit = 'MB')): pass ``` Annotations can hold any information you want, language doesn't define what should go there. You can access them with `func.__annotations__` dict later.
How to convert string to variable name?
6,122,816
8
2011-05-25T10:14:52Z
6,122,893
11
2011-05-25T10:20:56Z
[ "python", "string", "variables", "module", "introspection" ]
I would like to know how to convert a string input into a variable name to use into Python code. A concrete example: ``` def insrospect(foo, bar): requested_module = makestringvariable(foo) requested_object = makestringvariable(bar) import requested_module for item in inspect.getmemebers(requested_modu...
with the [\_\_import\_\_](http://docs.python.org/library/functions.html?highlight=import#__import__) function and the [getattr](http://docs.python.org/library/functions.html#getattr) magic, you will be able to directly write this : ``` import importlib def introspect(foo, bar): imported_module = importlib.import_m...
SMTP AUTH extension trouble with Python
6,123,072
2
2011-05-25T10:34:31Z
6,123,242
8
2011-05-25T10:47:55Z
[ "python", "email", "authentication", "smtp", "smtplib" ]
I am trying to write a simple Python script to send emails through my company's SMTP server. I am using the following piece of code. ``` #! /usr/local/bin/python import sys,re,os,datetime from smtplib import SMTP #Email function def sendEmail(message): sender="SENDERID@COMPANY.com" receivers=['REVEIV...
The error you get means the SMTP server you're talking to doesn't claim to support authentication. If you look at the debug output you'll see that none of the responses to your `EHLO`s contain the necessary declaration for `AUTH`. If it did (properly) support authentication, one of the responses would be something like...
Python/imaplib - How to get messages' labels?
6,123,164
5
2011-05-25T10:41:43Z
6,902,780
9
2011-08-01T18:36:27Z
[ "python", "gmail", "imaplib" ]
I'm using imaplib for my project because I need to access gmails accounts. Fact: With gmail's labels each message may be on an arbitrary number of folders/boxes/labels. The problem is that I would like to get every single label from every single message. The first solution it cames to my mind is to use "All Mail" fol...
To get all the labels for a given message within gmail you can do the following ``` t, d = imapconn.uid('FETCH', uid, '(X-GM-LABELS)') or t, d = imapconn.fetch(uid, '(X-GM-LABELS)') ``` BTW: You can find more on gmail imap extensions at <http://code.google.com/apis/gmail/imap/>
howto uncompress gzipped data in a byte array?
6,123,223
8
2011-05-25T10:46:26Z
6,124,315
14
2011-05-25T12:16:03Z
[ "python" ]
I have a byte array containing data that is compressed by gzip. Now I need to uncompress this data. How can this be achieved?
zlib.decompress(data, 15 + 32) should autodetect whether you have `gzip` data or `zlib` data. zlib.decompress(data, 15 + 16) should work if `gzip` and barf if `zlib`. Here it is with Python 2.7.1, creating a little gz file, reading it back, and decompressing it: ``` >>> import gzip, zlib >>> f = gzip.open('foo.gz', ...
Equivalent to InnerHTML when using lxml.html to parse HTML
6,123,351
14
2011-05-25T10:56:44Z
6,123,758
9
2011-05-25T11:29:53Z
[ "python", "parsing", "lxml" ]
I'm working on a script using lxml.html to parse web pages. I have done a fair bit of BeautifulSoup in my time but am now experimenting with lxml due to its speed. I would like to know what the most sensible way in the library is to do the equivalent of Javascript's InnerHtml - that is, to retrieve or set the complete...
You can get the children of an ElementTree node using the getchildren() or iterdescendants() methods of the root node: ``` >>> from lxml import etree >>> from cStringIO import StringIO >>> t = etree.parse(StringIO("""<body> ... <h1>A title</h1> ... <p>Some text</p> ... </body>""")) >>> root = t.getroot() >>> for child...
Equivalent to InnerHTML when using lxml.html to parse HTML
6,123,351
14
2011-05-25T10:56:44Z
6,396,097
12
2011-06-18T12:46:11Z
[ "python", "parsing", "lxml" ]
I'm working on a script using lxml.html to parse web pages. I have done a fair bit of BeautifulSoup in my time but am now experimenting with lxml due to its speed. I would like to know what the most sensible way in the library is to do the equivalent of Javascript's InnerHtml - that is, to retrieve or set the complete...
Sorry for bringing this up again, but I've been looking for a solution and yours contains a bug: ``` <body>This text is ignored <h1>Title</h1><p>Some text</p></body> ``` Text directly under the root element is ignored. I ended up doing this: ``` (body.text or '') +\ ''.join([html.tostring(child) for child in body.it...
Strange reduce behaviour
6,124,586
10
2011-05-25T12:40:43Z
6,124,639
7
2011-05-25T12:43:49Z
[ "python" ]
When I execute this code in python 2.6 ``` reduce(lambda x,y: x+[y], [1,2,3],[]) ``` I get [1, 2, 3] as expected. But when I execute this one (I think it is equivalent to previous) ``` reduce(lambda x,y: x.append(y), [1,2,3],[]) ``` I get an error message ``` Traceback (most recent call last): File "<stdin>", line...
`reduce` calls the function and uses the return value as the new result. `append` returns `None`, and therefore the next `append` invocation fails. You could write ``` def tmpf(x,y): x.append(y) return x reduce(tmpf, [1,2,3], []) ``` and get the correct result. However, if the result is a list of the same size ...
Strange reduce behaviour
6,124,586
10
2011-05-25T12:40:43Z
6,124,656
12
2011-05-25T12:44:57Z
[ "python" ]
When I execute this code in python 2.6 ``` reduce(lambda x,y: x+[y], [1,2,3],[]) ``` I get [1, 2, 3] as expected. But when I execute this one (I think it is equivalent to previous) ``` reduce(lambda x,y: x.append(y), [1,2,3],[]) ``` I get an error message ``` Traceback (most recent call last): File "<stdin>", line...
`x.append(y)` is not equivalent to `x+[y]`; `append` modifies a list in place and returns nothing, while `x+[y]` is an expression that returns the result.
Python failing to encode bad unicode to ascii
6,124,897
5
2011-05-25T13:03:33Z
6,124,972
10
2011-05-25T13:09:40Z
[ "python", "unicode" ]
I have some Python code that's receiving a string with bad unicode in it. When I try to ignore the bad characters, Python still chokes (version 2.6.1). Here's how to reproduce it: ``` s = 'ad\xc2-ven\xc2-ture' s.encode('utf8', 'ignore') ``` It throws ``` UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in po...
Converting a string to a unicode instance is `str.decode()` in Python 2.x: ``` >>> s.decode("ascii", "ignore") u'ad-ven-ture' ```
Python failing to encode bad unicode to ascii
6,124,897
5
2011-05-25T13:03:33Z
6,124,974
8
2011-05-25T13:09:54Z
[ "python", "unicode" ]
I have some Python code that's receiving a string with bad unicode in it. When I try to ignore the bad characters, Python still chokes (version 2.6.1). Here's how to reproduce it: ``` s = 'ad\xc2-ven\xc2-ture' s.encode('utf8', 'ignore') ``` It throws ``` UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in po...
You are confusing "unicode" and "utf-8". Your string `s` is not unicode; it's a bytestring in a particular encoding (but not UTF-8, more likely iso-8859-1 or such.) Going from a bytestring to `unicode` is done by *decoding* the data, not *encoding*. Going from unicode to bytestring is encoding. Perhaps you meant to mak...
Python: Getting a traceback from a multiprocessing.Process
6,126,007
22
2011-05-25T14:26:09Z
6,127,014
11
2011-05-25T15:30:39Z
[ "python", "exception", "process", "multiprocessing", "traceback" ]
I am trying to get hold of a traceback object from a multiprocessing.Process. Unfortunately passing the exception info through a pipe does not work because traceback objects can not be pickled: ``` def foo(pipe_to_parent): try: raise Exception('xxx') except: pipe_to_parent.send(sys.exc_info()) ...
It seems to be difficult to made picklable the traceback object. But you can only send the 2 first items of `sys.exc_info()`, and a preformated traceback information with the [traceback.extract\_tb](http://docs.python.org/library/traceback.html#traceback.extract_tb) method : ``` import multiprocessing import sys impor...
Python: Getting a traceback from a multiprocessing.Process
6,126,007
22
2011-05-25T14:26:09Z
16,618,842
22
2013-05-17T22:33:34Z
[ "python", "exception", "process", "multiprocessing", "traceback" ]
I am trying to get hold of a traceback object from a multiprocessing.Process. Unfortunately passing the exception info through a pipe does not work because traceback objects can not be pickled: ``` def foo(pipe_to_parent): try: raise Exception('xxx') except: pipe_to_parent.send(sys.exc_info()) ...
Since `multiprocessing` does print the string contents of exceptions raised in child processes, you can wrap all your child process code in a try-except that catches any exceptions, formats the relavent stack traces, and raises a new `Exception` that holds all the relevant information in its string: An example of a fu...
Python: Getting a traceback from a multiprocessing.Process
6,126,007
22
2011-05-25T14:26:09Z
26,096,355
9
2014-09-29T09:13:55Z
[ "python", "exception", "process", "multiprocessing", "traceback" ]
I am trying to get hold of a traceback object from a multiprocessing.Process. Unfortunately passing the exception info through a pipe does not work because traceback objects can not be pickled: ``` def foo(pipe_to_parent): try: raise Exception('xxx') except: pipe_to_parent.send(sys.exc_info()) ...
Using [`tblib`](https://github.com/ionelmc/python-tblib) you can pass wrapped exceptions and reraise them later: ``` import tblib.pickling_support tblib.pickling_support.install() import sys class DelayedException(object): def __init__(self, ee): self.ee = ee __, __, self.tb = sys.exc_info() ...
How to reference the same Model twice from another one?
6,126,045
5
2011-05-25T14:28:48Z
6,126,113
7
2011-05-25T14:33:40Z
[ "python", "google-app-engine", "foreign-keys", "gae-datastore" ]
The following code ``` class Translation(db.Model): origin = db.ReferenceProperty(Expression, required=True) target = db.ReferenceProperty(Expression, required=True) ``` produces the following error: > Traceback (most recent call last): > File "C:\Program Files (x86)\Google\google\_appengine\google\appengine...
``` class Translation(db.Model): origin = db.ReferenceProperty(Expression, required=True, collection_name='translation_origins') target = db.ReferenceProperty(Expression, required=True, collection_name='translation_targets') ```
How to reference the same Model twice from another one?
6,126,045
5
2011-05-25T14:28:48Z
6,126,408
10
2011-05-25T14:52:02Z
[ "python", "google-app-engine", "foreign-keys", "gae-datastore" ]
The following code ``` class Translation(db.Model): origin = db.ReferenceProperty(Expression, required=True) target = db.ReferenceProperty(Expression, required=True) ``` produces the following error: > Traceback (most recent call last): > File "C:\Program Files (x86)\Google\google\_appengine\google\appengine...
Give distinct collection names ``` class Translation(db.Model): origin = db.ReferenceProperty(Expression, required=True,collection_name='origin_translation_set') target = db.ReferenceProperty(Expression, required=True,collection_name='target_translation_set') ``` every db.ReferenceProperty by default creates ...
How do you assign an exception to a local variable in Python 2.5?
6,126,107
7
2011-05-25T14:33:15Z
6,126,136
11
2011-05-25T14:34:47Z
[ "python", "python-2.5" ]
In Python 2.6+, you can handle exceptions like this: ``` try: # stuff except Exception as e: return 'exception %s' % type(e) ``` What is the equivalent in 2.5?
Like this : ``` try: # stuff except Exception, e: return 'exception %s' % type(e) ```
selecting attribute values from lxml
6,126,789
18
2011-05-25T15:16:17Z
6,126,846
24
2011-05-25T15:19:57Z
[ "python", "lxml" ]
I want to use an xpath expression to get the value of an attribute. I expected the following to work ``` from lxml import etree for customer in etree.parse('file.xml').getroot().findall('BOB'): print customer.find('./@NAME') ``` but this gives an error : ``` Traceback (most recent call last): File "bob.py", ...
`find` and `findall` [only implement a subset](http://lxml.de/FAQ.html#xpath-and-document-traversal) of XPath. Their presence is meant to provide compatibility with other ElementTree implementations (like `ElementTree` and `cElementTree`). The `xpath` method, in contrast, provides full access to XPath 1.0: ``` print ...
Match the last number in a string
6,127,771
2
2011-05-25T16:30:57Z
6,127,792
11
2011-05-25T16:32:29Z
[ "python", "regex" ]
I was trying to match the last number in a string, such as "34" in > 3.1 General definitions 34 I am using Python-style regex, and I have tried: ``` (.*?)(\d) ``` so that later I can use \1 to refer "3.1 General definitions " and \2 to refer "34". But \2 matches "4" instead of "34". So how shall I do? Thanks and ...
You're currently only matching a single digit. Try ``` (.*?)(\d+) ``` to match *at least* one digit. This should be all you need, as you've already made the first part of the match reluctant (non-greedy). Depending on how you're performing the match, you *may* need an "end of string" anchor ($) at the end, to make s...
Queryset of people with a birthday in the next X days
6,128,921
2
2011-05-25T18:15:28Z
6,130,259
7
2011-05-25T20:08:35Z
[ "python", "django", "datetime", "django-models", "django-queryset" ]
how do i get queryset of people with a birthday in the next X days? I saw [this](http://stackoverflow.com/questions/5936966/django-total-birthdays-each-day-for-the-next-30-days) answer, but it does not suit me, because gets people only with current year of birth.
Assuming a model like this-- ``` class Person(models.Model): name = models.CharField(max_length=40) birthday = models.DateTimeField() # their next birthday ``` The next step would be to create a query filtering out any records with birthdays having a month and day in between (now.month, now.day) and (then.mon...
Python - Multiple frames with Grid manager
6,129,899
7
2011-05-25T19:37:10Z
6,132,876
7
2011-05-26T01:47:36Z
[ "python", "tkinter" ]
I'm trying to use the functionality from the Tkinter module (Python 2.7) to create a GUI that has eight widgets placed on a 7 row by 5 column grid (sorry that I did not include an image; the dialog box is not allowing me to browse and upload the saved image). (Widget, start\_row, start\_col, row\_span, column\_span): ...
After messing around with my code for a few hours, I was finally able to create the GUI that I intended to. The key was looping over rows and columns and setting their weights using rowconfigure and columnconfigure, respectively. Code is below: ``` from tkinter import * class Application(Frame): def __init__(self...
How can I put an intersphinx link to an arbitrary method in the standard library documentation?
6,129,963
5
2011-05-25T19:42:43Z
6,130,311
7
2011-05-25T20:12:36Z
[ "python", "documentation", "python-sphinx" ]
I am trying to use Sphinx to document a project, but I cannot figure out how to use intersphinx. I use this line: ``` :py:meth:`math.sin` ``` to add the link, but in the output, it shows up bold, not as a link. Although that line does not work, both the following do: ``` :py:meth:`dict.items` :py:class:`zipfile.ZipF...
The `:py:meth:` should be `:py:func:`. Basically, any valid [domain](http://sphinx.pocoo.org/domains.html) can be used.
python modify item in list, save back in list
6,130,211
14
2011-05-25T20:04:40Z
6,130,251
19
2011-05-25T20:08:09Z
[ "python", "list", "for-loop" ]
I have a hunch that I need to access an item in a list (of strings), modify that item (as a string), and put it back in the list in the same index I'm having difficulty getting an item back into the same index ``` for item in list: if "foo" in item: item = replace_all(item, replaceDictionary) list...
You could do this: ``` for idx, item in enumerate(list): if 'foo' in item: item = replace_all(...) list[idx] = item ```
Exact semantics of Matplotlib's "interactive mode" (ion(), ioff())?
6,130,341
14
2011-05-25T20:15:38Z
6,446,392
10
2011-06-22T20:50:33Z
[ "python", "matplotlib", "ion", "interactive-mode" ]
The documentation for the "interactive mode" in Matplotlib's pyplot reads: > The interactive property of the pyplot interface controls whether a figure canvas is drawn on every pyplot command. If interactive is False, then the figure state is updated on every plot command, but will only be drawn on explicit calls to d...
Here is the summary of an [interesting discussion](http://old.nabble.com/Exact-semantics-of-ion%28%29---tp31728909p31775370.html) on this subject in the Matplotlib mailing list. The executive summary is: * The interactive mode (activated with `ion()`) automates many things. In particular, `pyplot.*` commands automatic...
Empty set literal in Python?
6,130,374
190
2011-05-25T20:18:55Z
6,130,391
210
2011-05-25T20:20:24Z
[ "python", "set", "literals" ]
`[]` = empty `list` `()` = empty `tuple` `{}` = empty `dict` Is there a similar notation for an empty `set`? Or do I have to write `set()`?
No, there's no literal syntax for the empty set. You have to write `set()`.
Empty set literal in Python?
6,130,374
190
2011-05-25T20:18:55Z
31,072,911
13
2015-06-26T12:13:11Z
[ "python", "set", "literals" ]
`[]` = empty `list` `()` = empty `tuple` `{}` = empty `dict` Is there a similar notation for an empty `set`? Or do I have to write `set()`?
Just to extend the accepted answer: From version `2.7` and `3.1` python has got `set` literal `{}` in form of usage `{1,2,3}`, but `{}` itself still used for empty dict. Python 2.7 ``` >>> {1,2,3}.__class__ <type 'set'> ``` Python 3.x ``` >>> {1,4,5}.__class__ <class 'set'> ``` More here: <https://docs.python.org...
Return None if Dictionary key is not available
6,130,768
161
2011-05-25T20:49:52Z
6,130,787
18
2011-05-25T20:51:49Z
[ "python" ]
I need a way to get a dictionary value if its key exists, or simply return None, if it does not. However, Python returns a key\_error if you search for a key that does not exist. I know that I can check for the key, but I am looking for something more explicit. Is there a way to just return None if the key does not ex...
Use [`dict.get`](http://docs.python.org/library/stdtypes.html#dict.get)
Return None if Dictionary key is not available
6,130,768
161
2011-05-25T20:49:52Z
6,130,791
10
2011-05-25T20:52:04Z
[ "python" ]
I need a way to get a dictionary value if its key exists, or simply return None, if it does not. However, Python returns a key\_error if you search for a key that does not exist. I know that I can check for the key, but I am looking for something more explicit. Is there a way to just return None if the key does not ex...
You should use the `get()` method from the `dict` class ``` d = {} r = d.get( 'missing_key', None ) ``` This will result in `r == None`. If the key isn't found in the dictionary, the get function returns the second argument.
Return None if Dictionary key is not available
6,130,768
161
2011-05-25T20:49:52Z
6,130,800
273
2011-05-25T20:52:32Z
[ "python" ]
I need a way to get a dictionary value if its key exists, or simply return None, if it does not. However, Python returns a key\_error if you search for a key that does not exist. I know that I can check for the key, but I am looking for something more explicit. Is there a way to just return None if the key does not ex...
You can use [`get()`](http://docs.python.org/library/stdtypes.html#dict.get) ``` value = d.get(key) ``` which will return `None` if `key is not in d`. You can also provide a different default value that will be returned instead of `None`: ``` value = d.get(key, "empty") ```
Return None if Dictionary key is not available
6,130,768
161
2011-05-25T20:49:52Z
6,130,879
7
2011-05-25T21:00:24Z
[ "python" ]
I need a way to get a dictionary value if its key exists, or simply return None, if it does not. However, Python returns a key\_error if you search for a key that does not exist. I know that I can check for the key, but I am looking for something more explicit. Is there a way to just return None if the key does not ex...
If you want a more transparent solution, you can subclass `dict` to get this behavior: ``` class NoneDict(dict): def __getitem__(self, key): return dict.get(self, key) >>> foo = NoneDict([(1,"asdf"), (2,"qwerty")]) >>> foo[1] 'asdf' >>> foo[2] 'qwerty' >>> foo[3] is None True ```
Return None if Dictionary key is not available
6,130,768
161
2011-05-25T20:49:52Z
6,131,279
44
2011-05-25T21:37:08Z
[ "python" ]
I need a way to get a dictionary value if its key exists, or simply return None, if it does not. However, Python returns a key\_error if you search for a key that does not exist. I know that I can check for the key, but I am looking for something more explicit. Is there a way to just return None if the key does not ex...
Wonder no more. It's built into the language. ``` >>> help(dict) Help on class dict in module builtins: class dict(object) | dict() -> new empty dictionary | dict(mapping) -> new dictionary initialized from a mapping object's | (key, value) pairs ... | | get(...) ...
Error Installing Python
6,131,560
3
2011-05-25T22:06:34Z
6,131,627
8
2011-05-25T22:14:37Z
[ "python", "linux", "command-line", "centos" ]
Upon hitting `make install` I get the following error `/usr/bin/install: cannot create regular file /usr/local/bin/python2.6: Permission denied make: *** [altbininstall] Error 1` I am not the root user so I assume its a permissions issue. I do have my own subfolder at `/home/my_username` Is there a way to complete ...
The `configure` script lets you specify `--prefix=[dest]`. From the usage: > By default, `make install' will install all the files in > /usr/local/bin, /usr/local/lib etc. You can specify > an installation prefix other than /usr/local using --prefix, > for instance --prefix=$HOME. So to install under `py26` in your h...
Web sockets / Tornado - Notify client on database update
6,131,915
9
2011-05-25T22:56:24Z
6,139,458
8
2011-05-26T13:41:55Z
[ "python", "tornado", "websocket" ]
I'm trying to use a Tornado web socket server to notify my user when changes are made to a database in realtime. I was hoping to use HTML5 web sockets for this, even though most browsers don't support them. None of the demos that come with the Tornado package use web sockets and they are not mentioned in the documentat...
A Lee's answer is a good one, you probably want socket.io if you need to support older browsers. Websockets are very easy in tornado though: ``` import tornado.websocket class EchoWebSocket(tornado.websocket.WebSocketHandler): def open(self): print "WebSocket opened" def on_message(self, mes...
Create python string with fill char and counter
6,132,048
2
2011-05-25T23:16:39Z
6,132,062
9
2011-05-25T23:19:07Z
[ "python", "string" ]
I'd like to do it in an elegant fashion: ``` >>> ''.zfill(5, '-') '-----' ``` There's any way to initialize a string with a fill char and a counter? Of course, count may vary.
Just try: ``` >>> '-'*5 '-----' ``` It's that simple in Python :)
ImportError: No module named mysql.base, in django project on Ubuntu 11.04 server
6,132,181
5
2011-05-25T23:37:59Z
6,134,620
16
2011-05-26T06:35:09Z
[ "python", "mysql", "django", "mysql-python" ]
I am following the steps in the [Django Book](http://www.djangobook.com/en/2.0/chapter05/) and got to the part where the authors explain hot wo set up a django project to use a database. I chose mysql. My settings in `settings.py` are: ``` DATABASES = { 'default': { 'ENGINE': 'mysql', # Add ...
The correct [database setting](https://docs.djangoproject.com/en/dev/ref/settings/?from=olddocs?from=olddocs#engine) is `'django.db.backends.mysql'`.
Why can't I pickle an error's Traceback in Python?
6,132,469
9
2011-05-26T00:20:11Z
6,132,584
15
2011-05-26T00:44:16Z
[ "python", "pickle", "traceback" ]
I've since found a work around, but still want to know the answer.
The traceback holds references to the stack frames of each function/method that was called on the current thread, from the topmost-frame on down to the point where the error was raised. Each stack frame also holds references to the local and global variables in effect at the time each function in the stack was called. ...
Find the sum of subsets of a list in python
6,133,434
4
2011-05-26T03:44:08Z
6,133,486
8
2011-05-26T03:54:06Z
[ "list", "python", "chunks" ]
This is probably very simple and I'm overlooking something... I have a long list of integers, in this case representing daily visitors to a website. I want a new list of *weekly* visitors. So I need to get groups of seven from the original list, sum them, and add them to a new list. My solution seems pretty brute for...
``` weekly = [ sum(visitors[x:x+7]) for x in range(0, len(daily), 7)] ``` Or slightly less densely: ``` weekly = [] for x in range(0, len(daily), 7): weekly.append( sum(visitors[x:x+7]) ) ``` Alternatively, using the numpy module. ``` by_week = numpy.reshape(visitors, (7, -1)) weekly = numpy.sum( by_week, axis...
Parse config files, environment, and command-line arguments, to get a single collection of options
6,133,517
82
2011-05-26T04:01:25Z
7,789,081
25
2011-10-17T03:29:19Z
[ "python", "environment-variables", "command-line-arguments", "configuration-files" ]
Python's standard library has modules for **configuration file parsing** ([configparser](http://docs.python.org/3/library/configparser.html)), **environment variable reading** ([os.environ](http://docs.python.org/3/library/os.html#os.environ)), and **command-line argument parsing** ([argparse](http://docs.python.org/3/...
The argparse module makes this not nuts, as long as you're happy with a config file that looks like command line. (I think this is an advantage, because users will only have to learn one syntax.) Setting [fromfile\_prefix\_chars](http://docs.python.org/library/argparse.html#fromfile-prefix-chars) to, for example, `@`, ...
Parse config files, environment, and command-line arguments, to get a single collection of options
6,133,517
82
2011-05-26T04:01:25Z
14,743,159
14
2013-02-07T03:44:09Z
[ "python", "environment-variables", "command-line-arguments", "configuration-files" ]
Python's standard library has modules for **configuration file parsing** ([configparser](http://docs.python.org/3/library/configparser.html)), **environment variable reading** ([os.environ](http://docs.python.org/3/library/os.html#os.environ)), and **command-line argument parsing** ([argparse](http://docs.python.org/3/...
Here's a little something that I hacked together. Feel free suggest improvements/bug-reports in the comments: ``` import argparse import ConfigParser import os def _identity(x): return x _SENTINEL = object() class AddConfigFile(argparse.Action): def __call__(self,parser,namespace,values,option_string=None)...
Parse config files, environment, and command-line arguments, to get a single collection of options
6,133,517
82
2011-05-26T04:01:25Z
17,663,858
8
2013-07-15T21:00:48Z
[ "python", "environment-variables", "command-line-arguments", "configuration-files" ]
Python's standard library has modules for **configuration file parsing** ([configparser](http://docs.python.org/3/library/configparser.html)), **environment variable reading** ([os.environ](http://docs.python.org/3/library/os.html#os.environ)), and **command-line argument parsing** ([argparse](http://docs.python.org/3/...
There's library that does exactly this called [configglue](https://pypi.python.org/pypi/configglue/). > configglue is a library that glues together python's > optparse.OptionParser and ConfigParser.ConfigParser, so that you don't > have to repeat yourself when you want to export the same options to a > configuration f...
How can I access a matlab/octave module from python?
6,134,933
22
2011-05-26T07:06:28Z
6,193,922
8
2011-05-31T21:44:32Z
[ "python", "matlab", "octave", "lapack" ]
I am looking for a way to access a matlab module from python. My current situation is this: * I have a python code that does numerical computations by calling Lapack routines while the memory is allocated as `ctypes` and passed as pointers to the Lapack routines. * I also have a matlab module, which is compatible with...
Have you considered using OMPC, <http://ompc.juricap.com/> ? I have used it with great success when not wishing to re-write some numerical linear algebra routines. I can imagine that the more esoteric the Matlab commands, the harder it would be to translate... but it might be worth a try. In the end, you're going to wa...
How can I access a matlab/octave module from python?
6,134,933
22
2011-05-26T07:06:28Z
16,383,880
11
2013-05-05T11:09:45Z
[ "python", "matlab", "octave", "lapack" ]
I am looking for a way to access a matlab module from python. My current situation is this: * I have a python code that does numerical computations by calling Lapack routines while the memory is allocated as `ctypes` and passed as pointers to the Lapack routines. * I also have a matlab module, which is compatible with...
You can use [oct2py](https://pypi.python.org/pypi/oct2py), which IIUC was started by its author because pytave didn't work on win32. It is successfully used in IPython through its [octavemagic extension](http://ipython.org/ipython-doc/dev/config/extensions/octavemagic.html) and I can tell it is easy to use on its own, ...
Rounded division by power of 2
6,135,157
12
2011-05-26T07:30:05Z
6,135,300
9
2011-05-26T07:46:32Z
[ "python", "bit-manipulation", "rounding", "bitwise-operators" ]
I'm implementing a quantization algorithm from a textbook. I'm at a point where things pretty much work, except I get off-by-one errors when rounding. This is what the textbook has to say about that: > Rounded division by `2^p` may be carried out by adding an offset and right-shifting by p bit positions Now, I get th...
The shift will truncate. The shift is a binary operator operating. I'm using square brackets to denote the base here: ``` 196605[10] = 101111111111111111[2] 101111111111111111[2] >> 16[10] = 10[2] = 2[10] ``` To perform correct rounding you need to add half of your divisor before doing the shift. ``` 101111111111111...
Why should CSS and JS not go through Django?
6,135,684
6
2011-05-26T08:27:52Z
6,135,948
11
2011-05-26T08:52:18Z
[ "javascript", "python", "css", "django", "optimization" ]
As per [this answer](http://stackoverflow.com/questions/3968650/can-i-gzip-javascript-and-css-files-in-django/3968792#3968792) to [Can I gzip JavaScript and CSS files in Django?](http://stackoverflow.com/q/3968650/143295): > Your CSS and JS should not be going through Django on your production system. You need to conf...
Apache and Nginx are faster than Django (because they do much less and much simpler things). So serving CSS and JS with Django is a waste of resources. Although "should" is too strong here, IMO. "Should, if you have high traffic", rather.
question for python experts: code doesn't work when called with generators
6,135,750
3
2011-05-26T08:33:06Z
6,135,834
7
2011-05-26T08:41:06Z
[ "python", "generator" ]
I have a small snippet that does not work in an inexplicable way. The purpose is to generate all combinations of two or more sequences. It works when called with lists, but it doesn't when called with generators. ``` def comb(seqs): if seqs: for item in seqs[0]: for rest in comb(seqs[1:]): ...
A generator is exhausted once it has generated everything that it is going generate whereas a list can be iterated through multiple times. Your `comb` generator relies on being able to iterate through the second and later sequences that it is passed multiple times so won't work if these sequences are actually a genera...
How to get a win32 handle of an open file in python?
6,135,805
7
2011-05-26T08:38:06Z
6,135,957
8
2011-05-26T08:53:11Z
[ "python", "winapi" ]
I'm sure this is documented somewhere but i can't find it... My code is getting a python object from another library (that i can't modify), and i need to call some win32 api functions on it. Python returns something that isn't the os-level handle from file.fileno(), my guess is that it gives MSVCRT's fileno. ``` >>>...
I found the answer: ``` >>> msvcrt.get_osfhandle(a.fileno()) 1956 # valid HANDLE ``` This is actually documented on <http://docs.python.org/library/msvcrt.html> , no idea how i missed it.
Image Cropping using Python
6,136,588
3
2011-05-26T09:44:24Z
6,140,013
8
2011-05-26T14:13:32Z
[ "python", "image-processing", "python-imaging-library", "crop" ]
I am new to Python coding and I am writing a program in which I will be cropping an entered image and then saving it in a location. Now, I am being able to do this using a combination of PIL and pygame. But the problem is that, when I am selecting the image from the open pygame window, the selection area is totally opa...
I took a quick look and fixed a few other problems along the way. Essentially my changes do this: * Draw the bounding box on a temporary image, set its alpha transparency, and then blit this over top of the main image. * Avoid extraneous drawing cycles (when the mouse isn't moving, no sense in drawing the same image a...
Python equivalent of Java's getClass().getFields()
6,139,588
5
2011-05-26T13:49:29Z
6,139,668
9
2011-05-26T13:54:09Z
[ "java", "python", "reflection" ]
I'm converting a piece of code from Java to Python and I don't know how to translate the following: ``` Field[] fields = getClass().getFields(); for (int i = 0; i < fields.length; i++ ) { if (fields[i].getName().startsWith((String) param){ .... ```
In Python, you can query an object's bindings with `__dict__`, e.g.: ``` >>> class A: ... def foo(self): return "bar" ... >>> A.__dict__ {'__module__': '__main__', 'foo': <function foo at 0x7ff3d79c>, '__doc__': None} ``` Also, this has been asked from a C# standpoint in: [How to enumerate an object's properties ...
Python data structure for a indexable list of string
6,141,354
9
2011-05-26T15:47:53Z
6,141,999
8
2011-05-26T16:36:08Z
[ "python", "algorithm", "data-structures" ]
I got a list of objects which look like strings, but are not real strings (think about mmap'ed files). Like this: ``` x = [ "abc", "defgh", "ij" ] ``` What i want is `x` to be directly indexable like it was a big string, i.e.: ``` (x[4] == "e") is True ``` (Of course I don't want to do "".join(x) which would merge ...
What you are describing is a special case of the [rope data structure](http://en.wikipedia.org/wiki/Rope_%28computer_science%29). Unfortunately, I am not aware of any Python implementations.
Detect python version in shell script
6,141,581
27
2011-05-26T16:05:04Z
6,141,628
13
2011-05-26T16:08:46Z
[ "python", "shell" ]
I'd like to detect if python is installed on a Linux system and if it is, which python version is installed. How can I do it? Is there something more graceful than parsing the output of `"python --version"`?
``` python -c 'import sys; print sys.version_info' ``` or, human-readable: ``` python -c 'import sys; print(".".join(map(str, sys.version_info[:3])))' ```
Detect python version in shell script
6,141,581
27
2011-05-26T16:05:04Z
6,141,633
29
2011-05-26T16:09:10Z
[ "python", "shell" ]
I'd like to detect if python is installed on a Linux system and if it is, which python version is installed. How can I do it? Is there something more graceful than parsing the output of `"python --version"`?
You could use something along the following lines: ``` $ python -c 'import sys; print(sys.version_info[:])' (2, 6, 5, 'final', 0) ``` The tuple is documented [here](http://docs.python.org/library/sys.html#sys.version_info). You can expand the Python code above to format the version number in a manner that would suit ...
numpy array of python objects
6,141,853
4
2011-05-26T16:24:10Z
6,141,929
7
2011-05-26T16:29:13Z
[ "python", "arrays", "object", "numpy" ]
Since when did numpy allow you to define an array of python objects? [Objects array with numpy](http://stackoverflow.com/questions/2674139/objects-array-with-numpy). Is there any fundamental difference between these arrays and a python list? What is the difference between these arrays and say, a python tuple? There ...
The "fundamental" difference is that a Numpy `array` is fixed-size, while a Python `list` is a [dynamic array](https://secure.wikimedia.org/wikipedia/en/wiki/Dynamic_array). ``` >>> class Foo: ... pass ... >>> x = numpy.array([Foo(), Foo()]) >>> x.append(Foo()) Traceback (most recent call last): File "<stdin>", li...
dynamically add field to a form
6,142,025
32
2011-05-26T16:38:08Z
6,142,749
44
2011-05-26T17:38:25Z
[ "python", "django", "django-forms" ]
I have 3 fields in my form. I have a submit button and a button to "Add additional Field". I understand I can add fields using `__init__` method in the form class. I am new to Python and Django and am stuck with a beginner question: My question is: When I click the "Add additional field" button, what is the process t...
Your form would have to be constructed based on some variables passed to it from your POST (or blindly check for attributes). The form itself is constructed every time the view is reloaded, errors or not, so the HTML needs to contain information about how many fields there are to construct the correct amount of fields ...
BadValueError: Property xxxx is required, even after the xxxx property has already been set? (google app engine)
6,142,439
5
2011-05-26T17:13:55Z
6,142,665
7
2011-05-26T17:30:25Z
[ "python", "google-app-engine", "web-applications" ]
Here's my model: ``` from google.appengine.ext import db from google.appengine.ext.db import polymodel class Item(polymodel.PolyModel): title = db.StringProperty(required=True) summary = db.StringProperty(required=True) content = db.TextProperty(required=True) createDate = db.DateTimeProperty(auto_now...
From [the docs](http://code.google.com/appengine/docs/python/datastore/datamodeling.html): > Because validation occurs when the > instance is constructed, any property > that is configured to be required must > be initialized in the constructor. So: ``` title = "Test title " + str(i) author = "wliao" summary = "this...
Tuple to string with a function to each element
6,142,792
2
2011-05-26T17:41:37Z
6,142,805
8
2011-05-26T17:43:10Z
[ "python" ]
There is a tuple `(a, b, c)`. I need to get `foo(a) + "\n" + foo(b) + "\n" + foo(c)` How it can be done in a smart way, not manually?
You could do it this way (if foo() returns a string): ``` tuple_ = (a,b,c) "\n".join( foo(i) for i in tuple_ ) ``` if foo() doesn't return a string: ``` tuple_ = (a,b,c) "\n".join( str(foo(i)) for i in tuple_ ) ``` **Edit** If writing for python < 2.4 use this since generator expressions were added in Python 2.4: ...