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
In javascript, how would I do this rfind?
6,921,560
2
2011-08-03T04:17:52Z
6,921,597
7
2011-08-03T04:23:45Z
[ "javascript", "python" ]
``` www.mydomain.com/invite/abc123 ``` I want the function to return "abc123". The logic goes like this: ``` If there is a forward slash, then take all characters after the last forward slash. ``` In python, I write it like this: ``` if s.find('/') >= 0: return s[s.rfind('/')+1:] ``` But how do I do this in ja...
You can just say ``` s.substring(s.lastIndexOf("/")) ``` Returns the whole string if `s` has no slashes!
Can I get JSON to load into an OrderedDict in Python?
6,921,699
201
2011-08-03T04:38:14Z
6,921,760
251
2011-08-03T04:48:33Z
[ "python", "json", "load", "ordereddictionary" ]
Ok so I can use an OrderedDict in `json.dump`. That is, an OrderedDict can be used as an input to JSON. But can it be used as an output? If so how? In my case I'd like to `load` into an OrderedDict so I can keep the order of the keys in the file. If not, is there some kind of workaround?
Yes, you can. By specifying the `object_pairs_hook` argument to [JSONDecoder](http://docs.python.org/library/json.html#encoders-and-decoders). In fact, this is the exact example given in the documentation. ``` >>> json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode('{"foo":1, "bar": 2}') OrderedDict([('...
Can I get JSON to load into an OrderedDict in Python?
6,921,699
201
2011-08-03T04:38:14Z
6,921,842
103
2011-08-03T05:00:36Z
[ "python", "json", "load", "ordereddictionary" ]
Ok so I can use an OrderedDict in `json.dump`. That is, an OrderedDict can be used as an input to JSON. But can it be used as an output? If so how? In my case I'd like to `load` into an OrderedDict so I can keep the order of the keys in the file. If not, is there some kind of workaround?
Simple version for Python 2.7+ ``` my_ordered_dict = json.loads(json_str, object_pairs_hook=collections.OrderedDict) ``` Or for Python 2.4 to 2.6 ``` import simplejson as json import ordereddict my_ordered_dict = json.loads(json_str, object_pairs_hook=ordereddict.OrderedDict) ```
How can I pass arguments to Tkinter button's callback command?
6,922,621
7
2011-08-03T06:45:29Z
6,922,740
14
2011-08-03T06:57:57Z
[ "python", "callback", "tkinter", "arguments" ]
I got 2 buttons, respectively named 'ButtonA', 'ButtonB'. I want the program to print 'hello, ButtonA' and 'hello, ButtonB' if any button is clicked. My code is as follows: ``` def sayHi(name): print 'hello,', name root = Tk() btna = Button(root, text = 'ButtonA', command = lambda: text) btna.pack() ``` When I c...
This should work: ``` ... btnaText='ButtonA' btna = Button(root, text = btnaText, command = lambda: sayHi(btnaText)) btna.pack() ``` For more information take a look at [Tkinter Callbacks](http://effbot.org/zone/tkinter-callbacks.htm)
Disable browser 'Back' button after logout?
6,923,027
3
2011-08-03T07:27:35Z
6,935,774
11
2011-08-04T03:09:40Z
[ "javascript", "python", "django", "django-admin" ]
I am using python with django i want redirect users to login page when he clicks back button after logout. How to achieve this? where to write the code? To test whether django admin handles this..i logged into django admin..logged out and then hit back button and i am able to see the previous page. Why django admin do...
Finally found the solution: ``` from django.views.decorators.cache import cache_control @cache_control(no_cache=True, must_revalidate=True) def func() #some code return ``` This will force the browser to make request to server.
Disable browser 'Back' button after logout?
6,923,027
3
2011-08-03T07:27:35Z
9,626,825
9
2012-03-08T23:40:45Z
[ "javascript", "python", "django", "django-admin" ]
I am using python with django i want redirect users to login page when he clicks back button after logout. How to achieve this? where to write the code? To test whether django admin handles this..i logged into django admin..logged out and then hit back button and i am able to see the previous page. Why django admin do...
You may find you need to use @cache\_control(no\_cache=True, must\_revalidate=True, no\_store=True) in chrome to fully stop any back button viewing. The key thing being no\_store for chrome as I found here [1](http://stackoverflow.com/questions/9625046/django-login-required-views-still-show-when-users-are-logged-out-b...
Avoid Circular Model Imports in Django Apps
6,923,042
7
2011-08-03T07:29:19Z
6,923,425
20
2011-08-03T08:09:10Z
[ "python", "django", "organization", "circular-reference", "contenttype" ]
I have a django project with 2 apps like this: ``` ## tags app, models.py class Tag(models.Model): title = models.CharField(max_length=50) ## items app, models.py from application.tags.models import Tag class Item(models.Model): title = models.CharField(max_length=300) tags = models.ManyToManyField(Tag,...
When you define models with foreign keys, you can use the format: ``` tags = models.ManyToManyField('tags.Tag', ...) ``` This means you don't need to have imported the Tag class, just installed the tags app. Then you can store a function in a different location, that might import both Tag and Item, and not have to w...
python base64 string decoding
6,923,159
4
2011-08-03T07:42:38Z
6,923,202
7
2011-08-03T07:45:56Z
[ "python", "encoding", "ucs2" ]
I've got what's supposed to be a UCS-2 encoded xml document that I've managed to build a DOM based on minidom after some tweaking. The issue is that I'm supposed to have some data encoded on base64. I know for a fact that: ``` AME= (or \x00A\x00M\x00E\x00=) is base64 code for Á ``` How would I decode that? <http:/...
Check this out ``` >>> import base64 >>> base64.b64decode('AME=').decode('UTF-16') u'\uc100' >>> base64.b64decode('AME=').decode('UTF-16LE') u'\uc100' >>> base64.b64decode('AME=').decode('UTF-16BE') u'\xc1' ``` Perhaps you are looking for big endian decoding?
Selenium-Python Client Library - Automating in Background
6,924,387
6
2011-08-03T09:32:41Z
6,925,133
8
2011-08-03T10:36:06Z
[ "python", "selenium" ]
I am trying automate a login process to my web application using Selenium-Python Client Library. The ultimate goal is to learn Selenium's Python Client Library. So, I would really appreciate answers from those who are into Selenium-Python. I current have a code like this: ``` from selenium import webdriver from selen...
Firefox (and other graphical browsers) require an X display. You can use a virtual one with the help of [PyVirtualDisplay](http://pypi.python.org/pypi/PyVirtualDisplay): ``` from pyvirtualdisplay import Display display = Display(visible=0, size=(1024, 768)) display.start() browser = webdriver.Firefox() ... more selen...
Error when parsing JSON data
6,924,519
8
2011-08-03T09:45:41Z
10,594,180
10
2012-05-15T04:34:16Z
[ "python", "python-3.x", "google-api", "google-earth" ]
I want to get elevation data from Google Earth according to latitude and longitude, but I am not able to do this. I'm not sure what I'm doing wrong but my code is shown below. ``` def getElevation(locations,sensor="true", **elvtn_args): elvtn_args.update({ 'locations': locations, 'sensor': sensor ...
Post is a little late but recently ran into the same problem. The solution below worked for me. Basically what Lennart said. ``` from urllib import request import json req = request.urlopen('https://someurl.net/api') encoding = req.headers.get_content_charset() obj = json.loads(req.read().decode(encoding)) ```
How to print number with commas as thousands separator and decimal places in Python/Django
6,924,706
3
2011-08-03T10:00:53Z
6,924,762
15
2011-08-03T10:04:59Z
[ "python", "django", "number-formatting" ]
I'm trying to display numbers in my Django templates with 1. commas as thousand sepaerator and 2. specifying the decimal places to round to. e.g. 76384.8739439 -> 76,384.87 Django has template tags to achieve both these. * intcomma - for thousand separator and * floatformat - for decimal places I can't seem to fin...
``` {{ value|floatformat:2|intcomma }} ```
tastypie api not showing ForeignKey in json result
6,925,006
6
2011-08-03T10:23:50Z
7,006,241
7
2011-08-10T05:22:05Z
[ "python", "django", "json", "api" ]
I recently started using tastypie to open up my api for a potential smartphone app. **I'm using python-2.7 and Django-1.1.2** Two things are confusing me 1: in the `EntryResource` class when calling the `ForeignKey`, they just call the resource along with the resource\_name, when I do it in such a way I get the foll...
I'm not sure if I understand your first problem, but about the second one, you'll need to specify you want the full resource using: ``` user = fields.ForeignKey(UserResource, 'user',full=True) ``` otherwise you'll get the resource URI instead of the contents. ([Ref](http://readthedocs.org/docs/django-tastypie/en/late...
How do I import a module from a parent directory? (unittest purposes)
6,925,050
8
2011-08-03T10:27:59Z
6,925,064
11
2011-08-03T10:29:35Z
[ "python", "unit-testing", "import" ]
I have just finished writing the core section of a project I am working on and I want to write test for it using unittest before I continue. I am aware that I should have done this before, but when I started I didn't know Python, so.. whatever.. What I would like to achieve: I have a sub-package of the main package wh...
Run the unit test from the parent directory so the directory is in your PYTHONPATH (the current working directory always is). This is done by executing the test file from your parent directory or by using something like nosetest which recursively looks for all tests in your package. Don't use relative imports, they ca...
Get subdomain from URL using Python
6,925,825
4
2011-08-03T11:37:42Z
6,925,937
14
2011-08-03T11:47:25Z
[ "python", "string", "url" ]
For example, the address is: `Address = http://lol1.domain.com:8888/some/page` I want to save the subdomain into a variable so i could do like so; ``` print SubAddr >> lol1 ```
`urlparse.urlparse` will split the URL into protocol, location, port, etc. You can then split the location by `.` to get the subdomain. ``` url = urlparse.urlparse(address) subdomain = url.hostname.split('.')[0] ```
Get unique items from list of lists?
6,926,928
5
2011-08-03T13:08:21Z
6,926,947
13
2011-08-03T13:10:19Z
[ "python", "duplicates" ]
I have a list of lists that looks like this: ``` animal_groups = [['fox','monkey', 'zebra'], ['snake','elephant', 'donkey'],['beetle', 'mole', 'mouse'],['fox','monkey', 'zebra']] ``` What is the best to remove duplicate lists? Using the above example, I am looking for code that would produce this: ``` uniq_animal_gr...
``` uniq_animal_groups = set(map(tuple, animal_groups)) ``` will do the trick, though you will end up with a set of tuples instead of a set of lists. (Of course you could convert this back to a list of lists, but unless there is a specific reason to do so, why bother?)
Where can i find vtk documentation for python?
6,927,352
11
2011-08-03T13:39:43Z
6,927,582
9
2011-08-03T13:54:27Z
[ "python", "vtk" ]
I am trying to use VTK from python. I tried to find and could not realy find anything on the web which can be used for documentation. I tried looking at the c++ documentation but the methods are very different. Thanks a lot
I recommend you use Mayavi and TVTK from Enthought, the API is much pythonic: <http://code.enthought.com/projects/mayavi/>
Where can i find vtk documentation for python?
6,927,352
11
2011-08-03T13:39:43Z
6,945,196
12
2011-08-04T16:36:48Z
[ "python", "vtk" ]
I am trying to use VTK from python. I tried to find and could not realy find anything on the web which can be used for documentation. I tried looking at the c++ documentation but the methods are very different. Thanks a lot
You could see the python examples at [VTK's wiki](http://www.vtk.org/Wiki/VTK/Examples/Python). There is another resource by going to the [official nightly documentation](http://www.vtk.org/doc/nightly/html/) and looking for a particular class; in the section examples for many (not all) classes you can find implementat...
Detect an invalid keyword argument
6,928,068
4
2011-08-03T14:25:19Z
6,928,116
12
2011-08-03T14:29:09Z
[ "python", "arguments", "keyword" ]
I have the following function: ``` def foo(**kwargs): if not kwargs: # No keyword arguments? It's all right. Set defaults here... elif ('start_index' or 'end_index') in kwargs: # Do something here... else: # Catch unexpected keyword arguments raise TypeError("%r are invalid keyword arguments" % (...
Why do you need `**kwargs` here? Just ``` def foo(start_index=None, end_index=None): ``` and Python will perform all validation for you.
How may I override the compiler (gcc) flags that setup.py uses by default?
6,928,110
31
2011-08-03T14:28:36Z
10,867,041
41
2012-06-03T00:40:30Z
[ "python", "gcc", "setup.py" ]
I understand that setup.py uses the same CFLAGS that were used to build python. I have a single C extension of ours that is segfaulting. I need to build it **without** `-O2` because `-O2` is optimizing out some values and code so that the core files are not sufficient to pin down the problem. I just need to modify set...
* Prepend `CFLAGS="-O0"` before you run `setup.py`: ``` % CFLAGS="-O0" python ./setup.py ``` The `-O0` will be appended to `CFLAGS` while compiling, therefore will override previous `-O2` setting. * Another way is add `-O0` to `extra_compile_args` in `setup.py`: ``` moduleA = Extension('moduleA', ....., ...
Yielding from sorted iterators in sorted order in Python?
6,928,421
7
2011-08-03T14:50:50Z
6,928,478
20
2011-08-03T14:53:42Z
[ "python", "sorting", "iterator" ]
Is there a better way to merge/collate a bunch of sorted iterators into one so that it yields the items in sorted order? I think the code below works but I feel like there is a cleaner, more concise way of doing it that I'm missing. ``` def sortIters(*iterables, **kwargs): key = kwargs.get('key', lambda x : x) ...
yes, you want [`heapq.merge()`](http://docs.python.org/library/heapq.html#heapq.merge) which does exactly one thing; iterate over sorted iterators in order ``` def sortkey(row): return (row[5], row) def unwrap(key): sortkey, row = key return row from itertools import imap FILE_LIST = map(file, ['foo.csv'...
Issue with 'StringVar' in Python Program
6,928,937
5
2011-08-03T15:22:08Z
6,929,219
8
2011-08-03T15:40:48Z
[ "python", "string", "user-interface", "widget", "tkinter" ]
I am trying to write a VERY simple UI in Python using Tkinter. I have run into a small problem with the `StringVar` class. The thing is, when I run the python script, I get an error on the line that initializes the `StringVar` variable. I have written a sample program with this issue that I would like to get working: ...
I think you might need to call Tk() explicitly before invoking StringVar. Just do this: ``` from Tkinter import * Tk() # Add this var = StringVar() var.set('test'); ```
VirtualEnv initilaized from a bash script
6,929,024
7
2011-08-03T15:27:56Z
6,929,125
19
2011-08-03T15:34:18Z
[ "python", "bash", "virtualenv" ]
I am trying to write what should be a super simple bash script. Basically activate a virtual env and than change to the working directory. A task i do a lot and condesing to one command just made sense. Basically ... ``` #!/bin/bash source /usr/local/turbogears/pps_beta/bin/activate cd /usr/local/turbogears/pps_beta/...
All you need to do is to run your script with the source command. This is because the cd command is local to the shell that runs it. When you run a script directly, a new shell is executed which terminates when it reaches the script's end of file. By using the source command you tell the shell to directly execute the s...
Python xlwt - accessing existing cell content, auto-adjust column width
6,929,115
20
2011-08-03T15:33:39Z
9,137,934
36
2012-02-04T02:30:13Z
[ "python", "xlwt", "xlrd" ]
I am trying to create an Excel workbook where I can auto-set, or auto-adjust the widths of the columns before saving the workbook. I have been reading the Python-Excel tutorial in hopes of finding some functions in xlwt that emulate xlrd ones (such as `sheet_names()`, `cellname(row, col)`, `cell_type`, `cell_value`, a...
I just implemented a wrapper class that tracks the widths of items as you enter them. It seems to work pretty well. ``` import arial10 class FitSheetWrapper(object): """Try to fit columns to max size of any entry. To use, wrap this around a worksheet returned from the workbook's add_sheet method, like fo...
TypeError: 'float' object is not callable
6,929,777
5
2011-08-03T16:21:22Z
6,929,801
15
2011-08-03T16:23:30Z
[ "python", "math", "types" ]
I am trying to use values from an array in the following equation: ``` for x in range(len(prof)): PB = 2.25 * (1 - math.pow(math.e, (-3.7(prof[x])/2.25))) * (math.e, (0/2.25))) ``` When I run I receive the following error: ``` Traceback (most recent call last): File "C:/Users/cwpapine/Desktop/1mPro_Chlavg", li...
There is an operator missing, likely a `*`: ``` -3.7 need_something_here (prof[x]) ``` The "is *not callable*" occurs because the parenthesis -- and lack of operator which would have switched the parenthesis into precedence operators -- make Python try to *call* the result of `-3.7` (a float) as a function, which is ...
Regex to join numbers when they have spaces between them
6,929,981
3
2011-08-03T16:38:56Z
6,930,051
10
2011-08-03T16:43:40Z
[ "php", "python", "regex", "replace", "preg-replace" ]
I'm trying to build a regex that joins numbers in a string when they have spaces between them, ex: ``` $string = "I want to go home 8890 7463 and then go to 58639 6312 the cinema" ``` The regex should output: ``` "I want to go home 88907463 and then go to 586396312 the cinema" ``` The regex can be either in python ...
Use a look-ahead to see if the next block is a set of numbers and remove the trailing space. That way, it works for any number of sets (which I suspected you might want): ``` $string = "I want to go home 8890 7463 41234 and then go to 58639 6312 the cinema"; $newstring = preg_replace("/\b(\d+)\s+(?=\d+\b)/", "$1", $s...
How to use a variable inside a regular expression?
6,930,982
57
2011-08-03T17:59:41Z
6,931,046
12
2011-08-03T18:04:32Z
[ "python", "regex", "variables", "python-3.x" ]
I'd like to use a `variable` inside a `regex`, how can I achieve this in Python? ``` TEXTO = sys.argv[1] if re.search(r"\b(?=\w)TEXTO\b(?!\w)", subject, re.IGNORECASE): # Successful match else: # Match attempt failed ```
``` rx = r'\b(?=\w){0}\b(?!\w)'.format(TEXTO) ```
How to use a variable inside a regular expression?
6,930,982
57
2011-08-03T17:59:41Z
6,931,048
18
2011-08-03T18:04:36Z
[ "python", "regex", "variables", "python-3.x" ]
I'd like to use a `variable` inside a `regex`, how can I achieve this in Python? ``` TEXTO = sys.argv[1] if re.search(r"\b(?=\w)TEXTO\b(?!\w)", subject, re.IGNORECASE): # Successful match else: # Match attempt failed ```
``` if re.search(r"\b(?=\w)%s\b(?!\w)" % TEXTO, subject, re.IGNORECASE): ``` This will insert what is in TEXTO into the regex as a string.
How to use a variable inside a regular expression?
6,930,982
57
2011-08-03T17:59:41Z
6,931,070
85
2011-08-03T18:05:54Z
[ "python", "regex", "variables", "python-3.x" ]
I'd like to use a `variable` inside a `regex`, how can I achieve this in Python? ``` TEXTO = sys.argv[1] if re.search(r"\b(?=\w)TEXTO\b(?!\w)", subject, re.IGNORECASE): # Successful match else: # Match attempt failed ```
You have to build the regex as a string: ``` TEXTO = sys.argv[1] my_regex = r"\b(?=\w)" + re.escape(TEXTO) + r"\b(?!\w)" if re.search(my_regex, subject, re.IGNORECASE): etc. ``` Note the use of `re.escape` so that if your text has special characters, they won't be interpreted as such.
Difference between scipy.spatial.KDTree and scipy.spatial.cKDTree
6,931,209
17
2011-08-03T18:16:28Z
6,931,317
18
2011-08-03T18:24:54Z
[ "python", "scipy", "kdtree" ]
What is the difference between these two algorithms?
[cKDTree](http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.cKDTree.html#scipy.spatial.cKDTree) is a subset of [KDTree](http://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.KDTree.html#scipy.spatial.KDTree), presumably implemented in C, so therefore faster. Each of them is > a binary trie...
Difference between scipy.spatial.KDTree and scipy.spatial.cKDTree
6,931,209
17
2011-08-03T18:16:28Z
15,331,547
7
2013-03-11T05:08:05Z
[ "python", "scipy", "kdtree" ]
What is the difference between these two algorithms?
In a use case (5D nearest neighbor look ups in a KDTree with approximately 100K points) cKDTree is around 12x faster than KDTree.
System-wide mutex in Python on Linux
6,931,342
27
2011-08-03T18:27:21Z
6,931,784
12
2011-08-03T19:00:04Z
[ "python", "linux", "mutex" ]
Is there any easy way to have a system-wide mutex in Python on Linux? By "system-wide", I mean the mutex will be used by a group of Python *processes*; this is in contrast to a traditional mutex, which is used by a group of *threads* within the same process. EDIT: I'm not sure Python's multiprocessing package is what ...
The POSIX standard specifies inter-process semaphores which can be used for this purpose. <http://linux.die.net/man/7/sem_overview> The `multiprocessing` module in Python is built on this API and others. In particular, `multiprocessing.Lock` provides a cross-process "mutex". <http://docs.python.org/library/multiproces...
System-wide mutex in Python on Linux
6,931,342
27
2011-08-03T18:27:21Z
9,464,945
13
2012-02-27T12:21:52Z
[ "python", "linux", "mutex" ]
Is there any easy way to have a system-wide mutex in Python on Linux? By "system-wide", I mean the mutex will be used by a group of Python *processes*; this is in contrast to a traditional mutex, which is used by a group of *threads* within the same process. EDIT: I'm not sure Python's multiprocessing package is what ...
The "traditional" Unix answer is to use file locks. You can use `lockf(3)` to lock sections of a file so that other processes can't edit it; a very common abuse is to use this as a mutex between processes. The python equivalent is [fcntl.lockf](https://docs.python.org/3/library/fcntl.html#fcntl.lockf). Traditionally y...
How can a non-assigned string in Python have an address in memory?
6,931,880
43
2011-08-03T19:07:20Z
6,931,932
47
2011-08-03T19:11:18Z
[ "python", "memory-address" ]
Can someone explain this to me? So I've been playing with the id() command in python and came across this: ``` >>> id('cat') 5181152 >>> a = 'cat' >>> b = 'cat' >>> id(a) 5181152 >>> id(b) 5181152 ``` This makes some sense to me except for one part: The string 'cat' has an address in memory before I assign it to a va...
`'cat'` has an address because you create it in order to pass it to `id()`. You haven't yet bound it to a name, but the object still exists. **Python** caches and reuses short strings. But if you assemble strings by concatenation, then the code that searches the cache and attempts re-use is bypassed. Note that the in...
How can a non-assigned string in Python have an address in memory?
6,931,880
43
2011-08-03T19:07:20Z
6,931,950
17
2011-08-03T19:13:09Z
[ "python", "memory-address" ]
Can someone explain this to me? So I've been playing with the id() command in python and came across this: ``` >>> id('cat') 5181152 >>> a = 'cat' >>> b = 'cat' >>> id(a) 5181152 >>> id(b) 5181152 ``` This makes some sense to me except for one part: The string 'cat' has an address in memory before I assign it to a va...
All values must reside somewhere in memory. This is why `id('cat')` produces a value. You call it a "non-existent" string, but it clearly does exist, it just hasn't been assigned to a name yet. Strings are immutable, so the interpreter can do clever things like make all instances of the literal `'cat'` be the same obj...
How can a non-assigned string in Python have an address in memory?
6,931,880
43
2011-08-03T19:07:20Z
6,932,143
48
2011-08-03T19:29:32Z
[ "python", "memory-address" ]
Can someone explain this to me? So I've been playing with the id() command in python and came across this: ``` >>> id('cat') 5181152 >>> a = 'cat' >>> b = 'cat' >>> id(a) 5181152 >>> id(b) 5181152 ``` This makes some sense to me except for one part: The string 'cat' has an address in memory before I assign it to a va...
Python *interns* all string literals, which means it stores them in a big table of string literals and reuses them wherever they occur. So, no matter where you use `"cat"`, it always refers to the same string object. This is done at "compile" time (that is, when the bytecode is generated -- Python is only half-compiled...
How can a non-assigned string in Python have an address in memory?
6,931,880
43
2011-08-03T19:07:20Z
6,932,278
8
2011-08-03T19:39:50Z
[ "python", "memory-address" ]
Can someone explain this to me? So I've been playing with the id() command in python and came across this: ``` >>> id('cat') 5181152 >>> a = 'cat' >>> b = 'cat' >>> id(a) 5181152 >>> id(b) 5181152 ``` This makes some sense to me except for one part: The string 'cat' has an address in memory before I assign it to a va...
Python variables are rather unlike variables in other languages (say, C). In many other languages, a variable is a name for a location in memory. In these languages, Different kinds of variables can refer to different kinds of locations, and the same location could be given multiple names. For the most part, a given m...
How to remotely update Python applications
6,932,389
10
2011-08-03T19:50:13Z
6,935,222
8
2011-08-04T01:38:21Z
[ "python", "packaging", "remote-access", "downloading", "software-update" ]
What is the best method to push changes to a program written in Python? I have a piece of software that is written in Python that will regularly be updated. What would be the best way to do this? All the machines will have Windows 7. Also, excuse the ambiguity of my question. This will be my first time having to imple...
If you're not already packaging your program with [InnoSetup](http://www.jrsoftware.org/isinfo.php), I strongly recommend you switch to it, because it has facilities to make this sort of thing easier. You can specify any special situations, such as files that should not be updated if they already exist (i.e. if you hav...
Django Boolean Queryset Filter Not Working
6,933,196
8
2011-08-03T20:57:02Z
7,547,935
16
2011-09-25T19:17:40Z
[ "python", "django", "django-models", "sqlite3", "django-queryset" ]
This has been frustrating me for the better part of an hour. I have the following model: ``` sold= models.BooleanField(default=False) ``` And the following view code: ``` properties = Property.objects.filter(sold=False).order_by('-created_on'); ``` And the following values in my sqlite3 database: ``` sqlite> sel...
This has happened to me as well. Turned out in SQLite you can have Boolean with value 0 and Boolean with value False So Django does not work wiht the ones set to False I saw this discrepancy in sqliteman Simple update fixed the problem. I think this happened during schema upgrades and migration in my dev environme...
Virtualenvwrapper errors on Mac OS X Lion
6,933,535
8
2011-08-03T21:28:50Z
6,933,819
13
2011-08-03T21:58:32Z
[ "python", "osx", "osx-lion", "virtualenv", "virtualenvwrapper" ]
I have just update my Mac from Snow Leopard to Lion. I then needed to install `virtualenv` and `virtualenvwrapper`. I used for both `easy_install`. I also added virtualenvwrapper settings to my .bash\_profile file as following: ``` # virtualenvwrapper settings export WORKON_HOME="~/virtualenvs" source "/usr/local/bin/...
Since `/Library/Frameworks/Python.framework/Versions/2.7/bin/python` is the path to a separately-installed Python 2.7 (possibly from a python.org installer) rather than the Apple-supplied Python 2.7 (`/usr/bin/python2.7`), you need to make sure you are using an `easy_install` for that separate Python or change to using...
Interoperating with Django/Celery From Java
6,933,833
12
2011-08-03T22:00:31Z
6,950,818
12
2011-08-05T02:36:49Z
[ "java", "python", "django", "rabbitmq", "celery" ]
Our company has a Python based web site and some Python based worker nodes which communicate via Django/Celery and RabbitMQ. I have a Java based application which needs to submit tasks to the Celery based workers. I can send jobs to RabbitMQ from Java just fine, but the Celery based workers are never picking up the job...
I found the solution. The Java library for RabbitMQ refers to exchanges/queues/routekeys. In Celery, the queue name is actually mapping to the exchange referred to in the Java library. By default, the queue for Celery is simply "celery". If your Django settings define a queue called "myqueue" using the following syntax...
Tool to convert regex between different language syntaxes?
6,933,891
16
2011-08-03T22:07:11Z
6,933,978
7
2011-08-03T22:16:30Z
[ "java", "python", "regex", "perl" ]
Is there a tool to convert a regex from one popular language's syntax to another? For example a Python-style regex to a Java-style regex?. Or at least, has someone put together a set of rules to do these conversions? And obviously some constructs won't be able to convert.
Go to [this article](http://stackoverflow.com/questions/4644847/list-of-all-regex-implementations), and follow the link to "Regex info's comparison of Regex flavors", that got me to a tool called [RegexBuddy](http://www.regexbuddy.com/), which sounds like it might do what you want.
Python intern for non-strings
6,934,202
7
2011-08-03T22:44:43Z
6,936,919
13
2011-08-04T06:12:18Z
[ "python", "language-features" ]
Why is Python's `intern` built-in only for strings? It should be possible to extend `intern` to classes that are hashable and comparable, right?
The purpose of interning things is to be able to compare them by comparing their memory address; you ensure that you never create two objects with the same value (when the program requests the creation of a second object with the same value as an existing object, it instead receives a reference to the pre-existing obje...
How do I tell if the returned cursor is the last cursor in App Engine
6,934,681
10
2011-08-03T23:52:40Z
6,937,123
18
2011-08-04T06:34:46Z
[ "python", "google-app-engine", "cursor" ]
I apologize if I am missing something really obvious. I'm making successive calls to app engine using cursors. How do I tell if the I'm on the last cursor? The current way I'm doing it now is to save the last cursor and then testing to see if that cursor equals the currently returned cursor. This requires an extra cal...
I don't think there's a way to do this with ext.db in a single datastore call, but with [ndb](http://code.google.com/p/appengine-ndb-experiment/) it is possible. Example: ``` query = Person.query(Person.name == 'Guido') result, cursor, more = query.fetch_page(10) ``` If using the returned cursor will result in more r...
Python subprocess.call and subprocess.Popen giving me different outputs
6,934,696
4
2011-08-03T23:55:28Z
6,934,722
10
2011-08-03T23:59:38Z
[ "python", "subprocess" ]
When using subprocess.call, the output is what is expected. ``` result = subprocess.call([securefx, '/NoPrompt', '/Q', '/RetryCount', retries, '/RetryDelay', '1', '/Log', sfxLogFile, '/List', '/S', session]) ``` Printing the result will output something like -533428 or 0 But when I run ``` args = [se...
`subprocess.Popen` returns a [Popen object](http://docs.python.org/library/subprocess.html#popen-objects), which you can use to communicate with the process and get output, however `subprocess.call` will only return the return code of the process: ``` subprocess.call(*popenargs, **kwargs) Run command with arguments....
Is list comprehension appropriate here?
6,935,068
5
2011-08-04T01:01:42Z
6,935,265
7
2011-08-04T01:47:05Z
[ "python", "list", "list-comprehension", "duplicates" ]
I have to append elements to a list only if the current iterated element is not already in the list. ``` >>> l = [1, 2] >>> for x in (2, 3, 4): ... if x not in l: ... l.append(x) ... >>> l [1, 2, 3, 4] ``` vs ``` >>> l = [1, 2] >>> [l.append(i) for i in (2, 3, 4) if i not in l] [None, None] >>> l [1...
This algorithm, either with or without a list comprehension, is not as efficient as possible; `list.__contains__` is O(n), and so adding the elements of another list to it is O(n2). On the other hand, `set.__contains__` is O(log n), so the *best* way to do this is to use a set to check for membership, and a list to pre...
How to use joinedload/contains_eager for query-enabled relationships (lazy='dynamic' option) in SQLAlchemy
6,935,809
5
2011-08-04T03:16:06Z
6,935,872
14
2011-08-04T03:30:26Z
[ "python", "sqlalchemy" ]
I have the following model classes declared by SQLAlchemy: ``` class User(Base): id = Column(Integer, primary_key=True) name = Column(String, nullable=False, unique=True) created_at = Colmn(DateTime, nullable=False, default=func.now()) class Post(Base): id = Column(Integer, primary_key=True) user_...
The problem is that the property on `User` for posts is a dynamic relationship; It's supposed to return a `Query` object. There's no way for the property to know, or safely communicate, that this time, all of the related items are already loaded. The simple workaround will be to have two properties, one that uses the ...
How to install MatPlotLib on Mac 10.7 in virtualenv
6,936,884
14
2011-08-04T06:08:30Z
6,949,576
8
2011-08-04T22:54:14Z
[ "python", "install", "matplotlib", "virtualenv" ]
Here what I try to do: ``` (SAASSenv)miki725mac:SAASSenv miki725$ python Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> exit() (SAASSenv)miki725mac:SAASSenv miki725$ (SAASSenv)m...
just do pip install -e <https://github.com/matplotlib/matplotlib.git> matplotlib or clone and then install or have a look @ <http://jholewinski.org/blog/installing-matplotlib-on-os-x-10-7-with-homebrew/> but it s not a lion problem just a python 2.7.2 bug. had the same problem on a colleagues snow leopard machine ...
How to install MatPlotLib on Mac 10.7 in virtualenv
6,936,884
14
2011-08-04T06:08:30Z
7,508,096
25
2011-09-22T00:02:33Z
[ "python", "install", "matplotlib", "virtualenv" ]
Here what I try to do: ``` (SAASSenv)miki725mac:SAASSenv miki725$ python Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> exit() (SAASSenv)miki725mac:SAASSenv miki725$ (SAASSenv)m...
locojays line didn't work for me (osx 10.7, Python 2.7.2 via homebrew), I had to modify the command as follows: ``` pip install -e git+https://github.com/matplotlib/matplotlib.git#egg=matplotlib ```
Why is collections.deque slower than collections.defaultdict?
6,937,893
2
2011-08-04T07:48:53Z
6,938,182
10
2011-08-04T08:16:47Z
[ "python", "performance", "spell-checking", "deque", "defaultdict" ]
Forgive me for asking in in such a general way as I'm sure their performance is depending on how one uses them, but in my case `collections.deque` was way slower than `collections.defaultdict` when I wanted to verify the existence of a value. I used the [spelling correction from Peter Norvig](http://norvig.com/spell-c...
These three data structures aren't interchangeable, they serve very different purposes and have very different characteristics: * Lists are dynamic arrays, you use them to store items sequentially for fast random access, use as stack (adding and removing at the end) or just storing something and later iterating over i...
Why the hashlib and hmac are generating different hash values?
6,938,675
8
2011-08-04T09:01:10Z
6,939,124
18
2011-08-04T09:36:31Z
[ "python", "hmac", "hashlib" ]
In Python 2.7, ``` my = "my" key = "key" print(hashlib.sha256(my + key).hexdigest()) print(hmac.new(my, key, hashlib.sha256).hexdigest()) ``` output, ``` 5e50f405ace6cbdf17379f4b9f2b0c9f4144c5e380ea0b9298cb02ebd8ffe511 15a55993a27e0de7a4c4daa67a7c219199a464ca283797f545b783cce07b38a5 ``` or have I misunderstood?
This is because `hmac` uses the provided `key` to generate a [salt](http://en.wikipedia.org/wiki/Salt_%28cryptography%29) and make the hash more strong, while `hashlib` only hashes the provided message. By looking at the `hmac` module [source code](http://hg.python.org/cpython/file/65c412586901/Lib/hmac.py), you will ...
UnicodeEncodeError when writing to a file
6,939,692
11
2011-08-04T10:20:45Z
6,939,744
11
2011-08-04T10:24:45Z
[ "python", "unicode", "beautifulsoup" ]
I am trying to write some strings to a file (the strings have been given to me by the HTML parser BeautifulSoup). I can use "print" to display them, but when I use file.write() I get the following error: ``` UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 6: ordinal not in range(128) ``` ...
This error occurs when you pass a Unicode string containing non-English characters (Unicode characters beyond 128) to something that expects an ASCII bytestring. The default encoding for a Python bytestring is ASCII, "which handles exactly 128 (English) characters". This is why trying to convert Unicode characters beyo...
UnicodeEncodeError when writing to a file
6,939,692
11
2011-08-04T10:20:45Z
6,939,797
15
2011-08-04T10:28:19Z
[ "python", "unicode", "beautifulsoup" ]
I am trying to write some strings to a file (the strings have been given to me by the HTML parser BeautifulSoup). I can use "print" to display them, but when I use file.write() I get the following error: ``` UnicodeEncodeError: 'ascii' codec can't encode character u'\xa3' in position 6: ordinal not in range(128) ``` ...
Yes, approximately 99.9% of veteran Python users have seen it before. If I type 'python unicode' into Google, I get about 14 million results; the first is <http://docs.python.org/howto/unicode.html> the official doc which describes the whole situation in excruciating detail; and the fourth is <http://farmdev.com/talks...
Use Python standard logging in Celery
6,940,987
16
2011-08-04T11:55:41Z
6,942,030
16
2011-08-04T13:12:29Z
[ "python", "django", "logging", "standards", "celery" ]
I have to implement Celery in a pre-existing system. The previous version of the system already used Python standard logging. My code is similar to the code below. Process one and process two are non-Celery functions, which are logging everywhere. We are using the logging to track data loss if something bad happens. ...
You probably want this setting: ``` CELERYD_HIJACK_ROOT_LOGGER = False ``` Tell me how that works out. Btw, the reason it hijacks the root logger is because some badly written libraries sets up logging, something a library should never do, resulting in users experiencing no output from the celeryd worker :(
Send Email to multiple recipients from .txt file with Python smtplib
6,941,811
5
2011-08-04T12:57:35Z
8,071,309
32
2011-11-09T20:36:50Z
[ "python", "email" ]
I try to send mails from python to multiple email-addresses, imported from a .txt file, I've tried differend syntaxes, but nothing would work... The code: ``` s.sendmail('sender@mail.com', ['recipient@mail.com', 'recipient2@mail.com', 'recipient3@mail.com'], msg.as_string()) ``` So I tried this to import the recipie...
This question has sort of been answered, but not fully. The issue for me is that "To:" header wants the emails as a string, and the sendmail function wants it in a list structure. ``` # list of emails emails = ["banjer@example.com", "slingblade@example.com", "dude@example.com"] # Use a string for the To: header msg['...
Check string for numbers in Python
6,941,866
4
2011-08-04T13:00:39Z
6,941,880
9
2011-08-04T13:01:57Z
[ "python", "string", "numbers" ]
How to check if string contains numbers in Python? I have a variable which I am convert to float, but I want to make if statement, to convert it to float only if it contains only numbers.
Just convert it and catch the exception if it fails. ``` s = "3.14" try: val = float(s) except ValueError: val = None ```
Convert a date string into YYYYMMDD
6,941,965
7
2011-08-04T13:07:49Z
6,942,141
9
2011-08-04T13:18:23Z
[ "python" ]
I've got a bunch of date strings in this form: - ``` 30th November 2009 31st March 2010 30th September 2010 ``` I want them like this: - ``` YYYYMMDD ``` Currently I'm doing this: - ``` parsed_date = "30th November 2009" part = parsed_date.split(' ') daymonth = part[0].strip(string.ascii_letters) mytime = ...
Try [**dateutil**](http://labix.org/python-dateutil): ``` from dateutil import parser dates = ['30th November 2009', '31st March 2010', '30th September 2010'] for date in dates: print parser.parse(date).strftime('%Y%m%d') ``` output: ``` 20091130 20100331 20100930 ``` or if you want to do it using standard `d...
What's the Pythonic way to store a data block in a Python script?
6,942,843
10
2011-08-04T14:04:32Z
6,942,906
8
2011-08-04T14:07:51Z
[ "python" ]
Perl allows me to use the `__DATA__` token in a script to mark the start of a data block. I can read the data using the DATA filehandle. What's the Pythonic way to store a data block in a script?
It depends on your data, but dict literals and multi-line strings are both really good ways. ``` state_abbr = { 'MA': 'Massachusetts', 'MI': 'Michigan', 'MS': 'Mississippi', 'MN': 'Minnesota', 'MO': 'Missouri', } gettysburg = """ Four score and seven years ago, our fathers brought forth on thi...
Has threading in GTK w/ Python changed in PyGObject introspection?
6,943,098
25
2011-08-04T14:20:46Z
6,949,522
25
2011-08-04T22:46:14Z
[ "python", "multithreading", "gtk", "pygtk", "pygobject" ]
I'm in the process of converting a program from PyGTK to PyGObject introspection for the first time and I've hit a roadblock with threading. I have a process that takes some time to complete, so I pop up a dialog with a progress bar on it and I use a thread to do the process and to update the progress bar. This worked ...
I managed to answer my own question by poking through some Gnome programs written in Python (Gnome Sudoku, in this case, which actually has helped me a couple of times). The trick is that you have to call `GObject.threads_init()` at the beginning of your code, not `GLib.thread_init()` as the C documentation implies.
Python - get name of current class
6,943,182
35
2011-08-04T14:25:23Z
6,943,223
12
2011-08-04T14:28:01Z
[ "python", "class" ]
How do I get the name of the class I am currently in? Example: ``` def get_input(class_name): [do things] return class_name_result class foo(): input = get_input([class name goes here]) ``` Due to the nature of the program I am interfacing with (vistrails), I cannot use **init** to initialize input.
Within the body of a class, the class name isn't defined yet, so it is not available. Can you not simply type the name of the class? Maybe you need to say more about the problem so we can find a solution for you. I would create a metaclass to do this work for you. It's invoked at class creation time (conceptually at t...
Python - get name of current class
6,943,182
35
2011-08-04T14:25:23Z
6,943,240
7
2011-08-04T14:29:15Z
[ "python", "class" ]
How do I get the name of the class I am currently in? Example: ``` def get_input(class_name): [do things] return class_name_result class foo(): input = get_input([class name goes here]) ``` Due to the nature of the program I am interfacing with (vistrails), I cannot use **init** to initialize input.
You can access it by the class' private attributes: ``` cls_name = self.__class__.__name__ ``` **EDIT:** As said by `Ned Batcheler`, this wouldn't work in the class body, but it would in a method.
Python - get name of current class
6,943,182
35
2011-08-04T14:25:23Z
6,943,307
51
2011-08-04T14:32:46Z
[ "python", "class" ]
How do I get the name of the class I am currently in? Example: ``` def get_input(class_name): [do things] return class_name_result class foo(): input = get_input([class name goes here]) ``` Due to the nature of the program I am interfacing with (vistrails), I cannot use **init** to initialize input.
`obj.__class__.__name__` will get you any objects name, so you can do this: ``` class Clazz(): def getName(self): return self.__class__.__name__ ``` Usage: ``` >>> c = Clazz() >>> c.getName() 'Clazz' ```
Activate a virtualenv with a python script
6,943,208
40
2011-08-04T14:27:27Z
6,944,649
11
2011-08-04T15:57:56Z
[ "python", "virtualenv" ]
I want to activate a virtualenv instance from a python script. I know it's quite easy to do, but all the examples I've seen use it to run commands within the env and then close the subprocess. What I want is simply activate the virtualenv and return to the shell, the same way that bin/activate does. Something like t...
Turns out that yes the problem is not simple but the solution is. First I had to create a shell script to wrap the "source" command. That said I used the "." instead because I've read that it's better to use it than source for bash scripts. ``` #!/bin/bash . /path/to/env/bin/activate ``` Then from my python script I...
Activate a virtualenv with a python script
6,943,208
40
2011-08-04T14:27:27Z
14,792,407
41
2013-02-09T22:38:06Z
[ "python", "virtualenv" ]
I want to activate a virtualenv instance from a python script. I know it's quite easy to do, but all the examples I've seen use it to run commands within the env and then close the subprocess. What I want is simply activate the virtualenv and return to the shell, the same way that bin/activate does. Something like t...
If you want to run a Python subprocess under the virtualenv, you can do that by running the script using the python interpreter that lives inside virtualenv's /bin/ directory: ``` # path to a python interpreter that runs any python script # under the virtualenv /path/to/virtualenv/ python_bin = "/path/to/virtualenv/bi...
Using a global flag for python RegExp compile
6,943,912
4
2011-08-04T15:11:40Z
6,944,352
9
2011-08-04T15:38:03Z
[ "python", "regex" ]
Would it be possible to define a global flag so that Python's `re.compile()` automatically sets it ? For instance I want to use `re.DOTALL` flag for all my RegExp in -- say -- a class? It may sound weird at first, but I'm not really in control of this part of the code since it's generated by YAPPS. I just give YAPPS a...
Yes, you can change it to be globally `re.DOTALL`. But you *shouldn't*. Global settings are a bad idea at the best of times -- this could cause any Python code run by the same instance of Python to break. --- So, **don't do this**: The way you can change it is to use the fact that the Python interpreter caches modul...
Localized date strftime in Django view
6,945,251
28
2011-08-04T16:41:23Z
6,991,918
57
2011-08-09T05:53:04Z
[ "python", "django", "localization" ]
I would like to send localized date in JSON from django view Normal text translation via > ugettext is OK Following code in view has no effect: ``` translation.activate("ru") print datetime.now().strtime("%B") ``` Output is **"August"**, instead of "**Август**" I read about python's "locale" module, but it...
Finally i used date filter from django templates: ``` from django.template.defaultfilters import date as _date from datetime import datetime _date(datetime.now(), "d b, D") ```
Using python to run another program?
6,945,466
7
2011-08-04T16:57:37Z
6,945,501
13
2011-08-04T17:00:29Z
[ "python", "python-3.x", "subprocess" ]
I have a program that I run from the command line that looks like this: `$ program a.txt b.txt` The program requires two text files as arguments. I am trying to write a Python 3.2 script to run the above program. How can I do this? Currently, I am trying to use the `subprocess` module like this: ``` import subproces...
`subprocess.Popen` expects an array of strings. Two of the items in that array are file handles. You need to pass the actual file *name* to the program you're trying to run. ``` cmd = ['/Users/me/src/program', 'a.txt', 'b.txt'] ``` You can get rid of the `with open(...) as ...` lines completely.
Using python to run another program?
6,945,466
7
2011-08-04T16:57:37Z
6,945,516
11
2011-08-04T17:01:23Z
[ "python", "python-3.x", "subprocess" ]
I have a program that I run from the command line that looks like this: `$ program a.txt b.txt` The program requires two text files as arguments. I am trying to write a Python 3.2 script to run the above program. How can I do this? Currently, I am trying to use the `subprocess` module like this: ``` import subproces...
Look at [@Chris's answer](http://stackoverflow.com/questions/6945466/using-python-to-run-another-program/6945501#6945501), and also: Subprocess doesn't wait for command to finish, so you should use `wait` method. ``` process = subprocess.Popen(cmd, stdout=subprocess.PIPE) process.wait() for line in proces...
how to reload a Class in python shell?
6,946,376
24
2011-08-04T18:08:10Z
6,946,467
23
2011-08-04T18:13:18Z
[ "python", "ipython", "biopython" ]
If I import a module defining a class of the same name belonging to a package, it is imported as a Class, not a Module because of the \_\_init\_\_.py of the parent package. See [different import results at different directories](http://stackoverflow.com/questions/6945592/different-import-results-at-different-directorie...
``` >>> import MyPak >>> reload(MyPak) >>> from MyPak import MyMod ``` However, instances of the old class will not be updated (there's simply no code that describes the update mechanism).
how to reload a Class in python shell?
6,946,376
24
2011-08-04T18:08:10Z
7,123,146
19
2011-08-19T14:34:45Z
[ "python", "ipython", "biopython" ]
If I import a module defining a class of the same name belonging to a package, it is imported as a Class, not a Module because of the \_\_init\_\_.py of the parent package. See [different import results at different directories](http://stackoverflow.com/questions/6945592/different-import-results-at-different-directorie...
I finally found the answer: ``` import MyPak from MyPak import MyMod ``` after editing `MyPak/MyMod.py` file, to reload the class `MyMod` in the file `MyMod.py`, one needs to ``` import sys del sys.modules['MyPak.MyMod'] reload(MyPak) from MyPak import MyMod ``` **Caveats**: 1. Executing `del MyPak` or `del MyMod...
Run wxPython on Lion
6,946,503
8
2011-08-04T18:16:19Z
6,946,933
7
2011-08-04T18:49:18Z
[ "python", "wxpython", "osx-lion" ]
I've just bought a new computer with Lion on it. I've downloaded and installed both Python 2.7 and wxPython 2.8 (for 2.7). I know Python comes with the system, but I rather go with the official one. Anyway, upon typing "import wx" on the IDLE, I get the following message: > Traceback (most recent call last): > File "...
wxPython 2.9 supports 64-bit on Mac too (see the Development version section and look for the cocoa build: <http://wxpython.org/download.php>). This was also discussed on the mailing list, and multiple users confirmed that wx works on Lion: <https://groups.google.com/forum/#!searchin/wxpython-users/lion/wxpython-users/...
Can I get a socket.makefile to have the same read semantics as a regular file?
6,946,629
11
2011-08-04T18:27:34Z
6,947,023
20
2011-08-04T18:56:03Z
[ "python", "file", "sockets", "io" ]
Python file objects have a read method which takes an optional size argument, which is basically the maximum number of bytes to return. For example: ``` fname = "message.txt" open(fname, "w").write("Hello World!") print open(fname).read() # prints the entire file contents print open(fname).read(5) # print "Hello" p...
The problem here is that `client.read()` tries to read from current position to the `EOF`, but the EOF for the socket appears only when the other side closes the connection. `recv` on the other hand will return any data ready to be read (if there are any), or may block according to blocking and timeout settings. Compa...
right way to run some code with timeout in Python
6,947,065
24
2011-08-04T18:59:19Z
6,992,960
7
2011-08-09T07:45:45Z
[ "python", "windows", "multithreading", "timeout" ]
I looked online and found some SO discussing and ActiveState recipes for running some code with a timeout. It looks there are some common approaches: * Use thread that run the code, and `join` it with timeout. If timeout elapsed - kill the thread. This is not directly supported in Python (used private `_Thread__stop` ...
What you might be looking for is the [multiprocessing](http://docs.python.org/library/multiprocessing.html#module-multiprocessing.pool) module. If `subprocess` is too heavy, then this may not suit your needs either. ``` import time import multiprocessing def do_this_other_thing_that_may_take_too_long(duration): t...
right way to run some code with timeout in Python
6,947,065
24
2011-08-04T18:59:19Z
7,027,923
8
2011-08-11T14:46:21Z
[ "python", "windows", "multithreading", "timeout" ]
I looked online and found some SO discussing and ActiveState recipes for running some code with a timeout. It looks there are some common approaches: * Use thread that run the code, and `join` it with timeout. If timeout elapsed - kill the thread. This is not directly supported in Python (used private `_Thread__stop` ...
A completely general solution to this *really, honestly* does not exist. You have to use the right solution for a given domain. * If you want timeouts for code you fully control, you have to write it to cooperate. Such code has to be able to break up into little chunks in some way, as in an event-driven system. You ca...
When to use pip requirements file versus install_requires in setup.py?
6,947,988
60
2011-08-04T20:16:17Z
7,085,000
49
2011-08-16T21:04:48Z
[ "python", "setuptools", "pip", "distribute", "setup.py" ]
I'm using pip with virtualenv to package and install some Python libraries. I'd imagine what I'm doing is a pretty common scenario. I'm the maintainer on several libraries for which I can specify the dependencies explicitly. A few of my libraries are dependent on third party libraries that have transitive dependencies...
My philosophy is that `install_requires` should indicate a minimum of what you need. It might include version requirements if you *know* that some versions will not work; but it shouldn't have version requirements where you aren't sure (e.g., you aren't sure if a future release of a dependency will break your library o...
When to use pip requirements file versus install_requires in setup.py?
6,947,988
60
2011-08-04T20:16:17Z
15,341,042
11
2013-03-11T14:26:55Z
[ "python", "setuptools", "pip", "distribute", "setup.py" ]
I'm using pip with virtualenv to package and install some Python libraries. I'd imagine what I'm doing is a pretty common scenario. I'm the maintainer on several libraries for which I can specify the dependencies explicitly. A few of my libraries are dependent on third party libraries that have transitive dependencies...
here's what I put in my setup.py: ``` # this grabs the requirements from requirements.txt REQUIREMENTS = [i.strip() for i in open("requirements.txt").readlines()] setup( ..... install_requires=REQUIREMENTS ) ```
Python logging: reverse effects of disable()
6,948,190
7
2011-08-04T20:35:11Z
6,948,231
11
2011-08-04T20:39:10Z
[ "python", "logging" ]
The [logging docs](http://docs.python.org/library/logging.html#logging.disable) say that calling the `logging.disable(lvl)` method can "temporarily throttle logging output down across the whole application," but I'm having trouble finding the "temporarily." Take, for example, the following script: ``` import logging l...
``` logging.disable(logging.NOTSET) ```
Determining execution time of queries in SQLite
6,948,270
21
2011-08-04T20:43:33Z
6,948,375
51
2011-08-04T20:53:43Z
[ "python", "sql", "sqlite", "sqlite3" ]
I am creating a program for analyzing and generating queries. I was curious if there currently exists a method within SQLite such that I could query the time taken for a query to process? I am unable to modify my install in any way, so this method needs to work out of the box. I am writing my tool in python, and althou...
From within the sqlite3 command-line program you can do: ``` .timer ON select * from my_table; ``` This will print the CPU time taken for the query.
Why does Python treat tuples, lists, sets and dictionaries as fundamentally different things?
6,948,383
21
2011-08-04T20:54:19Z
6,948,513
13
2011-08-04T21:06:14Z
[ "python", "collections", "language-design", "zen" ]
One of the reasons I love Python is the expressive power / reduced programming effort provided by tuples, lists, sets and dictionaries. Once you understand list comprehensions and a few of the basic patterns using IN and FOR, life gets so much better! Python rocks. However I do wonder why these constructs are treated ...
# tl;dr (duck-typing) You're correct to see some similarities in all these data structures. **Remember that python uses duck-typing** (if it looks like a duck and quacks like a duck then it is a duck). If you can use two objects in the same situation then, for your current intents and purposes, they might as well be t...
Why does Python treat tuples, lists, sets and dictionaries as fundamentally different things?
6,948,383
21
2011-08-04T20:54:19Z
6,948,527
13
2011-08-04T21:07:44Z
[ "python", "collections", "language-design", "zen" ]
One of the reasons I love Python is the expressive power / reduced programming effort provided by tuples, lists, sets and dictionaries. Once you understand list comprehensions and a few of the basic patterns using IN and FOR, life gets so much better! Python rocks. However I do wonder why these constructs are treated ...
These data types all serve different purposes, and in an ideal world you might be able to unify them more. However, in the real world we need to have *efficient* implementations of the basic collections, and e.g. ordering adds a runtime penalty. The named tuples mainly serve to make the interface of stat() and the lik...
Python Tkinter Root Title doesn't work
6,949,265
3
2011-08-04T22:16:56Z
6,949,297
11
2011-08-04T22:20:11Z
[ "python", "user-interface", "tkinter" ]
I can't seem to title my windows. They all have the title "Tk".I believe my code is correct, so correct me if this is wrong... ``` from Tkinter import * root = Tk() root.title="Title" root.mainloop() ``` The title is still Tk(). Could I maybe `from Tkinter import Tk as MyTitle`?
``` root.title("Title") ``` Try that, its a method you invoke and pass in the parameter.
Is there a way to get a line number from an ElementTree Element
6,949,395
10
2011-08-04T22:29:47Z
6,950,930
10
2011-08-05T03:01:20Z
[ "python", "xml", "python-3.x", "elementtree" ]
So I'm parsing some XML files using Python 3.2.1's cElementTree, and during the parsing I noticed that some of the tags were missing attribute information. I was wondering if there is any easy way of getting the line numbers of those Elements in the xml file.
Looking at the docs, I see no way to do this with cElementTree. However I've had luck with [lxml](http://lxml.de/)s version of the XML implementation. Its supposed to be almost a drop in replacement, using libxml2. And elements have a `sourceline` attribute. (As well as getting a lot of other XML features). Only cave...
How to create a dynamic array
6,950,456
9
2011-08-05T01:24:01Z
6,950,527
9
2011-08-05T01:39:41Z
[ "python", "list", "numpy" ]
As I know, list type in Python is a dynamic pointer array, which will increase it's capacity when items are appended to it. And array in NumPy uses a continuous memory area to hold all the data of the array. Are there any types that dynamic increases it's capacity as list, and stores value as NumPy array. Something li...
You may be interested to know that the Python standard library also includes an [array](http://docs.python.org/library/array.html#module-array) module which sounds like just what you want: > This module defines an object type which can compactly represent an > array of basic values: characters, integers, floating poin...
pyaudio help play a file
6,951,046
4
2011-08-05T03:22:41Z
6,951,154
9
2011-08-05T03:45:20Z
[ "python", "audio", "pyaudio" ]
I did not understand the example material for pyaudio. It seems they had written an entire small program and it threw me off. How do I just play a single audio file? Format is not an issue, I just want to know the bare minimum code I need to play an audio file.
May be this small wrapper (warning: created on knees) of their example will help you to understand the meaning of code they wrote. ``` import pyaudio import wave import sys class AudioFile: chunk = 1024 def __init__(self, file): """ Init audio stream """ self.wf = wave.open(file, 'rb') ...
pyaudio help play a file
6,951,046
4
2011-08-05T03:22:41Z
6,951,173
8
2011-08-05T03:47:22Z
[ "python", "audio", "pyaudio" ]
I did not understand the example material for pyaudio. It seems they had written an entire small program and it threw me off. How do I just play a single audio file? Format is not an issue, I just want to know the bare minimum code I need to play an audio file.
The example seems pretty clear to me. You simply save the example as playwav.py call: `python playwav.py my_fav_wav.wav` The wave example with some extra comments: ``` import pyaudio import wave import sys # length of data to read. chunk = 1024 # validation. If a wave file hasn't been specified, exit. if len(sys.a...
Thread Safe Python Property/Attribute?
6,952,478
3
2011-08-05T06:48:20Z
6,953,262
8
2011-08-05T08:08:00Z
[ "python", "properties", "attributes", "thread-safety" ]
I have code like the following: ``` class SomeSharedData(object): def __init__(self): self._lock = RLock() self._errors = 0 @property def errors(self): with self._lock: return self._errors @errors.setter def errors(self, value): with self._lock: ...
You possibly need to think a bit harder about exactly what it means to be thread safe. Consider if you wrote this code instead: ``` class SomeSharedData(object): def __init__(self): self.errors = 0 ``` This code is **exactly** as thread-safe as the code that you posted. Assigning a value to an attribute i...
Thread Safety in Python's dictionary
6,953,351
38
2011-08-05T08:16:37Z
6,953,515
9
2011-08-05T08:33:41Z
[ "python", "multithreading", "dictionary", "thread-safety" ]
I have a class which holds a dictionary ``` class OrderBook: orders = {'Restaurant1': None, 'Restaurant2': None, 'Restaurant3': None, 'Restaurant4': None} @staticmethod def addOrder(restaurant_name, orders): OrderBook.orders[restaurant_name] = orders ``` And...
Yes, built-in types are inherently thread-safe: <http://docs.python.org/glossary.html#term-global-interpreter-lock> > This simplifies the CPython implementation by making the object model (*including critical built-in types such as dict*) implicitly safe against concurrent access.
Thread Safety in Python's dictionary
6,953,351
38
2011-08-05T08:16:37Z
6,955,678
34
2011-08-05T11:42:34Z
[ "python", "multithreading", "dictionary", "thread-safety" ]
I have a class which holds a dictionary ``` class OrderBook: orders = {'Restaurant1': None, 'Restaurant2': None, 'Restaurant3': None, 'Restaurant4': None} @staticmethod def addOrder(restaurant_name, orders): OrderBook.orders[restaurant_name] = orders ``` And...
Python's built-in structures are thread-safe for single operations, but it can sometimes be hard to see where a statement really becomes multiple operations. Your code should be safe. Keep in mind: a lock here will add almost no overhead, and will give you peace of mind. <http://effbot.org/pyfaq/what-kinds-of-global-...
Python REST frameworks for App Engine?
6,954,108
14
2011-08-05T09:21:08Z
9,695,945
10
2012-03-14T04:28:52Z
[ "python", "api", "google-app-engine", "rest", "frameworks" ]
Any pointers, advice on implementing a REST API on App Engine with Python? Using `webapp` for the application itself. What I currently know is that I can: * hack up my own `webapp` handlers for handling REST-like URIs, but this seems to lose its elegance for larger amounts of resources. I mean, it's simple when it co...
I had a similar issue. Wanting to quickly get my DataStore exposed via REST to WebApps. Found: [AppEngine REST Server](http://code.google.com/p/appengine-rest-server/). I have only used it lightly so far, but it certainly appears to be very useful with a small amount of work. And it does use webapp as you suggested.
python equivalent of Comparable
6,954,501
5
2011-08-05T09:54:06Z
6,954,630
8
2011-08-05T10:04:45Z
[ "python" ]
I have a dictionary of the following form: ``` { <Category('Simulate', 'False', 'False', 'False', 'INTERMEDIATE')>: {'link': u'/story/4/tvb-adapters-simulator-simulatorAdapter/SimulatorAdapter', 'name': u'Simulate'}, <Category('View Results', 'True', 'False', 'True', 'INTERMEDIATE')>: {'link': '/story/step/3', 'nam...
First: use `True` and `False` (boolean properties) instead of `'True'` and `'False'` (string properties). Generally, you can make everything comparable in Python. You just have to define specific methods (like `__eq__`, `__lt__`, etc.) for your class. So, let's say I want to compare instances of class A, and the comp...
Python regex findall into output file
6,956,279
3
2011-08-05T12:30:14Z
6,956,350
8
2011-08-05T12:35:33Z
[ "python", "regex" ]
i got an inputfile which contains a javascript code which contains many five-figure ids. I want to have these ids in a list like: > 53231,53891,72829 etc This is my actual python file: ``` import re fobj = open("input.txt", "r") text = fobj.read() output = re.findall(r'[0-9][0-9][0-9][0-9][0-9]' ,text) outp = ope...
``` import re # Use "with" so the file will automatically be closed with open("input.txt", "r") as fobj: text = fobj.read() # Use word boundary anchors (\b) so only five-digit numbers are matched. # Otherwise, 123456 would also be matched (and the match result would be 12345)! output = re.findall(r'\b\d{5}\b', text...
ValueError: invalid \x escape
6,956,402
8
2011-08-05T12:39:10Z
6,956,456
10
2011-08-05T12:42:58Z
[ "python" ]
``` python -c 'print "\x90" * 348 + "\x31\xc0\x83\xec\x01\x88\x04\x24\x68\x62\x61\x73\x68\x68\x62\x69\x6e\x2f\x8\xec\x01\xc6\x04\x24\x2f\x89\xe6\x50\x56\xb0\x0b\x89\xf3\x89\xe1\x31\xd2\xcd\x80\xb0\x01\x31\xdb\xcd\x80" + "\x30\xd1\xff\xff" * 35' ValueError: invalid \x escape ``` Any idea what's causing this error ?
you have `\x8\` in this string, change it to `\x08`
How can I hyperlink a method from a Python module in Sphinx?
6,957,083
5
2011-08-05T13:29:55Z
6,958,210
12
2011-08-05T14:48:04Z
[ "python", "python-sphinx" ]
While writing documentation using Sphinx, I know that I can link to a class by using [Intersphinx](http://sphinx-doc.org/latest/ext/intersphinx.html): ``` :py:class:`logging.Logger` ``` But how do I link directly to a specific method, like `logging.Logger.warning()`?
Just use ``` :py:meth:`module.class.mymethodname` ```
URL building with Flask and non-unique handler names
6,957,396
17
2011-08-05T13:51:52Z
6,958,518
48
2011-08-05T15:09:33Z
[ "python", "url", "url-routing", "wsgi", "flask" ]
Flask provides a [`url_for`](http://flask.pocoo.org/docs/quickstart/#url-building) function to generate URLs to handlers based on the URL pattern. But this would imply that the handler functions must have unique names across the entire application. Is that correct? **Example** Module A has a handler `index`: ``` @ap...
I don't know how you could do with all the views routed by the same module. What I usually do is separate my views in different modules (like you did with module `A` and `B`), and register them as blueprints, after that, when using the `url_for()` function, you can prefix the view name with your blueprint name and the...
visualize structure python module
6,957,484
11
2011-08-05T13:58:18Z
6,957,755
12
2011-08-05T14:16:33Z
[ "python" ]
Is there tool out there which can be used to graphically represent the structure of a python module? I'm thinking that a graph of sub-modules and classes connected by arrows representing imports.
I think you want the Python library [snakefood](http://furius.ca/snakefood/) > sfood: > Given a set of input files or root directories, generate a list of dependencies between the files; > > sfood-graph: > Read a list of dependencies and produce a Graphviz dot file. (This file can be run through the Graphviz dot tool ...
python sqlite string insertion
6,958,833
6
2011-08-05T15:32:40Z
6,958,877
8
2011-08-05T15:35:34Z
[ "python", "sqlite" ]
I'm trying to insert a string that was received as an argument into a sqlite db using python: ``` def addUser(self, name): cursor=self.conn.cursor() t = (name) cursor.execute("INSERT INTO users ( unique_key, name, is_online, translate) VALUES (NULL, ?, 1, 0);", t) s...
You need this: ``` t = (name,) ``` to make a single-element tuple. Remember, it's **commas** that make a tuple, not brackets!
Cannot register custom logging handler class with Django dictConfig
6,958,871
3
2011-08-05T15:35:12Z
6,961,241
8
2011-08-05T18:52:34Z
[ "python", "django", "logging", "python-2.6", "django-1.3" ]
My goal is to create a "log" app, apart from my main app, that will be used for several custom handler classes, filters, etc, and other error and stat reporting. But when running the dev server for my Django project, I receive the error: ``` File "/Library/Python/2.7/site-packages/Django-1.3-py2.7.egg/django/conf/__...
It looks like you are getting a circular import. You cannot define a handler class in a module which itself imports settings.py It is documented at <https://docs.djangoproject.com/en/dev/topics/logging/#topic-logging-parts-handlers> (Search for 'circular imports')
`goto` in Python
6,959,360
26
2011-08-05T16:15:56Z
6,959,532
8
2011-08-05T16:28:34Z
[ "python", "compilation", "bytecode", "goto" ]
I must use `goto` in Python. I read [this](http://entrian.com/goto/) but my Python implementation (CPython 2.7.1 on Mac) does not have this module, so it doesn't seem to be portable. It should at least work in all Python implementations which support CPython bytecode (esp. I care about CPython and PyPy). I could go an...
You may have the only valid use case I have ever seen for needing `goto` in Python. :-) The most straightforward way to emulate forward `goto` in Python is using exceptions, as these can jump out of any depth of nested control structures. ``` class Goto(Exception): pass try: if foo = "bar": raise Got...
`goto` in Python
6,959,360
26
2011-08-05T16:15:56Z
6,960,173
41
2011-08-05T17:20:29Z
[ "python", "compilation", "bytecode", "goto" ]
I must use `goto` in Python. I read [this](http://entrian.com/goto/) but my Python implementation (CPython 2.7.1 on Mac) does not have this module, so it doesn't seem to be portable. It should at least work in all Python implementations which support CPython bytecode (esp. I care about CPython and PyPy). I could go an...
I know what everybody is thinking: [![xkcd GOTO](http://i.stack.imgur.com/f1fOh.png)](http://xkcd.com/292/) However, there might be some didactic cases where you actually need a `goto`. This python recipe provides the `goto` command as a function decorator. [**The goto decorator**](http://code.activestate.com/recip...
Difference between Python print/format methods
6,960,442
7
2011-08-05T17:43:31Z
6,960,715
8
2011-08-05T18:07:52Z
[ "python" ]
When combining a variable and a string to be printed in Python, there seem to be a number of ways to do the same thing; ``` test = "Hello" print "{} World".format(test) #Prints 'Hello World' print test+" World" #Prints 'Hello World' print "%s World" % test #Prints 'Hello World' ``` What (if any) is the difference bet...
A little benchmark: ``` >>> a = lambda: "{} World".format("Hello") >>> b = lambda: "Hello" + " World" >>> c = lambda: "%s World" % "Hello" >>> d = lambda: "".join(("Hello", " World")) >>> a(), b(), c(), d() ('Hello World', 'Hello World', 'Hello World', 'Hello World') >>> timeit.timeit(a) 0.7830071449279785 >>> timeit....
Non-test methods in a Python TestCase
6,961,099
7
2011-08-05T18:39:57Z
6,961,157
20
2011-08-05T18:44:29Z
[ "python", "unit-testing" ]
Ok, as Google search isn't helping me in a while (even when using the correct keywords). I have a class extending from TestCase in which I want to have some auxiliary methods that are not going to be executed as part of the test, they'll be used to generate some mocked objects, etc, auxiliary things for almost any tes...
I believe that you don't have to do anything. Your helper methods should just not start with `test_`.