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
Python: can I have a list with named indices?
178,199
13
2008-10-07T12:25:25Z
178,668
11
2008-10-07T14:21:43Z
[ "python", "arrays" ]
In PHP I can name my array indicies so that I may have something like: ``` $shows = Array(0 => Array('id' => 1, 'name' => 'Sesaeme Street'), 1 => Array('id' => 2, 'name' => 'Dora The Explorer')); ``` Is this possible in Python?
@Unkwntech, What you want is available in the just-released Python 2.6 in the form of [named tuples](http://docs.python.org/whatsnew/2.6.html#new-improved-and-deprecated-modules). They allow you to do this: ``` import collections person = collections.namedtuple('Person', 'id name age') me = person(id=1, age=1e15, na...
Python, unit-testing and mocking imports
178,458
10
2008-10-07T13:34:42Z
179,531
7
2008-10-07T17:30:27Z
[ "python", "unit-testing", "refactoring", "python-import" ]
I am in a project where we are starting refactoring some massive code base. One problem that immediately sprang up is that each file imports a lot of other files. How do I in an elegant way mock this in my unit test without having to alter the actual code so I can start to write unit-tests? As an example: The file wit...
If you want to import a module while at the same time ensuring that it doesn't import anything, you can replace the `__import__` builtin function. For example, use this class: ``` class ImportWrapper(object): def __init__(self, real_import): self.real_import = real_import def wrapper(self, wantedModu...
Average difference between dates in Python
179,716
2
2008-10-07T18:18:48Z
179,738
12
2008-10-07T18:26:46Z
[ "python", "algorithm", "datetime" ]
I have a series of datetime objects and would like to calculate the average delta between them. For example, if the input was `(2008-10-01 12:15:00, 2008-10-01 12:25:00, 2008-10-01 12:35:00)`, then the average delta would be exactly 00:10:00, or 10 minutes. Any suggestions on how to calculate this using Python?
As far as algorithms go, that's an easy one. Just find the max and min datetimes, take the difference, and divide by the number of datetimes you looked at. If you have an array a of datetimes, you can do: ``` mx = max(a) mn = min(a) avg = (mx-mn)/(len(a)-1) ``` to get back the average difference. EDIT: fixed the of...
How to handle a broken pipe (SIGPIPE) in python?
180,095
40
2008-10-07T19:53:53Z
180,152
30
2008-10-07T20:07:27Z
[ "python", "broken-pipe" ]
I've written a simple multi-threaded game server in python that creates a new thread for each client connection. I'm finding that every now and then, the server will crash because of a broken-pipe/SIGPIPE error. I'm pretty sure it is happening when the program tries to send a response back to a client that is no longer...
Read up on the try: statement. ``` try: # do something except socket.error, e: # A socket error except IOError, e: if e.errno == errno.EPIPE: # EPIPE error else: # Other error ```
How to handle a broken pipe (SIGPIPE) in python?
180,095
40
2008-10-07T19:53:53Z
180,922
44
2008-10-08T00:14:18Z
[ "python", "broken-pipe" ]
I've written a simple multi-threaded game server in python that creates a new thread for each client connection. I'm finding that every now and then, the server will crash because of a broken-pipe/SIGPIPE error. I'm pretty sure it is happening when the program tries to send a response back to a client that is no longer...
Assuming that you are using the standard socket module, you should be catching the `socket.error: (32, 'Broken pipe')` exception (not IOError as others have suggested). This will be raised in the case that you've described, i.e. sending/writing to a socket for which the remote side has disconnected. ``` import socket,...
How do I convert a list of ascii values to a string in python?
180,606
31
2008-10-07T21:51:01Z
180,615
56
2008-10-07T21:54:33Z
[ "python", "string", "ascii" ]
I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?
You are probably looking for 'chr()': ``` >>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100] >>> ''.join(chr(i) for i in L) 'hello, world' ```
How do I convert a list of ascii values to a string in python?
180,606
31
2008-10-07T21:51:01Z
181,057
12
2008-10-08T01:22:05Z
[ "python", "string", "ascii" ]
I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?
Same basic solution as others, but I personally prefer to use map instead of the list comprehension: ``` >>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100] >>> ''.join(map(chr,L)) 'hello, world' ```
How do I convert a list of ascii values to a string in python?
180,606
31
2008-10-07T21:51:01Z
184,708
8
2008-10-08T20:22:31Z
[ "python", "string", "ascii" ]
I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?
``` import array def f7(list): return array.array('B', list).tostring() ``` from [Python Patterns - An Optimization Anecdote](http://www.python.org/doc/essays/list2str.html)
In the Django admin interface, is there a way to duplicate an item?
180,809
40
2008-10-07T23:23:11Z
180,816
71
2008-10-07T23:26:15Z
[ "python", "django", "django-models", "django-admin" ]
Just wondering if there is an easy way to add the functionality to duplicate an existing listing in the admin interface? In data entry we have run into a situation where a lot of items share generic data with another item, and to save time it would be very nice to quickly duplicate an existing listing and only alter t...
You can [save as](http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_as) by just enabling adding this to your ModelAdmin: ``` save_as = True ``` This replaces the "Save and add another" button with a "Save as" button. "Save as" means the object will be saved as a new object (...
What is the difference between Python's re.search and re.match?
180,986
189
2008-10-08T00:51:36Z
180,993
209
2008-10-08T00:53:12Z
[ "python", "regex", "search", "match" ]
What is the difference between the `search()` and `match()` functions in the [Python `re` module](http://docs.python.org/2/library/re.html)? I've read the [documentation](http://www.python.org/doc/2.5.2/lib/matching-searching.html) ([current documentation](http://docs.python.org/2/library/re.html?highlight=matching%20...
`re.match` is anchored at the beginning of the string. That has nothing to do with newlines, so it is not the same as using `^` in the pattern. As [re.match documentation](http://docs.python.org/2/library/re.html#re.match) says: > If zero or more characters at the > **beginning of string** match the regular expressio...
What is the difference between Python's re.search and re.match?
180,986
189
2008-10-08T00:51:36Z
181,000
9
2008-10-08T00:54:57Z
[ "python", "regex", "search", "match" ]
What is the difference between the `search()` and `match()` functions in the [Python `re` module](http://docs.python.org/2/library/re.html)? I've read the [documentation](http://www.python.org/doc/2.5.2/lib/matching-searching.html) ([current documentation](http://docs.python.org/2/library/re.html?highlight=matching%20...
re.match attempts to match a pattern **at the beginning of the string**. re.search attempts to match the pattern **throughout the string** until it finds a match.
What is the difference between Python's re.search and re.match?
180,986
189
2008-10-08T00:51:36Z
181,028
37
2008-10-08T01:07:26Z
[ "python", "regex", "search", "match" ]
What is the difference between the `search()` and `match()` functions in the [Python `re` module](http://docs.python.org/2/library/re.html)? I've read the [documentation](http://www.python.org/doc/2.5.2/lib/matching-searching.html) ([current documentation](http://docs.python.org/2/library/re.html?highlight=matching%20...
`re.search` **search**es for the pattern **throughout the string**, whereas `re.match` does *not search* the pattern; if it does not, it has no other choice than to **match** it at start of the string.
What is the difference between Python's re.search and re.match?
180,986
189
2008-10-08T00:51:36Z
8,687,988
32
2011-12-31T12:05:43Z
[ "python", "regex", "search", "match" ]
What is the difference between the `search()` and `match()` functions in the [Python `re` module](http://docs.python.org/2/library/re.html)? I've read the [documentation](http://www.python.org/doc/2.5.2/lib/matching-searching.html) ([current documentation](http://docs.python.org/2/library/re.html?highlight=matching%20...
`search` ⇒ find something anywhere in the string and return a match object. `match` ⇒ find something at the *beginning* of the string and return a match object.
Python style: multiple-line conditions in IFs
181,530
270
2008-10-08T06:19:07Z
181,553
11
2008-10-08T06:31:54Z
[ "python", "coding-style", "if-statement" ]
Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is: ``` if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something ``` Isn't very very appealing visually, because the action blends with the conditions. However, it is the natu...
This doesn't improve so much but... ``` allCondsAreOK = (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4') if allCondsAreOK: do_something ```
Python style: multiple-line conditions in IFs
181,530
270
2008-10-08T06:19:07Z
181,557
296
2008-10-08T06:34:25Z
[ "python", "coding-style", "if-statement" ]
Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is: ``` if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something ``` Isn't very very appealing visually, because the action blends with the conditions. However, it is the natu...
You don't need to use 4 spaces on your second conditional line. Maybe use: ``` if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something ``` Also, don't forget the whitespace is more flexible than you might think: ``` if ( cond1 == 'val1' and cond2 == 'val2'...
Python style: multiple-line conditions in IFs
181,530
270
2008-10-08T06:19:07Z
181,641
13
2008-10-08T07:19:09Z
[ "python", "coding-style", "if-statement" ]
Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is: ``` if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something ``` Isn't very very appealing visually, because the action blends with the conditions. However, it is the natu...
I suggest moving the `and` keyword to the second line and indenting all lines containing conditions with two spaces instead of four: ``` if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something ``` This is exactly how I solve this problem in my code. Having a keyword as the...
Python style: multiple-line conditions in IFs
181,530
270
2008-10-08T06:19:07Z
181,848
11
2008-10-08T08:39:58Z
[ "python", "coding-style", "if-statement" ]
Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is: ``` if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something ``` Isn't very very appealing visually, because the action blends with the conditions. However, it is the natu...
I prefer this style when I have a terribly large if-condition: ``` if ( expr1 and (expr2 or expr3) and hasattr(thingy1, '__eq__') or status=="HappyTimes" ): do_stuff() else: do_other_stuff() ```
Python style: multiple-line conditions in IFs
181,530
270
2008-10-08T06:19:07Z
182,050
61
2008-10-08T10:26:48Z
[ "python", "coding-style", "if-statement" ]
Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is: ``` if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something ``` Isn't very very appealing visually, because the action blends with the conditions. However, it is the natu...
I've resorted to the following in the degenerate case where it's simply AND's or OR's. ``` if all( [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4'] ): if any( [cond1 == 'val1', cond2 == 'val2', cond3 == 'val3', cond4 == 'val4'] ): ``` It shaves a few characters and makes it clear that there's no ...
Python style: multiple-line conditions in IFs
181,530
270
2008-10-08T06:19:07Z
183,206
27
2008-10-08T14:55:02Z
[ "python", "coding-style", "if-statement" ]
Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is: ``` if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something ``` Isn't very very appealing visually, because the action blends with the conditions. However, it is the natu...
*Someone* has to champion use of vertical whitespace here! :) ``` if ( cond1 == val1 and cond2 == val2 and cond3 == val3 ): do_stuff() ``` This makes each condition clearly visible. It also allows cleaner expression of more complex conditions: ``` if ( cond1 == val1 or ( con...
Python style: multiple-line conditions in IFs
181,530
270
2008-10-08T06:19:07Z
4,690,241
12
2011-01-14T10:50:32Z
[ "python", "coding-style", "if-statement" ]
Sometimes I break long conditions in IFs to several lines. The most obvious way to do this is: ``` if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something ``` Isn't very very appealing visually, because the action blends with the conditions. However, it is the natu...
Here's my very personal take: long conditions are (in my view) a code smell that suggests refactoring into a boolean-returning function/method. For example: ``` def is_action__required(...): return (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4') ``` Now, if I found a way ...
What is the problem with reduce()?
181,543
47
2008-10-08T06:27:12Z
181,593
7
2008-10-08T06:53:54Z
[ "python", "python-3.x" ]
There seems to be a lot of heated discussion on the net about the changes to the reduce() function in python 3.0 and how it should be removed. I am having a little difficulty understanding why this is the case; I find it quite reasonable to use it in a variety of cases. If the contempt was simply subjective, I cannot i...
People worry it encourages an obfuscated style of programming, doing something that can be achieved with clearer methods. I'm not against reduce myself, I also find it a useful tool sometimes.
What is the problem with reduce()?
181,543
47
2008-10-08T06:27:12Z
181,646
24
2008-10-08T07:20:43Z
[ "python", "python-3.x" ]
There seems to be a lot of heated discussion on the net about the changes to the reduce() function in python 3.0 and how it should be removed. I am having a little difficulty understanding why this is the case; I find it quite reasonable to use it in a variety of cases. If the contempt was simply subjective, I cannot i...
`reduce()` is not being removed -- it's simply being moved into the `functools` module. Guido's reasoning is that except for trivial cases like summation, code written using `reduce()` is usually clearer when written as an accumulation loop.
What is the problem with reduce()?
181,543
47
2008-10-08T06:27:12Z
181,706
56
2008-10-08T07:42:12Z
[ "python", "python-3.x" ]
There seems to be a lot of heated discussion on the net about the changes to the reduce() function in python 3.0 and how it should be removed. I am having a little difficulty understanding why this is the case; I find it quite reasonable to use it in a variety of cases. If the contempt was simply subjective, I cannot i...
As Guido says in his [The fate of reduce() in Python 3000](http://www.artima.com/weblogs/viewpost.jsp?thread=98196) post: > So now reduce(). This is actually the one I've always hated most, because, apart from a few examples involving + or \*, almost every time I see a reduce() call with a non-trivial function argumen...
wxPython: displaying multiple widgets in same frame
181,573
2
2008-10-08T06:41:18Z
181,626
8
2008-10-08T07:11:08Z
[ "python", "user-interface", "layout", "wxpython", "wxwidgets" ]
I would like to be able to display `Notebook` and a `TxtCtrl` wx widgets in a single frame. Below is an example adapted from the wxpython wiki; is it possible to change their layout (maybe with something like `wx.SplitterWindow`) to display the text box below the `Notebook` in the same frame? ``` import wx import wx.l...
Making two widgets appear on the same frame is easy, actually. You should use sizers to accomplish this. In your example, you can change your `Notebook` class implementation to something like this: ``` class Notebook(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, tit...
When to use the Python debugger
181,724
5
2008-10-08T07:49:01Z
181,767
7
2008-10-08T08:04:08Z
[ "python", "debugging" ]
Since Python is a dynamic, interpreted language you don't have to compile your code before running it. Hence, it's very easy to simply write your code, run it, see what problems occur, and fix them. Using hotkeys or macros can make this incredibly quick. So, because it's so easy to immediately see the output of your p...
I use pdb for basic python debugging. Some of the situations I use it are: * When you have a loop iterating over 100,000 entries and want to break at a specific point, it becomes really helpful.(conditional breaks) * Trace the control flow of someone else's code. * Its always better to use a debugger than litter the c...
When to use the Python debugger
181,724
5
2008-10-08T07:49:01Z
182,010
8
2008-10-08T10:09:56Z
[ "python", "debugging" ]
Since Python is a dynamic, interpreted language you don't have to compile your code before running it. Hence, it's very easy to simply write your code, run it, see what problems occur, and fix them. Using hotkeys or macros can make this incredibly quick. So, because it's so easy to immediately see the output of your p...
In 30 years of programming I've used a debugger exactly 4 times. All four times were to read the `core` file produced from a C program crashing to locate the traceback information that's buried in there. I don't think debuggers help much, even in compiled languages. Many people like debuggers, there are some reasons f...
Setup Python enviroment on windows
182,053
3
2008-10-08T10:29:28Z
182,057
7
2008-10-08T10:31:26Z
[ "python", "windows", "database", "installation", "development-environment" ]
How do I setup a Python enviroment on windows computer so I can start writing and running Python scripts, is there an install bundle? Also which database should i use? Thanks --- Sorry I should of mentioned that I am using this for web based applications. Does it require apache? or does it use another http server? W...
Download the Python 2.6 Windows installer from [python.org](http://python.org/) ([direct link](http://python.org/ftp/python/2.6/python-2.6.msi)). If you're just learning, use the included SQLite library so you don't have to fiddle with database servers. --- Most web development frameworks (Django, Turbogears, etc) co...
How do I watch a file for changes using Python?
182,197
197
2008-10-08T11:12:55Z
182,247
46
2008-10-08T11:29:43Z
[ "python", "file", "pywin32", "watch" ]
I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it. What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the `win32file.FindNextChangeNoti...
Have you already looked at the documentation available on <http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html>? If you only need it to work under Windows the 2nd example seems to be exactly what you want (if you exchange the path of the directory with the one of the file you want to watch). ...
How do I watch a file for changes using Python?
182,197
197
2008-10-08T11:12:55Z
182,259
49
2008-10-08T11:34:14Z
[ "python", "file", "pywin32", "watch" ]
I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it. What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the `win32file.FindNextChangeNoti...
If polling is good enough for you, I'd just watch if the "modified time" file stat changes. To read it: ``` os.stat(filename).st_mtime ``` (Also note that the Windows native change event solution does not work in all circumstances, e.g. on network drives.) ``` import os class Monkey(object): def __init__(self):...
How do I watch a file for changes using Python?
182,197
197
2008-10-08T11:12:55Z
182,953
10
2008-10-08T14:05:53Z
[ "python", "file", "pywin32", "watch" ]
I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it. What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the `win32file.FindNextChangeNoti...
Well after a bit of hacking of Tim Golden's script, I have the following which seems to work quite well: ``` import os import win32file import win32con path_to_watch = "." # look at the current directory file_to_watch = "test.txt" # look for changes to a file called test.txt def ProcessNewData( newData ): print...
How do I watch a file for changes using Python?
182,197
197
2008-10-08T11:12:55Z
473,471
20
2009-01-23T16:08:40Z
[ "python", "file", "pywin32", "watch" ]
I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it. What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the `win32file.FindNextChangeNoti...
It should not work on windows (maybe with cygwin ?), but for unix user, you should use the "fcntl" system call. Here is an example in Python. It's mostly the same code if you need to write it in C (same function names) ``` import time import fcntl import os import signal FNAME = "/HOME/TOTO/FILETOWATCH" def handler(...
How do I watch a file for changes using Python?
182,197
197
2008-10-08T11:12:55Z
3,031,168
19
2010-06-13T05:12:49Z
[ "python", "file", "pywin32", "watch" ]
I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it. What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the `win32file.FindNextChangeNoti...
Check out [pyinotify](https://github.com/seb-m/pyinotify). inotify replaces dnotify (from an earlier answer) in newer linuxes and allows file-level rather than directory-level monitoring.
How do I watch a file for changes using Python?
182,197
197
2008-10-08T11:12:55Z
4,690,739
164
2011-01-14T11:52:26Z
[ "python", "file", "pywin32", "watch" ]
I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it. What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the `win32file.FindNextChangeNoti...
Did you try using [Watchdog](http://packages.python.org/watchdog/)? > Python API library and shell utilities to monitor file system events. > > ### Directory monitoring made easy with > > * A cross-platform API. > * A shell tool to run commands in response to directory changes. > > Get started quickly with a simple ex...
How do I watch a file for changes using Python?
182,197
197
2008-10-08T11:12:55Z
5,339,877
41
2011-03-17T13:45:31Z
[ "python", "file", "pywin32", "watch" ]
I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it. What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the `win32file.FindNextChangeNoti...
If you want a multiplatform solution, then check [QFileSystemWatcher](http://doc.qt.io/qt-4.8/qfilesystemwatcher.html). Here an example code (not sanitized): ``` from PyQt4 import QtCore @QtCore.pyqtSlot(str) def directory_changed(path): print('Directory Changed!!!') @QtCore.pyqtSlot(str) def file_changed(path):...
What do I need to import to gain access to my models?
182,229
7
2008-10-08T11:23:54Z
182,345
12
2008-10-08T11:55:46Z
[ "python", "django" ]
I'd like to run a script to populate my database. I'd like to access it through the Django database API. The only problem is that I don't know what I would need to import to gain access to this. How can this be achieved?
Import your settings module too ``` import os os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings" from mysite.polls.models import Poll, Choice ``` should do the trick.
Os.path : can you explain this behavior?
182,253
5
2008-10-08T11:32:16Z
182,417
24
2008-10-08T12:11:55Z
[ "python", "path" ]
I love Python because it comes batteries included, and I use built-in functions, a lot, to do the dirty job for me. I have always been using happily the os.path module to deal with file path but recently I ended up with unexpected results on Python 2.5 under Ubuntu linux, while dealing with string that represent windo...
If you want to manipulate Windows paths on linux you should use the ntpath module (this is the module that is imported as os.path on windows - posixpath is imported as os.path on linux) ``` >>> import ntpath >>> filepath = r"c:\ttemp\FILEPA~1.EXE" >>> print ntpath.basename(filepath) FILEPA~1.EXE >>> print ntpath.split...
How can I use UUIDs in SQLAlchemy?
183,042
26
2008-10-08T14:26:20Z
812,363
40
2009-05-01T17:29:48Z
[ "python", "postgresql", "orm", "sqlalchemy", "uuid" ]
Is there a way to define a column (primary key) as a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) in [SQLAlchemy](http://www.sqlalchemy.org/) if using [PostgreSQL](http://www.postgresql.org/) (Postgres)?
[I wrote this](http://blog.sadphaeton.com/2009/01/19/sqlalchemy-recipeuuid-column.html) and the domain is gone but here's the guts.... Regardless of how my colleagues who really care about proper database design feel about UUID's and GUIDs used for key fields. I often find I need to do it. I think it has some advantag...
How can I use UUIDs in SQLAlchemy?
183,042
26
2008-10-08T14:26:20Z
5,384,215
21
2011-03-21T21:51:55Z
[ "python", "postgresql", "orm", "sqlalchemy", "uuid" ]
Is there a way to define a column (primary key) as a [UUID](https://en.wikipedia.org/wiki/Universally_unique_identifier) in [SQLAlchemy](http://www.sqlalchemy.org/) if using [PostgreSQL](http://www.postgresql.org/) (Postgres)?
See also the recipe for [Backend-agnostic GUID Type](http://docs.sqlalchemy.org/en/rel_0_9/core/custom_types.html?highlight=guid#backend-agnostic-guid-type) in the SQLAlchemy documentation for column types.
Is this the best way to get unique version of filename w/ Python?
183,480
13
2008-10-08T15:50:21Z
183,582
22
2008-10-08T16:13:02Z
[ "python", "filenames" ]
Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function - and I'm just wondering if there i...
One issue is that there is a race condition in your above code, since there is a gap between testing for existance, and creating the file. There may be security implications to this (think about someone maliciously inserting a symlink to a sensitive file which they wouldn't be able to overwrite, but your program runnin...
In Python, what is the difference between '/' and '//' when used for division?
183,853
144
2008-10-08T17:16:35Z
183,866
9
2008-10-08T17:19:59Z
[ "python", "math", "syntax", "operators" ]
Is there a benefit to using one over the other? They both seem to return the same results. ``` >>> 6/3 2 >>> 6//3 2 ```
`//` implements "floor division", regardless of your type. So `1.0/2.0` will give `0.5`, but both `1/2`, `1//2` and `1.0//2.0` will give `0`. See <https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator> for details
In Python, what is the difference between '/' and '//' when used for division?
183,853
144
2008-10-08T17:16:35Z
183,870
210
2008-10-08T17:21:37Z
[ "python", "math", "syntax", "operators" ]
Is there a benefit to using one over the other? They both seem to return the same results. ``` >>> 6/3 2 >>> 6//3 2 ```
In Python 3.0, `5 / 2` will return `2.5` and `5 // 2` will return `2`. The former is floating point division, and the latter is floor division, sometimes also called integer division. In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a `from __future__ import division`, whi...
In Python, what is the difference between '/' and '//' when used for division?
183,853
144
2008-10-08T17:16:35Z
1,704,753
13
2009-11-09T23:55:18Z
[ "python", "math", "syntax", "operators" ]
Is there a benefit to using one over the other? They both seem to return the same results. ``` >>> 6/3 2 >>> 6//3 2 ```
As everyone has already answered, `//` is floor division. Why this is important is that `//` is unambiguously floor division, in all Python versions from 2.2, including Python 3.x versions. The behavior of `/` can change depending on: * Active `__future__` import or not (module-local) * Python command line option, e...
In Python, what is the difference between '/' and '//' when used for division?
183,853
144
2008-10-08T17:16:35Z
11,604,247
25
2012-07-22T21:50:35Z
[ "python", "math", "syntax", "operators" ]
Is there a benefit to using one over the other? They both seem to return the same results. ``` >>> 6/3 2 >>> 6//3 2 ```
It helps to clarify for the Python 2.x line, `/` is neither floor division nor true division. The current accepted answer is not clear on this. `/` is floor division when both args are int, but is true division when either or both of the args are float. The above tells a lot more truth, and is a lot more clearer than ...
Framework/Language for new web 2.0 sites (2008 and 2009)
184,049
2
2008-10-08T18:07:42Z
184,278
9
2008-10-08T18:51:26Z
[ "python", "ruby-on-rails", "django", "merb" ]
I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now: 1. It is now October 2008. I want to start writing an application for January 2009. I am w...
Sorry, but your question is wrong. People are probably going to vote me down for this one but I want to say it anyway: I wouldn't expect to get an objective answer! Why? That's simple: * All Ruby advocates will tell to use Ruby. * All Python advocates will tell to use Python. * All PHP advocates will tell to use PHP....
Framework/Language for new web 2.0 sites (2008 and 2009)
184,049
2
2008-10-08T18:07:42Z
184,282
16
2008-10-08T18:51:52Z
[ "python", "ruby-on-rails", "django", "merb" ]
I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now: 1. It is now October 2008. I want to start writing an application for January 2009. I am w...
**Django!** Look up the DjangoCon talks on Google/Youtube - Especially "Reusable Apps" (www.youtube.com/watch?v=A-S0tqpPga4) I've been using Django for some time, after starting with Ruby/Rails. I found the Django Community easier to get into (nicer), the language documented with *excellent* examples, and it's modula...
Framework/Language for new web 2.0 sites (2008 and 2009)
184,049
2
2008-10-08T18:07:42Z
188,971
7
2008-10-09T20:02:49Z
[ "python", "ruby-on-rails", "django", "merb" ]
I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now: 1. It is now October 2008. I want to start writing an application for January 2009. I am w...
All of them will get the job done. ## Use the one that you and your team are most familiar with This will have a far greater impact on the delivery times and stability of your app than any of the other variables.
How do I check out a file from perforce in python?
184,187
13
2008-10-08T18:33:08Z
184,193
7
2008-10-08T18:33:51Z
[ "python", "scripting", "perforce" ]
I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first.
Here's what I came up with: ``` import os def CreateNewChangeList(description): "Create a new changelist and returns the changelist number as a string" p4in, p4out = os.popen2("p4 changelist -i") p4in.write("change: new\n") p4in.write("description: " + description) p4in.close() changelist = p4...
How do I check out a file from perforce in python?
184,187
13
2008-10-08T18:33:08Z
184,344
20
2008-10-08T19:02:38Z
[ "python", "scripting", "perforce" ]
I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first.
Perforce has Python wrappers around their C/C++ tools, available in binary form for Windows, and source for other platforms: <http://www.perforce.com/perforce/loadsupp.html#api> You will find their documentation of the scripting API to be helpful: <http://www.perforce.com/perforce/doc.current/manuals/p4script/p4scri...
Regular expression to match start of filename and filename extension
185,378
9
2008-10-08T23:42:27Z
185,397
23
2008-10-08T23:48:59Z
[ "python", "sql", "regex", "like" ]
What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'? The regular expression should match any of the following: ``` RunFoo.py RunBar.py Run42.py ``` It should not match: ``` myRunFoo.py RunBar.py1 Run42.txt ``` The SQL equivalent of...
For a regular expression, you would use: ``` re.match(r'Run.*\.py$') ``` A quick explanation: * . means match any character. * \* means match any repetition of the previous character (hence .\* means any sequence of chars) * \ is an escape to escape the explicit dot * $ indicates "end of the string", so we don't mat...
Regular expression to match start of filename and filename extension
185,378
9
2008-10-08T23:42:27Z
185,426
13
2008-10-09T00:01:25Z
[ "python", "sql", "regex", "like" ]
What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'? The regular expression should match any of the following: ``` RunFoo.py RunBar.py Run42.py ``` It should not match: ``` myRunFoo.py RunBar.py1 Run42.txt ``` The SQL equivalent of...
Warning: * jobscry's answer ("^Run.?.py$") is incorrect (will not match "Run123.py", for example). * orlandu63's answer ("/^Run[\w]\*?.py$/") will not match "RunFoo.Bar.py". (I don't have enough reputation to comment, sorry.)
Regular expression to match start of filename and filename extension
185,378
9
2008-10-08T23:42:27Z
185,593
11
2008-10-09T01:27:29Z
[ "python", "sql", "regex", "like" ]
What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'? The regular expression should match any of the following: ``` RunFoo.py RunBar.py Run42.py ``` It should not match: ``` myRunFoo.py RunBar.py1 Run42.txt ``` The SQL equivalent of...
I don't really understand why you're after a regular expression to solve this 'problem'. You're just after a way to find all .py files that start with 'Run'. So this is a simple solution that will work, without resorting to compiling an running a regular expression: ``` import os for filename in os.listdir(dirname): ...
Delete Folder Contents in Python
185,936
171
2008-10-09T04:22:33Z
185,941
153
2008-10-09T04:27:21Z
[ "python", "file", "local", "delete-directory" ]
How can I delete the contents of a local folder in Python? The current project is for Windows but I would like to see \*nix also.
Updated to only delete files and to used the os.path.join() method suggested in the comments. If you also want to remove subdirectories, uncomment the elif statement. ``` import os, shutil folder = '/path/to/folder' for the_file in os.listdir(folder): file_path = os.path.join(folder, the_file) try: if ...
Delete Folder Contents in Python
185,936
171
2008-10-09T04:22:33Z
186,049
8
2008-10-09T05:52:54Z
[ "python", "file", "local", "delete-directory" ]
How can I delete the contents of a local folder in Python? The current project is for Windows but I would like to see \*nix also.
You might be better off using `os.walk()` for this. `os.listdir()` doesn't distinguish files from directories and you will quickly get into trouble trying to unlink these. There is a good example of using `os.walk()` to recursively remove a directory [here](http://docs.python.org/library/os.html#os.walk), and hints on...
Delete Folder Contents in Python
185,936
171
2008-10-09T04:22:33Z
186,236
125
2008-10-09T07:18:35Z
[ "python", "file", "local", "delete-directory" ]
How can I delete the contents of a local folder in Python? The current project is for Windows but I would like to see \*nix also.
Try the shutil module ``` import shutil shutil.rmtree('/path/to/folder') ``` > Description: `shutil.rmtree(path, > ignore_errors=False, onerror=None)` > > Docstring: Recursively delete a > directory tree. > > If `ignore_errors` is set, errors are > ignored; otherwise, if `onerror` is set, > it is called to handle the...
Delete Folder Contents in Python
185,936
171
2008-10-09T04:22:33Z
1,073,382
50
2009-07-02T09:25:56Z
[ "python", "file", "local", "delete-directory" ]
How can I delete the contents of a local folder in Python? The current project is for Windows but I would like to see \*nix also.
Expanding on mhawke's answer this is what I've implemented. It removes all the content of a folder but not the folder itself. Tested on Linux with files, folders and symbolic links, should work on Windows as well. ``` import os import shutil for root, dirs, files in os.walk('/path/to/folder'): for f in files: ...
Delete Folder Contents in Python
185,936
171
2008-10-09T04:22:33Z
5,756,937
81
2011-04-22T15:23:45Z
[ "python", "file", "local", "delete-directory" ]
How can I delete the contents of a local folder in Python? The current project is for Windows but I would like to see \*nix also.
You can simply do this : ``` import os import glob files = glob.glob('/YOUR/PATH/*') for f in files: os.remove(f) ``` You can of corse use an other filter in you path, for exemple : /YOU/PATH/\*.txt for removing all text files in a directory.
Delete Folder Contents in Python
185,936
171
2008-10-09T04:22:33Z
6,615,332
38
2011-07-07T18:25:47Z
[ "python", "file", "local", "delete-directory" ]
How can I delete the contents of a local folder in Python? The current project is for Windows but I would like to see \*nix also.
Using `rmtree` and recreating the folder could work, but I have run into errors when deleting and immediately recreating folders on network drives. The proposed solution using walk does not work as it uses `rmtree` to remove folders and then may attempt to use `os.unlink` on the files that were previously in those fol...
Delete Folder Contents in Python
185,936
171
2008-10-09T04:22:33Z
20,173,900
10
2013-11-24T11:22:15Z
[ "python", "file", "local", "delete-directory" ]
How can I delete the contents of a local folder in Python? The current project is for Windows but I would like to see \*nix also.
As a oneliner: ``` import os # Python 2.7 map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) ) # Python 3+ list( map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) ) ) ```
What is the best way to open a file for exclusive access in Python?
186,202
29
2008-10-09T06:58:54Z
186,464
16
2008-10-09T09:00:09Z
[ "python", "file", "locking" ]
What is the most elegant way to solve this: * open a file for reading, but only if it is not already opened for writing * open a file for writing, but only if it is not already opened for reading or writing The built-in functions work like this ``` >>> path = r"c:\scr.txt" >>> file1 = open(path, "w") >>> print file1...
I don't think there is a fully crossplatform way. On unix, the fcntl module will do this for you. However on windows (which I assume you are by the paths), you'll need to use the win32file module. Fortunately, there is a portable implementation ([portalocker](https://github.com/WoLpH/portalocker)) using the platform a...
Python - How to use Conch to create a Virtual SSH server
186,316
5
2008-10-09T07:54:12Z
189,452
7
2008-10-09T22:30:29Z
[ "python", "twisted" ]
I'm looking at creating a server in python that I can run, and will work as an SSH server. This will then let different users login, and act as if they'd logged in normally, but only had access to one command. I want to do this so that I can have a system where I can add users to without having to create a system wide...
When you write a Conch server, you can control what happens when the client makes a shell request by implementing [`ISession.openShell`](http://twistedmatrix.com/trac/browser/trunk/twisted/conch/interfaces.py?rev=24441#L62). The Conch server will request [`IConchUser`](http://twistedmatrix.com/trac/browser/trunk/twiste...
Splitting a semicolon-separated string to a dictionary, in Python
186,857
56
2008-10-09T11:38:22Z
186,873
81
2008-10-09T11:43:42Z
[ "python", "string", "dictionary", "split" ]
I have a string that looks like this: ``` "Name1=Value1;Name2=Value2;Name3=Value3" ``` Is there a built-in class/function in Python that will take that string and construct a dictionary, as though I had done this: ``` dict = { "Name1": "Value1", "Name2": "Value2", "Name3": "Value3" } ``` I have looked t...
There's no builtin, but you can accomplish this fairly simply with a generator comprehension: ``` s= "Name1=Value1;Name2=Value2;Name3=Value3" dict(item.split("=") for item in s.split(";")) ``` **[Edit]** From your update you indicate you may need to handle quoting. This does complicate things, depending on what the e...
Configuration file with list of key-value pairs in python
186,916
25
2008-10-09T11:55:48Z
186,990
8
2008-10-09T12:13:27Z
[ "python", "configuration", "serialization" ]
I have a python script that analyzes a set of error messages and checks for each message if it matches a certain pattern (regular expression) in order to group these messages. For example "file x does not exist" and "file y does not exist" would match "file .\* does not exist" and be accounted as two occurrences of "fi...
I've heard that [ConfigObj](http://www.voidspace.org.uk/python/configobj.html "ConfigObj") is easier to work with than ConfigParser. It is used by a lot of big projects, IPython, Trac, Turbogears, etc... From their [introduction](http://www.voidspace.org.uk/python/configobj.html#introduction): ConfigObj is a simple b...
Configuration file with list of key-value pairs in python
186,916
25
2008-10-09T11:55:48Z
187,045
36
2008-10-09T12:32:37Z
[ "python", "configuration", "serialization" ]
I have a python script that analyzes a set of error messages and checks for each message if it matches a certain pattern (regular expression) in order to group these messages. For example "file x does not exist" and "file y does not exist" would match "file .\* does not exist" and be accounted as two occurrences of "fi...
I sometimes just write a python module (i.e. file) called `config.py` or something with following contents: ``` config = { 'name': 'hello', 'see?': 'world' } ``` this can then be 'read' like so: ``` from config import config config['name'] config['see?'] ``` easy.
Configuration file with list of key-value pairs in python
186,916
25
2008-10-09T11:55:48Z
187,628
35
2008-10-09T14:57:08Z
[ "python", "configuration", "serialization" ]
I have a python script that analyzes a set of error messages and checks for each message if it matches a certain pattern (regular expression) in order to group these messages. For example "file x does not exist" and "file y does not exist" would match "file .\* does not exist" and be accounted as two occurrences of "fi...
You have two decent options: 1. Python standard config file format using [ConfigParser](http://docs.python.org/lib/module-ConfigParser.html) 2. [YAML](http://www.yaml.org/) using a library like [PyYAML](http://pyyaml.org/) The standard Python configuration files look like INI files with `[sections]` and `key : val...
Base-2 (Binary) Representation Using Python
187,273
4
2008-10-09T13:38:32Z
187,536
13
2008-10-09T14:29:59Z
[ "python" ]
Building on [How Do You Express Binary Literals in Python](http://stackoverflow.com/questions/1476/how-do-you-express-binary-literals-in-python#13107), I was thinking about sensible, intuitive ways to do that Programming 101 chestnut of displaying integers in base-2 form. This is the best I came up with, but I'd like t...
For best efficiency, you generally want to process more than a single bit at a time. You can use a simple method to get a fixed width binary representation. eg. ``` def _bin(x, width): return ''.join(str((x>>i)&1) for i in xrange(width-1,-1,-1)) ``` \_bin(x, 8) will now give a zero padded representation of x's lo...
Counting array elements in Python
187,455
64
2008-10-09T14:12:55Z
187,463
156
2008-10-09T14:14:56Z
[ "python", "arrays" ]
How can I count the number of elements in an array, because contrary to logic array.count(string) does not count all the elements in the array, it just searches for the number of occurrences of string.
The method len() returns the number of elements in the list. Syntax: ``` len(myArray) ``` Eg: ``` myArray = [1, 2, 3] len(myArray) ``` Output: ``` 3 ```
Counting array elements in Python
187,455
64
2008-10-09T14:12:55Z
188,867
23
2008-10-09T19:40:04Z
[ "python", "arrays" ]
How can I count the number of elements in an array, because contrary to logic array.count(string) does not count all the elements in the array, it just searches for the number of occurrences of string.
`len` is a built-in function that calls the given container object's `__len__` member function to get the number of elements in the object. Functions encased with double underscores are usually "special methods" implementing one of the standard interfaces in Python (container, number, etc). Special methods are used vi...
How do I capture an mp3 stream with python
187,552
11
2008-10-09T14:36:02Z
187,563
15
2008-10-09T14:40:25Z
[ "python", "streaming" ]
What's the best way of capturing an mp3 stream coming off of http and saving it to disk with python? Thus far I've tried ``` target = open(target_path, "w") conn = urllib.urlopen(stream_url) while True: target.write(conn.read(buf_size)) ``` This gives me data but its garbled or wont play in mp3 players.
If you're on Windows, you might accidentally be doing CRLF conversions, corrupting the binary data. Try opening `target` in binary mode: ``` target = open(target_path, "wb") ```
How to make a python, command-line program autocomplete arbitrary things NOT interpreter
187,621
61
2008-10-09T14:55:02Z
187,660
38
2008-10-09T15:01:38Z
[ "python", "linux", "unix", "command-line", "autocomplete" ]
I am aware of how to setup autocompletion of python objects in the python interpreter (on unix). * Google shows many hits for explanations on how to do this. * Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different. I need to know how to enable, tab/...
Use Python's `readline` bindings. For example, ``` import readline def completer(text, state): options = [i for i in commands if i.startswith(text)] if state < len(options): return options[state] else: return None readline.parse_and_bind("tab: complete") readline.set_completer(completer) ...
How to make a python, command-line program autocomplete arbitrary things NOT interpreter
187,621
61
2008-10-09T14:55:02Z
187,701
46
2008-10-09T15:08:18Z
[ "python", "linux", "unix", "command-line", "autocomplete" ]
I am aware of how to setup autocompletion of python objects in the python interpreter (on unix). * Google shows many hits for explanations on how to do this. * Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different. I need to know how to enable, tab/...
Follow the [cmd documentation](http://docs.python.org/library/cmd.html#cmd.Cmd.cmdloop) and you'll be fine ``` import cmd addresses = [ 'here@blubb.com', 'foo@bar.com', 'whatever@wherever.org', ] class MyCmd(cmd.Cmd): def do_send(self, line): pass def complete_send(self, text, line, star...
How to make a python, command-line program autocomplete arbitrary things NOT interpreter
187,621
61
2008-10-09T14:55:02Z
197,158
19
2008-10-13T09:59:23Z
[ "python", "linux", "unix", "command-line", "autocomplete" ]
I am aware of how to setup autocompletion of python objects in the python interpreter (on unix). * Google shows many hits for explanations on how to do this. * Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different. I need to know how to enable, tab/...
Since you say "NOT interpreter" in your question, I guess you don't want answers involving python readline and suchlike. (***edit***: in hindsight, that's obviously not the case. Ho hum. I think this info is interesting anyway, so I'll leave it here.) I think you might be after [this](http://www.debian-administration....
How to make a python, command-line program autocomplete arbitrary things NOT interpreter
187,621
61
2008-10-09T14:55:02Z
209,915
10
2008-10-16T19:26:31Z
[ "python", "linux", "unix", "command-line", "autocomplete" ]
I am aware of how to setup autocompletion of python objects in the python interpreter (on unix). * Google shows many hits for explanations on how to do this. * Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different. I need to know how to enable, tab/...
Here is a full-working version of the code that was very supplied by ephemient [here](http://stackoverflow.com/questions/187621/how-to-make-a-python-command-line-program-autocomplete-arbitrary-things-not-int#187660) (thank you). ``` import readline addrs = ['angela@domain.com', 'michael@domain.com', 'david@test.com']...
How to make a python, command-line program autocomplete arbitrary things NOT interpreter
187,621
61
2008-10-09T14:55:02Z
23,959,790
12
2014-05-30T16:59:54Z
[ "python", "linux", "unix", "command-line", "autocomplete" ]
I am aware of how to setup autocompletion of python objects in the python interpreter (on unix). * Google shows many hits for explanations on how to do this. * Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different. I need to know how to enable, tab/...
I am surprised that nobody has mentioned argcomplete, here is an example from the docs: ``` from argcomplete.completers import ChoicesCompleter parser.add_argument("--protocol", choices=('http', 'https', 'ssh', 'rsync', 'wss')) parser.add_argument("--proto").completer=ChoicesCompleter(('http', 'https', 'ssh', 'rsync'...
Reading/Writing MS Word files in Python
188,444
15
2008-10-09T18:06:51Z
7,848,324
34
2011-10-21T10:45:37Z
[ "python", "ms-word", "read-write" ]
Is it possible to read and write Word (2003 and 2007) files in Python without using a COM object? I know that I can: ``` f = open('c:\file.doc', "w") f.write(text) f.close() ``` but Word will read it as an HTML file not a native .doc file.
See [python-docx](https://github.com/python-openxml/python-docx), its official documentation is available [here](https://python-docx.readthedocs.org/en/latest/). This has worked very well for me.
How can I, in python, iterate over multiple 2d lists at once, cleanly?
189,087
22
2008-10-09T20:32:13Z
189,111
10
2008-10-09T20:39:29Z
[ "python" ]
If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this. ``` for i in r...
You could zip them. ie: ``` for a_row,b_row in zip(alist, blist): for a_item, b_item in zip(a_row,b_row): if a_item.isWhatever: b_item.doSomething() ``` However the overhead of zipping and iterating over the items may be higher than your original method if you rarely actually use the b\_item (...
How can I, in python, iterate over multiple 2d lists at once, cleanly?
189,087
22
2008-10-09T20:32:13Z
189,165
14
2008-10-09T20:51:33Z
[ "python" ]
If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this. ``` for i in r...
I'd start by writing a generator method: ``` def grid_objects(alist, blist): for i in range(len(alist)): for j in range(len(alist[i])): yield(alist[i][j], blist[i][j]) ``` Then whenever you need to iterate over the lists your code looks like this: ``` for (a, b) in grid_objects(alist, blist):...
How can I, in python, iterate over multiple 2d lists at once, cleanly?
189,087
22
2008-10-09T20:32:13Z
189,497
32
2008-10-09T22:49:19Z
[ "python" ]
If I'm making a simple grid based game, for example, I might have a few 2d lists. One might be for terrain, another might be for objects, etc. Unfortunately, when I need to iterate over the lists and have the contents of a square in one list affect part of another list, I have to do something like this. ``` for i in r...
If anyone is interested in performance of the above solutions, here they are for 4000x4000 grids, from fastest to slowest: * [Brian](http://stackoverflow.com/questions/189087/how-can-i-in-python-iterate-over-multiple-2d-lists-at-once-cleanly#189111): 1.08s (modified, with `izip` instead of `zip`) * [John](http://stack...
How to use Python to login to a webpage and retrieve cookies for later usage?
189,555
126
2008-10-09T23:14:43Z
189,580
132
2008-10-09T23:24:39Z
[ "python", "http", "authentication", "cookies" ]
I want to download and parse webpage using python, but to access it I need a couple of cookies set. Therefore I need to login over https to the webpage first. The login moment involves sending two POST params (username, password) to /login.php. During the login request I want to retrieve the cookies from the response h...
``` import urllib, urllib2, cookielib username = 'myuser' password = 'mypassword' cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) login_data = urllib.urlencode({'username' : username, 'j_password' : password}) opener.open('http://www.example.com/login.php', login_data) resp =...
How to use Python to login to a webpage and retrieve cookies for later usage?
189,555
126
2008-10-09T23:14:43Z
12,103,969
122
2012-08-24T06:07:36Z
[ "python", "http", "authentication", "cookies" ]
I want to download and parse webpage using python, but to access it I need a couple of cookies set. Therefore I need to login over https to the webpage first. The login moment involves sending two POST params (username, password) to /login.php. During the login request I want to retrieve the cookies from the response h...
Here's a version using the excellent [requests](http://docs.python-requests.org/en/latest/index.html) library: ``` from requests import session payload = { 'action': 'login', 'username': USERNAME, 'password': PASSWORD } with session() as c: c.post('http://example.com/login.php', data=payload) res...
How to break out of multiple loops in Python?
189,645
226
2008-10-10T00:02:01Z
189,664
70
2008-10-10T00:11:37Z
[ "python", "control-flow" ]
Given the following code (that doesn't work): ``` while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff ``` Is the...
First, ordinary logic is helpful. If, for some reason, the terminating conditions can't be worked out, exceptions are a fall-back plan. ``` class GetOutOfLoop( Exception ): pass try: done= False while not done: isok= False while not (done or isok): ok = get_input("Is this ok? ...
How to break out of multiple loops in Python?
189,645
226
2008-10-10T00:02:01Z
189,666
29
2008-10-10T00:12:38Z
[ "python", "control-flow" ]
Given the following code (that doesn't work): ``` while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff ``` Is the...
First, you may also consider making the process of getting and validating the input a function; within that function, you can just return the value if its correct, and keep spinning in the *while* loop if not. This essentially obviates the problem you solved, and can usually be applied in the more general case (breakin...
How to break out of multiple loops in Python?
189,645
226
2008-10-10T00:02:01Z
189,685
258
2008-10-10T00:25:05Z
[ "python", "control-flow" ]
Given the following code (that doesn't work): ``` while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff ``` Is the...
My first instinct would be to refactor the nested loop into a function and use `return` to break out.
How to break out of multiple loops in Python?
189,645
226
2008-10-10T00:02:01Z
189,696
7
2008-10-10T00:29:37Z
[ "python", "control-flow" ]
Given the following code (that doesn't work): ``` while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff ``` Is the...
``` keeplooping=True while keeplooping: #Do Stuff while keeplooping: #do some other stuff if finisheddoingstuff(): keeplooping=False ``` or something like that. You could set a variable in the inner loop, and check it in the outer loop immediately after the inner loop exits, breaking if app...
How to break out of multiple loops in Python?
189,645
226
2008-10-10T00:02:01Z
189,838
7
2008-10-10T01:41:42Z
[ "python", "control-flow" ]
Given the following code (that doesn't work): ``` while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff ``` Is the...
This isn't the prettiest way to do it, but in my opinion, it's the best way. ``` def loop(): while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": return if ok == "n" or ok == "N": break #do more...
How to break out of multiple loops in Python?
189,645
226
2008-10-10T00:02:01Z
190,070
93
2008-10-10T03:50:44Z
[ "python", "control-flow" ]
Given the following code (that doesn't work): ``` while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff ``` Is the...
[PEP 3136](http://www.python.org/dev/peps/pep-3136/) proposes labeled break/continue. Guido [rejected it](http://mail.python.org/pipermail/python-3000/2007-July/008663.html) because "code so complicated to require this feature is very rare". The PEP does mention some workarounds, though (such as the exception technique...
How to break out of multiple loops in Python?
189,645
226
2008-10-10T00:02:01Z
2,621,659
7
2010-04-12T11:33:15Z
[ "python", "control-flow" ]
Given the following code (that doesn't work): ``` while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff ``` Is the...
Factor your loop logic into an iterator that yields the loop variables and returns when done -- here is a simple one that lays out images in rows/columns until we're out of images or out of places to put them: ``` def it(rows, cols, images): i = 0 for r in xrange(rows): for c in xrange(cols): ...
How to break out of multiple loops in Python?
189,645
226
2008-10-10T00:02:01Z
3,150,107
63
2010-06-30T14:15:59Z
[ "python", "control-flow" ]
Given the following code (that doesn't work): ``` while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff ``` Is the...
Here's another approach that is short. The disadvantage is that you can only break the outer loop, but sometimes it's exactly what you want. ``` for a in xrange(10): for b in xrange(20): if something(a, b): # Break the inner loop... break else: # Continue if the inner lo...
How to break out of multiple loops in Python?
189,645
226
2008-10-10T00:02:01Z
3,171,971
34
2010-07-03T15:50:53Z
[ "python", "control-flow" ]
Given the following code (that doesn't work): ``` while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff ``` Is the...
I tend to agree that refactoring into a function is usually the best approach for this sort of situation, but for when you *really* need to break out of nested loops, here's an interesting variant of the exception-raising approach that @S.Lott described. It uses Python's `with` statement to make the exception raising l...
How to break out of multiple loops in Python?
189,645
226
2008-10-10T00:02:01Z
6,564,670
12
2011-07-03T18:15:55Z
[ "python", "control-flow" ]
Given the following code (that doesn't work): ``` while True: #snip: print out current state while True: ok = get_input("Is this ok? (y/n)") if ok == "y" or ok == "Y": break 2 #this doesn't work :( if ok == "n" or ok == "N": break #do more processing with menus and stuff ``` Is the...
Introduce a new variable that you'll use as a 'loop breaker'. First assign something to it(False,0, etc.), and then, inside the outer loop, before you break from it, change the value to something else(True,1,...). Once the loop exits make the 'parent' loop check for that value. Let me demonstrate: ``` breaker = False ...
Google App Engine and 404 error
189,751
35
2008-10-10T00:51:00Z
189,935
33
2008-10-10T02:36:02Z
[ "python", "google-app-engine", "http-status-code-404" ]
I've setup a static website on GAE using hints found elsewhere, but can't figure out how to return a 404 error. My app.yaml file looks like ``` - url: (.*)/ static_files: static\1/index.html upload: static/index.html - url: / static_dir: static ``` with all the static html/jpg files stored under the static dir...
You need to register a catch-all script handler. Append this at the end of your app.yaml: ``` - url: /.* script: main.py ``` In main.py you will need to put this code: ``` from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app class NotFoundPageHandler(webapp.RequestHand...
Google App Engine and 404 error
189,751
35
2008-10-10T00:51:00Z
3,722,135
25
2010-09-15T21:50:05Z
[ "python", "google-app-engine", "http-status-code-404" ]
I've setup a static website on GAE using hints found elsewhere, but can't figure out how to return a 404 error. My app.yaml file looks like ``` - url: (.*)/ static_files: static\1/index.html upload: static/index.html - url: / static_dir: static ``` with all the static html/jpg files stored under the static dir...
google app engine now has [Custom Error Responses](https://cloud.google.com/appengine/docs/python/config/appconfig?csw=1#Python_app_yaml_Custom_error_responses) so you can now add an error\_handlers section to your app.yaml, as in this example: ``` error_handlers: - file: default_error.html - error_code: over_quota...
How can I quantify difference between two images?
189,943
88
2008-10-10T02:39:33Z
189,960
41
2008-10-10T02:46:02Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
Here's what I would like to do: I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much *looks* the same, I don't want to store the latest snapshot. I imagine there's some way of quantifying the difference, and I...
**A simple solution:** Encode the image as a **jpeg** and look for a substantial change in **filesize**. I've implemented something similar with video thumbnails, and had a lot of success and scalability.
How can I quantify difference between two images?
189,943
88
2008-10-10T02:39:33Z
190,036
12
2008-10-10T03:37:57Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
Here's what I would like to do: I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much *looks* the same, I don't want to store the latest snapshot. I imagine there's some way of quantifying the difference, and I...
A trivial thing to try: Resample both images to small thumbnails (e.g. 64 x 64) and compare the thumbnails pixel-by-pixel with a certain threshold. If the original images are almost the same, the resampled thumbnails will be very similar or even exactly the same. This method takes care of noise that can occur especial...
How can I quantify difference between two images?
189,943
88
2008-10-10T02:39:33Z
190,061
14
2008-10-10T03:47:44Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
Here's what I would like to do: I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much *looks* the same, I don't want to store the latest snapshot. I imagine there's some way of quantifying the difference, and I...
Two popular and relatively simple methods are: (a) the Euclidean distance already suggested, or (b) normalized cross-correlation. Normalized cross-correlation tends to be noticeably more robust to lighting changes than simple cross-correlation. Wikipedia gives a formula for the [normalized cross-correlation](http://en....
How can I quantify difference between two images?
189,943
88
2008-10-10T02:39:33Z
196,882
40
2008-10-13T06:50:17Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
Here's what I would like to do: I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much *looks* the same, I don't want to store the latest snapshot. I imagine there's some way of quantifying the difference, and I...
You can compare two images using functions from [PIL](http://www.pythonware.com/products/pil/). ``` import Image import ImageChops im1 = Image.open("splash.png") im2 = Image.open("splash2.png") diff = ImageChops.difference(im2, im1) ``` The diff object is an image in which every pixel is the result of the subtracti...
How can I quantify difference between two images?
189,943
88
2008-10-10T02:39:33Z
3,935,002
143
2010-10-14T15:43:55Z
[ "python", "image-processing", "background-subtraction", "image-comparison", "timelapse" ]
Here's what I would like to do: I'm taking pictures with a webcam at regular intervals. Sort of like a time lapse thing. However, if nothing has really changed, that is, the picture pretty much *looks* the same, I don't want to store the latest snapshot. I imagine there's some way of quantifying the difference, and I...
## General idea Option 1: Load both images as arrays (`scipy.misc.imread`) and calculate an element-wise (pixel-by-pixel) difference. Calculate the norm of the difference. Option 2: Load both images. Calculate some feature vector for each of them (like a histogram). Calculate distance between feature vectors rather t...
Daemon Threads Explanation
190,010
104
2008-10-10T03:24:07Z
190,017
220
2008-10-10T03:27:36Z
[ "python", "multithreading" ]
In the [Python documentation](https://docs.python.org/2/library/threading.html#thread-objects) it says: > A thread can be flagged as a "daemon thread". The significance of this > flag is that the entire Python program exits when only daemon threads > are left. The initial value is inherited from the creating thread. ...
Some threads do background tasks, like sending keepalive packets, or performing periodic garbage collection, or whatever. These are only useful when the main program is running, and it's okay to kill them off once the other, non-daemon, threads have exited. Without daemon threads, you'd have to keep track of them, and...
Daemon Threads Explanation
190,010
104
2008-10-10T03:24:07Z
190,033
14
2008-10-10T03:36:16Z
[ "python", "multithreading" ]
In the [Python documentation](https://docs.python.org/2/library/threading.html#thread-objects) it says: > A thread can be flagged as a "daemon thread". The significance of this > flag is that the entire Python program exits when only daemon threads > are left. The initial value is inherited from the creating thread. ...
Let's say you're making some kind of dashboard widget. As part of this, you want it to display the unread message count in your email box. So you make a little thread that will: 1. Connect to the mail server and ask how many unread messages you have. 2. Signal the GUI with the updated count. 3. Sleep for a little whil...
Daemon Threads Explanation
190,010
104
2008-10-10T03:24:07Z
190,131
8
2008-10-10T04:34:28Z
[ "python", "multithreading" ]
In the [Python documentation](https://docs.python.org/2/library/threading.html#thread-objects) it says: > A thread can be flagged as a "daemon thread". The significance of this > flag is that the entire Python program exits when only daemon threads > are left. The initial value is inherited from the creating thread. ...
A simpler way to think about it, perhaps: when main returns, your process will not exit if there are non-daemon threads still running. A bit of advice: Clean shutdown is easy to get wrong when threads and synchronization are involved - if you can avoid it, do so. Use daemon threads whenever possible.
Daemon Threads Explanation
190,010
104
2008-10-10T03:24:07Z
583,996
7
2009-02-24T22:55:10Z
[ "python", "multithreading" ]
In the [Python documentation](https://docs.python.org/2/library/threading.html#thread-objects) it says: > A thread can be flagged as a "daemon thread". The significance of this > flag is that the entire Python program exits when only daemon threads > are left. The initial value is inherited from the creating thread. ...
Other posters gave some examples for situations in which you'd use daemon threads. My recommendation, however, is never to use them. It's not because they're not useful, but because there are some bad side effects you can experience if you use them. Daemon threads can still execute after the Python runtime starts tear...