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 |
|---|---|---|---|---|---|---|---|---|---|
Sleeping in a batch file | 166,044 | 129 | 2008-10-03T09:10:29Z | 1,811,248 | 10 | 2009-11-28T01:29:47Z | [
"python",
"batch-file"
] | When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it ... | Over at Server Fault, [a similar question was asked](http://serverfault.com/questions/38318/better-way-to-wait-a-few-seconds-in-a-bat-file), the solution there was:
```
choice /d y /t 5 > nul
``` |
Sleeping in a batch file | 166,044 | 129 | 2008-10-03T09:10:29Z | 1,811,314 | 9 | 2009-11-28T02:00:40Z | [
"python",
"batch-file"
] | When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it ... | You could use the Windows *cscript WSH* layer and this *wait.js* JavaScript file:
```
if (WScript.Arguments.Count() == 1)
WScript.Sleep(WScript.Arguments(0)*1000);
else
WScript.Echo("Usage: cscript wait.js seconds");
``` |
Sleeping in a batch file | 166,044 | 129 | 2008-10-03T09:10:29Z | 5,438,142 | 8 | 2011-03-25T21:04:54Z | [
"python",
"batch-file"
] | When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it ... | Depending on your compatibility needs, either use `ping`:
```
ping -n <numberofseconds+1> localhost >nul 2>&1
```
e.g. to wait 5 seconds, use
```
ping -n 6 localhost >nul 2>&1
```
or on Windows 7 or later use `timeout`:
```
timeout 6 >nul
``` |
Sleeping in a batch file | 166,044 | 129 | 2008-10-03T09:10:29Z | 5,483,958 | 189 | 2011-03-30T08:38:43Z | [
"python",
"batch-file"
] | When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it ... | The [`timeout`](http://technet.microsoft.com/en-us/library/cc754891.aspx) command is available from Vista onwards.
```
c:\> timeout /?
TIMEOUT [/T] timeout [/NOBREAK]
Description:
This utility accepts a timeout parameter to wait for the specified
time period (in seconds) or until any key is pressed. It also
... |
Sleeping in a batch file | 166,044 | 129 | 2008-10-03T09:10:29Z | 6,806,192 | 15 | 2011-07-24T10:10:43Z | [
"python",
"batch-file"
] | When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it ... | I disagree with the answers I found here.
I use the following method entirely based on Windows XP capabilities to do a delay in a batch file:
DELAY.BAT:
```
@ECHO OFF
REM DELAY seconds
REM GET ENDING SECOND
FOR /F "TOKENS=1-3 DELIMS=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, ENDING=(H*60+M)*60... |
Sleeping in a batch file | 166,044 | 129 | 2008-10-03T09:10:29Z | 6,852,798 | 21 | 2011-07-28T00:20:12Z | [
"python",
"batch-file"
] | When writing a batch file to automate something on a Windows box, I've needed to pause its execution for several seconds (usually in a test/wait loop, waiting for a process to start). At the time, the best solution I could find uses ping (I kid you not) to achieve the desired effect. I've found a better write-up of it ... | Using the `ping` method as outlined is how I do it when I can't (or don't want to) add more executables or install any other software.
You should be pinging something that isn't there, and using the `-w` flag so that it fails after that amount of time, not pinging something that *is* there (like localhost) `-n` times.... |
How can I capture all exceptions from a wxPython application? | 166,198 | 6 | 2008-10-03T10:11:16Z | 190,233 | 9 | 2008-10-10T05:30:47Z | [
"python",
"exception",
"error-handling",
"wxwidgets",
"error-reporting"
] | I'm writing a little debug app for a bit of kit we're developing and I'd like to roll it out to a few users to see if they can provoke any crashes. Does anyone know a way of effectively wrapping a wxPython app to catch any and all unhandled exceptions that would cause the app to crash?
Ideally I'd want to capture all ... | For the exception handling, assuming your log file is opened as log:
```
import sys
import traceback
def excepthook(type, value, tb):
message = 'Uncaught exception:\n'
message += ''.join(traceback.format_exception(type, value, tb))
log.write(message)
sys.excepthook = excepthook
``` |
Clearing a list | 166,431 | 7 | 2008-10-03T11:37:23Z | 166,441 | 26 | 2008-10-03T11:40:52Z | [
"python",
"memory-management",
"refactoring",
"list"
] | I find it annoying that I can't clear a list. In this example:
```
a = []
a.append(1)
a.append(2)
a = []
```
The second time I initialize a to a blank list, it creates a new instance of a list, which is in a different place in memory, so I can't use it to reference the first, not to mention it's inefficient.
The on... | You are looking for:
```
del L[:]
``` |
Finding local IP addresses using Python's stdlib | 166,506 | 290 | 2008-10-03T12:03:36Z | 166,520 | 222 | 2008-10-03T12:06:50Z | [
"python",
"networking",
"ip-address"
] | How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library? | ```
import socket
socket.gethostbyname(socket.gethostname())
```
This won't work always (returns `127.0.0.1` on machines having the hostname in `/etc/hosts` as `127.0.0.1`), a paliative would be what gimel shows, use `socket.getfqdn()` instead. Of course your machine needs a resolvable hostname. |
Finding local IP addresses using Python's stdlib | 166,506 | 290 | 2008-10-03T12:03:36Z | 166,589 | 226 | 2008-10-03T12:35:13Z | [
"python",
"networking",
"ip-address"
] | How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library? | I just found this but it seems a bit hackish, however they say tried it on \*nix and I did on windows and it worked.
```
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("gmail.com",80))
print(s.getsockname()[0])
s.close()
```
This assumes you have an internet access, and that there is no... |
Finding local IP addresses using Python's stdlib | 166,506 | 290 | 2008-10-03T12:03:36Z | 166,591 | 62 | 2008-10-03T12:35:42Z | [
"python",
"networking",
"ip-address"
] | How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library? | You can use the [netifaces](http://pypi.python.org/pypi/netifaces) module. Just type:
```
easy_install netifaces
```
in your command shell and it will install itself on default Python installation.
Then you can use it like this:
```
from netifaces import interfaces, ifaddresses, AF_INET
for ifaceName in interfaces(... |
Finding local IP addresses using Python's stdlib | 166,506 | 290 | 2008-10-03T12:03:36Z | 166,992 | 17 | 2008-10-03T13:54:11Z | [
"python",
"networking",
"ip-address"
] | How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library? | If you don't want to use external packages and don't want to rely on outside Internet servers, this might help. It's a code sample that I found on [Google Code Search](http://www.google.com/codesearch?hl=en&lr=&q=getMACAddrWin&sbtn=Search) and modified to return required information:
```
def getIPAddresses():
from... |
Finding local IP addresses using Python's stdlib | 166,506 | 290 | 2008-10-03T12:03:36Z | 1,267,524 | 100 | 2009-08-12T17:20:38Z | [
"python",
"networking",
"ip-address"
] | How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library? | ```
import socket
print([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1])
```
I'm using this, because one of the computers I was on had an /etc/hosts with duplicate entries and references to itself. socket.gethostbyname() only returns the last entry in /etc/hosts. This s... |
Finding local IP addresses using Python's stdlib | 166,506 | 290 | 2008-10-03T12:03:36Z | 1,947,766 | 21 | 2009-12-22T17:07:58Z | [
"python",
"networking",
"ip-address"
] | How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library? | im using following module:
```
#!/usr/bin/python
# module for getting the lan ip address of the computer
import os
import socket
if os.name != "nt":
import fcntl
import struct
def get_interface_ip(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.... |
Finding local IP addresses using Python's stdlib | 166,506 | 290 | 2008-10-03T12:03:36Z | 3,177,266 | 26 | 2010-07-05T04:45:47Z | [
"python",
"networking",
"ip-address"
] | How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library? | I use this on my ubuntu machines:
```
import commands
commands.getoutput("/sbin/ifconfig").split("\n")[1].split()[1][5:]
``` |
Finding local IP addresses using Python's stdlib | 166,506 | 290 | 2008-10-03T12:03:36Z | 6,327,620 | 8 | 2011-06-13T07:21:56Z | [
"python",
"networking",
"ip-address"
] | How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library? | One simple way to produce "clean" output via command line utils:
```
import commands
ips = commands.getoutput("/sbin/ifconfig | grep -i \"inet\" | grep -iv \"inet6\" | " +
"awk {'print $2'} | sed -ne 's/addr\:/ /p'")
print ips
```
It will show all IPv4 addresses on the system. |
Finding local IP addresses using Python's stdlib | 166,506 | 290 | 2008-10-03T12:03:36Z | 6,453,053 | 43 | 2011-06-23T11:07:11Z | [
"python",
"networking",
"ip-address"
] | How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library? | **Socket API method**
```
import socket
# from http://commandline.org.uk/python/how-to-find-out-ip-address-in-python/
def getNetworkIp():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('INSERT SOME TARGET WEBSITE.com', 0))
return s.getsockname()[0]
```
Downsides:
* *Not cross-platform.*... |
Finding local IP addresses using Python's stdlib | 166,506 | 290 | 2008-10-03T12:03:36Z | 9,267,833 | 33 | 2012-02-13T20:52:31Z | [
"python",
"networking",
"ip-address"
] | How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library? | On Linux:
```
>>> import socket, struct, fcntl
>>> sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> sockfd = sock.fileno()
>>> SIOCGIFADDR = 0x8915
>>>
>>> def get_ip(iface = 'eth0'):
... ifreq = struct.pack('16sH14s', iface, socket.AF_INET, '\x00'*14)
... try:
... res = fcntl.ioctl(sockfd,... |
Finding local IP addresses using Python's stdlib | 166,506 | 290 | 2008-10-03T12:03:36Z | 24,564,613 | 7 | 2014-07-03T23:19:34Z | [
"python",
"networking",
"ip-address"
] | How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library? | On Debian (tested) and I suspect most Linux's..
```
import commands
RetMyIP = commands.getoutput("hostname -I")
```
On MS Windows (tested)
```
import socket
socket.gethostbyname(socket.gethostname())
``` |
Finding local IP addresses using Python's stdlib | 166,506 | 290 | 2008-10-03T12:03:36Z | 25,850,698 | 34 | 2014-09-15T14:43:47Z | [
"python",
"networking",
"ip-address"
] | How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library? | If the computer has a route to the Internet, this will *always* work to get the preferred local ip address, even if /etc/hosts is not set correctly.
```
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 0)) # connecting to a UDP address doesn't send packets
local_ip_address = s... |
Finding local IP addresses using Python's stdlib | 166,506 | 290 | 2008-10-03T12:03:36Z | 27,788,672 | 8 | 2015-01-05T22:03:07Z | [
"python",
"networking",
"ip-address"
] | How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library? | A version I do not believe that has been posted yet.
I tested with python 2.7 on Ubuntu 12.04.
Found this solution at : <http://code.activestate.com/recipes/439094-get-the-ip-address-associated-with-a-network-inter/>
```
import socket
import fcntl
import struct
def get_ip_address(ifname):
s = socket.socket(socke... |
Finding local IP addresses using Python's stdlib | 166,506 | 290 | 2008-10-03T12:03:36Z | 28,950,776 | 18 | 2015-03-09T20:02:27Z | [
"python",
"networking",
"ip-address"
] | How can I find local IP addresses (i.e. 192.168.x.x or 10.0.x.x) in Python platform independently and using only the standard library? | This works on Linux and Windows on both Python 2 and 3. Requires a working local interface with a default route (0.0.0.0), but that's it - no routable net access necessary, doesn't try or need to be able to actually *get* anywhere else. (This combines a bunch of ideas from above with modifications to not need external ... |
Finding a public facing IP address in Python? | 166,545 | 14 | 2008-10-03T12:20:07Z | 166,552 | 12 | 2008-10-03T12:22:07Z | [
"python",
"ip-address"
] | How can I find the public facing IP for my net work in Python? | This will fetch your remote IP address
```
import urllib
ip = urllib.urlopen('http://automation.whatismyip.com/n09230945.asp').read()
```
If you don't want to rely on someone else, then just upload something like this PHP script:
```
<?php echo $_SERVER['REMOTE_ADDR']; ?>
```
and change the URL in the Python or if ... |
Finding a public facing IP address in Python? | 166,545 | 14 | 2008-10-03T12:20:07Z | 166,563 | 8 | 2008-10-03T12:25:55Z | [
"python",
"ip-address"
] | How can I find the public facing IP for my net work in Python? | whatismyip.org is better... it just tosses back the ip as plaintext with no extraneous crap.
```
import urllib
ip = urllib.urlopen('http://whatismyip.org').read()
```
But yeah, it's impossible to do it easily without relying on something outside the network itself. |
Calling Python in PHP | 166,944 | 55 | 2008-10-03T13:44:41Z | 167,200 | 82 | 2008-10-03T14:40:12Z | [
"php",
"python"
] | I have a Python script I recently wrote that I call using the command line with some options. I now want a very thin web interface to call this script locally on my Mac.
I don't want to go through the minor trouble of installing mod\_python or mod\_wsgi on my Mac, so I was just going to do a system() or popen() from P... | Depending on what you are doing, [system()](http://php.net/manual/en/function.system.php) or [popen()](http://php.net/manual/en/function.popen.php) may be perfect. Use system() if the Python script has no output, or if you want the Python script's output to go directly to the browser. Use popen() if you want to write d... |
Calling Python in PHP | 166,944 | 55 | 2008-10-03T13:44:41Z | 167,205 | 7 | 2008-10-03T14:40:38Z | [
"php",
"python"
] | I have a Python script I recently wrote that I call using the command line with some options. I now want a very thin web interface to call this script locally on my Mac.
I don't want to go through the minor trouble of installing mod\_python or mod\_wsgi on my Mac, so I was just going to do a system() or popen() from P... | I do this kind of thing all the time for quick-and-dirty scripts. It's quite common to have a CGI or PHP script that just uses system/popen to call some external program.
Just be extra careful if your web server is open to the internet at large. Be sure to sanitize your GET/POST input in this case so as to not allow a... |
Calling Python in PHP | 166,944 | 55 | 2008-10-03T13:44:41Z | 168,678 | 15 | 2008-10-03T20:13:22Z | [
"php",
"python"
] | I have a Python script I recently wrote that I call using the command line with some options. I now want a very thin web interface to call this script locally on my Mac.
I don't want to go through the minor trouble of installing mod\_python or mod\_wsgi on my Mac, so I was just going to do a system() or popen() from P... | There's also a PHP extension: [Pip - Python in PHP](http://www.csh.rit.edu/~jon/projects/pip/), which I've never tried but had it bookmarked for just such an occasion |
Calling Python in PHP | 166,944 | 55 | 2008-10-03T13:44:41Z | 11,601,572 | 8 | 2012-07-22T15:33:38Z | [
"php",
"python"
] | I have a Python script I recently wrote that I call using the command line with some options. I now want a very thin web interface to call this script locally on my Mac.
I don't want to go through the minor trouble of installing mod\_python or mod\_wsgi on my Mac, so I was just going to do a system() or popen() from P... | You can run a python script via php, and outputs on browser.
Basically you have to call the python script this way:
```
$command = "python /path/to/python_script.py 2>&1";
$pid = popen( $command,"r");
while( !feof( $pid ) )
{
echo fread($pid, 256);
flush();
ob_flush();
usleep(100000);
}
pclose($pid);
```
Note: i... |
Calling Python in PHP | 166,944 | 55 | 2008-10-03T13:44:41Z | 18,921,091 | 12 | 2013-09-20T16:01:27Z | [
"php",
"python"
] | I have a Python script I recently wrote that I call using the command line with some options. I now want a very thin web interface to call this script locally on my Mac.
I don't want to go through the minor trouble of installing mod\_python or mod\_wsgi on my Mac, so I was just going to do a system() or popen() from P... | The backquote operator will also allow you to run python scripts using similar syntax to above
In a python file called python.py:
```
hello = "hello"
world = "world"
print hello + " " + world
```
In a php file called python.php:
```
$python = `python python.py`;
echo $python;
``` |
Removing a subset of a dict from within a list | 167,120 | 5 | 2008-10-03T14:24:35Z | 167,134 | 11 | 2008-10-03T14:28:29Z | [
"python",
"list",
"containers"
] | This is really only easy to explain with an example, so to remove the intersection of a list from within a dict I usually do something like this:
```
a = {1:'', 2:'', 3:'', 4:''}
exclusion = [3, 4, 5]
# have to build up a new list or the iteration breaks
toRemove = []
for var in a.iterkeys():
if var in exclusion:... | Consider [dict.pop](http://docs.python.org/library/stdtypes.html#dict.pop):
```
for key in exclusion:
a.pop(key, None)
```
The `None` keeps pop from raising an exception when `key` isn't a key. |
How do you get a directory listing sorted by creation date in python? | 168,409 | 52 | 2008-10-03T19:10:08Z | 168,424 | 65 | 2008-10-03T19:12:48Z | [
"python",
"windows",
"directory"
] | What is the best way to get a list of all files in a directory, sorted by date [created | modified], using python, on a windows machine? | I've done this in the past for a Python script to determine the last updated files in a directory:
```
import glob
import os
search_dir = "/mydir/"
# remove anything from the list that is not a file (directories, symlinks)
# thanks to J.F. Sebastion for pointing out that the requirement was a list
# of files (presum... |
How do you get a directory listing sorted by creation date in python? | 168,409 | 52 | 2008-10-03T19:10:08Z | 168,435 | 15 | 2008-10-03T19:15:23Z | [
"python",
"windows",
"directory"
] | What is the best way to get a list of all files in a directory, sorted by date [created | modified], using python, on a windows machine? | Here's a one-liner:
```
import os
import time
from pprint import pprint
pprint([(x[0], time.ctime(x[1].st_ctime)) for x in sorted([(fn, os.stat(fn)) for fn in os.listdir(".")], key = lambda x: x[1].st_ctime)])
```
This calls os.listdir() to get a list of the filenames, then calls os.stat() for each one to get the cr... |
How do you get a directory listing sorted by creation date in python? | 168,409 | 52 | 2008-10-03T19:10:08Z | 168,580 | 12 | 2008-10-03T19:46:53Z | [
"python",
"windows",
"directory"
] | What is the best way to get a list of all files in a directory, sorted by date [created | modified], using python, on a windows machine? | Here's my version:
```
def getfiles(dirpath):
a = [s for s in os.listdir(dirpath)
if os.path.isfile(os.path.join(dirpath, s))]
a.sort(key=lambda s: os.path.getmtime(os.path.join(dirpath, s)))
return a
```
First, we build a list of the file names. isfile() is used to skip directories; it can be om... |
How do you get a directory listing sorted by creation date in python? | 168,409 | 52 | 2008-10-03T19:10:08Z | 539,024 | 31 | 2009-02-11T21:58:21Z | [
"python",
"windows",
"directory"
] | What is the best way to get a list of all files in a directory, sorted by date [created | modified], using python, on a windows machine? | Here's a more verbose version of [`@Greg Hewgill`'s answer](http://stackoverflow.com/questions/168409/how-do-you-get-a-directory-listing-sorted-by-creation-date-in-python/168435#168435). It is the most conforming to the question requirements. It makes a distinction between creation and modification dates (at least on W... |
How do you get a directory listing sorted by creation date in python? | 168,409 | 52 | 2008-10-03T19:10:08Z | 4,914,674 | 8 | 2011-02-06T16:47:48Z | [
"python",
"windows",
"directory"
] | What is the best way to get a list of all files in a directory, sorted by date [created | modified], using python, on a windows machine? | There is an `os.path.getmtime` function that gives the number of seconds since the epoch
and should be faster than os.stat.
```
os.chdir(directory)
sorted(filter(os.path.isfile, os.listdir('.')), key=os.path.getmtime)
``` |
Python - How do I convert "an OS-level handle to an open file" to a file object? | 168,559 | 41 | 2008-10-03T19:41:04Z | 168,584 | 45 | 2008-10-03T19:47:17Z | [
"python",
"temporary-files",
"mkstemp",
"fdopen"
] | [tempfile.mkstemp()](http://www.python.org/doc/2.5.2/lib/module-tempfile.html) returns:
> a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order.
How do I convert that OS-level handle to a file object?
The [documentation for os.... | You can use
```
os.write(tup[0], "foo\n")
```
to write to the handle.
If you want to open the handle for writing you need to add the **"w"** mode
```
f = os.fdopen(tup[0], "w")
f.write("foo")
``` |
Python - How do I convert "an OS-level handle to an open file" to a file object? | 168,559 | 41 | 2008-10-03T19:41:04Z | 1,296,063 | 13 | 2009-08-18T19:44:31Z | [
"python",
"temporary-files",
"mkstemp",
"fdopen"
] | [tempfile.mkstemp()](http://www.python.org/doc/2.5.2/lib/module-tempfile.html) returns:
> a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order.
How do I convert that OS-level handle to a file object?
The [documentation for os.... | Here's how to do it using a with statement:
```
from __future__ import with_statement
from contextlib import closing
fd, filepath = tempfile.mkstemp()
with closing(os.fdopen(fd, 'w')) as tf:
tf.write('foo\n')
``` |
Now that Python 2.6 is out, what modules currently in the language should every programmer know about? | 168,727 | 9 | 2008-10-03T20:23:12Z | 168,768 | 12 | 2008-10-03T20:31:13Z | [
"python",
"module",
"language-features"
] | A lot of useful features in Python are somewhat "hidden" inside modules. Named tuples (new in [Python 2.6](http://docs.python.org/whatsnew/2.6.html)), for instance, are found in the [collections](http://docs.python.org/library/collections.html) module.
The [Library Documentation page](http://docs.python.org/library/) ... | The most impressive new module is probably the `multiprocessing` module. First because it lets you execute functions in new processes just as easily and with roughly the same API as you would with the `threading` module. But more importantly because it introduces a lot of great classes for communicating between process... |
Python - How do I write a decorator that restores the cwd? | 169,070 | 19 | 2008-10-03T22:04:01Z | 169,112 | 27 | 2008-10-03T22:19:30Z | [
"python",
"decorator",
"cwd"
] | How do I write a decorator that restores the current working directory to what it was before the decorated function was called? In other words, if I use the decorator on a function that does an os.chdir(), the cwd will not be changed after the function is called. | The answer for a decorator has been given; it works at the function definition stage as requested.
With Python 2.5+, you also have an option to do that at the function *call* stage using a context manager:
```
from __future__ import with_statement # needed for 2.5 ⤠Python < 2.6
import contextlib, os
@contextlib.c... |
Python - How do I write a decorator that restores the cwd? | 169,070 | 19 | 2008-10-03T22:04:01Z | 170,174 | 16 | 2008-10-04T11:29:33Z | [
"python",
"decorator",
"cwd"
] | How do I write a decorator that restores the current working directory to what it was before the decorated function was called? In other words, if I use the decorator on a function that does an os.chdir(), the cwd will not be changed after the function is called. | The given answers fail to take into account that the wrapped function may raise an exception. In that case, the directory will never be restored. The code below adds exception handling to the previous answers.
as a decorator:
```
def preserve_cwd(function):
@functools.wraps(function)
def decorator(*args, **kw... |
Python - How do I write a decorator that restores the cwd? | 169,070 | 19 | 2008-10-03T22:04:01Z | 14,019,583 | 8 | 2012-12-24T09:38:59Z | [
"python",
"decorator",
"cwd"
] | How do I write a decorator that restores the current working directory to what it was before the decorated function was called? In other words, if I use the decorator on a function that does an os.chdir(), the cwd will not be changed after the function is called. | The [path.py](https://github.com/jaraco/path.py) module (which you really should use if dealing with paths in python scripts) has a context manager:
```
subdir = d / 'subdir' #subdir is a path object, in the path.py module
with subdir:
# here current dir is subdir
#not anymore
```
(credits goes to [this blog post]... |
How can I compress a folder and email the compressed file in Python? | 169,362 | 7 | 2008-10-03T23:53:35Z | 169,406 | 18 | 2008-10-04T00:17:28Z | [
"python"
] | I would like to compress a folder and all its sub-folders/files, and email the zip file as an attachment. What would be the best way to achieve this with Python? | You can use the [zipfile](http://docs.python.org/dev/library/zipfile.html) module to compress the file using the zip standard, the [email](http://docs.python.org/dev/library/email.html) module to create the email with the attachment, and the [smtplib](http://docs.python.org/dev/library/smtplib.html) module to send it -... |
2D animation in Python | 169,810 | 6 | 2008-10-04T05:36:23Z | 169,825 | 10 | 2008-10-04T05:50:03Z | [
"python",
"animation",
"2d"
] | I'm writing a simulator in Python, and am curious about options and opinions regarding basic 2D animations. By animation, I'm referring to rendering on the fly, not displaying prerendered images.
I'm currently using matplotlib (Wxagg backend), and it's possible that I'll be able to continue using it, but I suspect it ... | I am a fan of [pyglet](http://pyglet.org) which is a completely self contained library for doing graphical work under win32, linux, and OS X.
It has very low overhead, and you can see this for yourself from the tutorial on the website. It *should* play well with wxpython, or at least I seem to recall posts to the mail... |
How to package Twisted program with py2exe? | 169,897 | 10 | 2008-10-04T07:08:05Z | 169,913 | 10 | 2008-10-04T07:21:29Z | [
"python",
"twisted",
"py2exe"
] | I tried to package a Twisted program with py2exe, but once I run the exe file I built, I got a "No module named resource" error.
And I found the py2exe said:
> The following modules appear to be missing ['FCNTL', 'OpenSSL', 'email.Generator', 'email.Iterators', 'email.Utils', 'pkg\_resources', 'pywintypes', 'resource... | I've seen this before... py2exe, for some reason, is not detecting that these modules are needed inside the ZIP archive and is leaving them out.
You can explicitly specify modules to include on the py2exe command line:
```
python setup.py py2exe -p win32com -i twisted.web.resource
```
Something like that. Read up on... |
Django signals vs. overriding save method | 170,337 | 49 | 2008-10-04T13:37:12Z | 171,703 | 57 | 2008-10-05T08:38:39Z | [
"python",
"django",
"django-models",
"django-signals"
] | I'm having trouble wrapping my head around this. Right now I have some models that looks kind of like this:
```
def Review(models.Model)
...fields...
overall_score = models.FloatField(blank=True)
def Score(models.Model)
review = models.ForeignKey(Review)
question = models.TextField()
grade = mode... | Save/delete signals are generally favourable in situations where you need to make changes which aren't completely specific to the model in question, or could be applied to models which have something in common, or could be configured for use across models.
One common task in overridden `save` methods is automated gene... |
UNIX shell written in a reasonable language? | 171,267 | 10 | 2008-10-05T00:42:54Z | 171,280 | 10 | 2008-10-05T00:52:02Z | [
"python",
"unix",
"shell"
] | Has anyone ever heard of a UNIX shell written in a reasonable language, like Python? | [iPython](http://ipython.scipy.org/moin/) (Python) and [Rush](http://rush.heroku.com/) (Ruby) are shells that are designed for more advanced languages. There's also Hotwire, which is sort of a weird integrated shell/terminal emulator. |
UNIX shell written in a reasonable language? | 171,267 | 10 | 2008-10-05T00:42:54Z | 171,294 | 22 | 2008-10-05T01:08:31Z | [
"python",
"unix",
"shell"
] | Has anyone ever heard of a UNIX shell written in a reasonable language, like Python? | * [Eshell](http://www.gnu.org/software/emacs/manual/html_node/eshell/index.html) is a Bash-like shell in Emacs Lisp.
* IPython can be [used as a system shell](http://ipython.org/ipython-doc/stable/interactive/shell.html), though the syntax is a bit weird (supporting all of Python plus basic sh constructs).
* [fish](htt... |
Formatting a list of text into columns | 171,662 | 11 | 2008-10-05T08:09:52Z | 171,707 | 10 | 2008-10-05T08:40:22Z | [
"python",
"string",
"formatting"
] | I'm trying to output a list of string values into a 2 column format. The standard way of making a list of strings into "normal text" is by using the **string.join** method. However, it only takes 2 arguments so I can only make a single column using "\n". I thought trying to make a loop that would simply add a tab betwe... | Two columns, separated by tabs, joined into lines. Look in *itertools* for iterator equivalents, to achieve a space-efficient solution.
```
import string
def fmtpairs(mylist):
pairs = zip(mylist[::2],mylist[1::2])
return '\n'.join('\t'.join(i) for i in pairs)
print fmtpairs(list(string.ascii_uppercase))
A ... |
What is the best way to get all the divisors of a number? | 171,765 | 62 | 2008-10-05T09:48:58Z | 171,779 | 19 | 2008-10-05T10:03:51Z | [
"python",
"algorithm",
"math"
] | Here's the very dumb way:
```
def divisorGenerator(n):
for i in xrange(1,n/2+1):
if n%i == 0: yield i
yield n
```
The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)
I can find prime factors and their multiplicity fast enough.
... | To expand on what Shimi has said, you should only be running your loop from 1 to the square root of n. Then to find the pair, do `n / i`, and this will cover the whole problem space.
As was also noted, this is a NP, or 'difficult' problem. Exhaustive search, the way you are doing it, is about as good as it gets for gu... |
What is the best way to get all the divisors of a number? | 171,765 | 62 | 2008-10-05T09:48:58Z | 171,784 | 62 | 2008-10-05T10:09:20Z | [
"python",
"algorithm",
"math"
] | Here's the very dumb way:
```
def divisorGenerator(n):
for i in xrange(1,n/2+1):
if n%i == 0: yield i
yield n
```
The result I'd like to get is similar to this one, but I'd like a smarter algorithm (this one it's too much slow and dumb :-)
I can find prime factors and their multiplicity fast enough.
... | Given your factorGenerator function, here is a divisorGen that should work:
```
def divisorGen(n):
factors = list(factorGenerator(n))
nfactors = len(factors)
f = [0] * nfactors
while True:
yield reduce(lambda x, y: x*y, [factors[x][0]**f[x] for x in range(nfactors)], 1)
i = 0
wh... |
How do you develop against OpenID locally | 172,040 | 34 | 2008-10-05T14:08:42Z | 172,145 | 9 | 2008-10-05T15:29:43Z | [
"python",
"django",
"openid"
] | I'm developing a website (in Django) that uses OpenID to authenticate users. As I'm currently only running on my local machine I can't authenticate using one of the OpenID providers on the web. So I figure I need to run a local OpenID server that simply lets me type in a username and then passes that back to my main ap... | I have no problems testing with [myopenid.com](http://myopenid.com). I thought there would be a problem testing on my local machine but it just worked. (I'm using ASP.NET with DotNetOpenId library).
The 'realm' and return url must contain the port number like '<http://localhost:93359>'.
I assume it works OK because t... |
How do you develop against OpenID locally | 172,040 | 34 | 2008-10-05T14:08:42Z | 175,273 | 13 | 2008-10-06T17:22:39Z | [
"python",
"django",
"openid"
] | I'm developing a website (in Django) that uses OpenID to authenticate users. As I'm currently only running on my local machine I can't authenticate using one of the OpenID providers on the web. So I figure I need to run a local OpenID server that simply lets me type in a username and then passes that back to my main ap... | The libraries at [OpenID Enabled](http://openidenabled.com/) ship with examples that are sufficient to run a local test provider. Look in the examples/djopenid/ directory of the python-openid source distribution. Running that will give you an instance of [this test provider](http://openidenabled.com/python-openid/trunk... |
How are you planning on handling the migration to Python 3? | 172,306 | 49 | 2008-10-05T17:08:30Z | 214,601 | 88 | 2008-10-18T04:59:57Z | [
"python",
"migration",
"python-3.x",
"py2to3"
] | I'm sure this is a subject that's on most python developers' minds considering that Python 3 is coming out soon. Some questions to get us going in the right direction:
1. Will you have a python 2 and python 3 version to be maintained concurrently or will you simply have a python 3 version once it's finished?
2. Have y... | Here's the general plan for Twisted. I was originally going to blog this, but then I thought: why blog about it when I could get *points* for it?
1. **Wait until somebody cares.**
Right now, nobody has Python 3. We're not going to spend a bunch of effort until at least one actual user has come forth and said "I ne... |
How are you planning on handling the migration to Python 3? | 172,306 | 49 | 2008-10-05T17:08:30Z | 13,095,022 | 8 | 2012-10-26T22:00:41Z | [
"python",
"migration",
"python-3.x",
"py2to3"
] | I'm sure this is a subject that's on most python developers' minds considering that Python 3 is coming out soon. Some questions to get us going in the right direction:
1. Will you have a python 2 and python 3 version to be maintained concurrently or will you simply have a python 3 version once it's finished?
2. Have y... | The Django project uses the library [`six`](http://packages.python.org/six) to maintain a codebase that works simultaneously on Python 2 *and* Python 3 ([blog post](https://www.djangoproject.com/weblog/2012/aug/19/experimental-python-3-support/)).
`six` does this by providing a compatibility layer that intelligently r... |
What symmetric cypher to use for encrypting messages? | 172,392 | 5 | 2008-10-05T18:23:19Z | 172,458 | 7 | 2008-10-05T18:52:23Z | [
"python",
"security",
"encryption"
] | I haven't a clue about encryption at all. But I need it. How?
Say you have a system of nodes communicating with each other on a network via asynchronous messages. The nodes do not maintain session information about other nodes (this is a design restriction).
Say you want to make sure only your nodes can read the mess... | Your first thought should be channel security - either SSL/TLS, or IPSec.
Admittedly, these both have a certain amount of setup overhead, IPSec more than SSL/TLS, especially when it comes to PKI etc. - but it more than pays for itself in simplicity of development, reliability, security, and more. Just make sure you'r... |
What symmetric cypher to use for encrypting messages? | 172,392 | 5 | 2008-10-05T18:23:19Z | 179,023 | 8 | 2008-10-07T15:24:37Z | [
"python",
"security",
"encryption"
] | I haven't a clue about encryption at all. But I need it. How?
Say you have a system of nodes communicating with each other on a network via asynchronous messages. The nodes do not maintain session information about other nodes (this is a design restriction).
Say you want to make sure only your nodes can read the mess... | > I haven't a clue about encryption at all. But I need it. How?
**DANGER!** If you don't know much about cryptography, don't try to implement it yourself. Cryptography is *hard to get right*. There are many, many different ways to break the security of a cryptographic system beyond actually cracking the key (which is ... |
How do I split a multi-line string into multiple lines? | 172,439 | 137 | 2008-10-05T18:46:27Z | 172,454 | 171 | 2008-10-05T18:50:59Z | [
"python",
"string"
] | I have a multi-line string literal that I want to do an operation on each line, like so:
```
inputString = """Line 1
Line 2
Line 3"""
```
I want to do something like the following:
```
for line in inputString:
doStuff()
``` | ```
inputString.splitlines()
```
Will give you a list with each item, the [`splitlines()`](http://docs.python.org/2/library/stdtypes.html#str.splitlines) method is designed to split each line into a list element. |
How do I split a multi-line string into multiple lines? | 172,439 | 137 | 2008-10-05T18:46:27Z | 172,468 | 154 | 2008-10-05T18:58:44Z | [
"python",
"string"
] | I have a multi-line string literal that I want to do an operation on each line, like so:
```
inputString = """Line 1
Line 2
Line 3"""
```
I want to do something like the following:
```
for line in inputString:
doStuff()
``` | Like the others said:
```
inputString.split('\n') # --> ['Line 1', 'Line 2', 'Line 3']
```
This is identical to the above, but the string module's functions are deprecated and should be avoided:
```
import string
string.split(inputString, '\n') # --> ['Line 1', 'Line 2', 'Line 3']
```
Alternatively, if you want e... |
How do I split a multi-line string into multiple lines? | 172,439 | 137 | 2008-10-05T18:46:27Z | 16,752,366 | 14 | 2013-05-25T17:54:57Z | [
"python",
"string"
] | I have a multi-line string literal that I want to do an operation on each line, like so:
```
inputString = """Line 1
Line 2
Line 3"""
```
I want to do something like the following:
```
for line in inputString:
doStuff()
``` | Might be overkill in this particular case but another option involves using `StringIO` to create a file-like object
```
for line in StringIO.StringIO(inputString):
doStuff()
``` |
How do I split a multi-line string into multiple lines? | 172,439 | 137 | 2008-10-05T18:46:27Z | 22,233,816 | 24 | 2014-03-06T19:13:57Z | [
"python",
"string"
] | I have a multi-line string literal that I want to do an operation on each line, like so:
```
inputString = """Line 1
Line 2
Line 3"""
```
I want to do something like the following:
```
for line in inputString:
doStuff()
``` | The best way to do this is to simply use `str.splitlines`.
Besides the advantage mentioned by @efotinis of optionally including the newline character in the split result when called with a `True` argument, `splitlines()` handles newlines properly, unlike `split("\n")`.
---
`\n`, in Python, represents a Unix line-bre... |
Speeding Up Python | 172,720 | 39 | 2008-10-05T21:46:00Z | 172,726 | 16 | 2008-10-05T21:51:10Z | [
"python",
"optimization",
"performance"
] | This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:
* **Firstly**: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?
* **Secondly**: When writing a program from scratch in python, what a... | First thing that comes to mind: [psyco](http://psyco.sourceforge.net/). It runs only on x86, for the time being.
Then, [constant binding](http://code.activestate.com/recipes/277940/). That is, make all global references (and *global.attr*, *global.attr.attr*â¦) be local names inside of functions and methods. This isn... |
Speeding Up Python | 172,720 | 39 | 2008-10-05T21:46:00Z | 172,740 | 9 | 2008-10-05T22:03:44Z | [
"python",
"optimization",
"performance"
] | This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:
* **Firstly**: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?
* **Secondly**: When writing a program from scratch in python, what a... | Cython and pyrex can be used to generate c code using a python-like syntax. Psyco is also fantastic for appropriate projects (sometimes you'll not notice much speed boost, sometimes it'll be as much as 50x as fast).
I still reckon the best way is to profile your code (cProfile, etc.) and then just code the bottlenecks ... |
Speeding Up Python | 172,720 | 39 | 2008-10-05T21:46:00Z | 172,744 | 22 | 2008-10-05T22:09:25Z | [
"python",
"optimization",
"performance"
] | This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:
* **Firstly**: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?
* **Secondly**: When writing a program from scratch in python, what a... | The usual suspects -- profile it, find the most expensive line, figure out what it's doing, fix it. If you haven't done much profiling before, there could be some big fat quadratic loops or string duplication hiding behind otherwise innocuous-looking expressions.
In Python, two of the most common causes I've found for... |
Speeding Up Python | 172,720 | 39 | 2008-10-05T21:46:00Z | 172,784 | 40 | 2008-10-05T22:46:37Z | [
"python",
"optimization",
"performance"
] | This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:
* **Firstly**: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?
* **Secondly**: When writing a program from scratch in python, what a... | Regarding "Secondly: When writing a program from scratch in python, what are some good ways to greatly improve performance?"
Remember the Jackson rules of optimization:
* Rule 1: Don't do it.
* Rule 2 (for experts only): Don't do it yet.
And the Knuth rule:
* "Premature optimization is the root of all evil."
The m... |
Speeding Up Python | 172,720 | 39 | 2008-10-05T21:46:00Z | 172,794 | 7 | 2008-10-05T22:54:57Z | [
"python",
"optimization",
"performance"
] | This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:
* **Firstly**: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?
* **Secondly**: When writing a program from scratch in python, what a... | I'm surprised no one mentioned ShedSkin: <http://code.google.com/p/shedskin/>, it automagically converts your python program to C++ and in some benchmarks yields better improvements than psyco in speed.
Plus anecdotal stories on the simplicity: <http://pyinsci.blogspot.com/2006/12/trying-out-latest-release-of-shedskin... |
Speeding Up Python | 172,720 | 39 | 2008-10-05T21:46:00Z | 173,055 | 26 | 2008-10-06T02:28:52Z | [
"python",
"optimization",
"performance"
] | This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together:
* **Firstly**: Given an established python project, what are some decent ways to speed it up beyond just plain in-code optimization?
* **Secondly**: When writing a program from scratch in python, what a... | Rather than just punting to C, I'd suggest:
Make your code count. Do more with fewer executions of lines:
* Change the algorithm to a faster one. It doesn't need to be fancy to be faster in many cases.
* Use python primitives that happens to be written in C. Some things will force an interpreter dispatch where some w... |
Parsing and generating Microsoft Office 2007 files (.docx, .xlsx, .pptx) | 173,246 | 12 | 2008-10-06T05:07:19Z | 173,306 | 16 | 2008-10-06T06:10:41Z | [
"php",
"python",
"perl",
"parsing",
"office-2007"
] | I have a web project where I must import text and images from a user-supplied document, and one of the possible formats is Microsoft Office 2007. There's also a need to generate documents in this format.
The server runs CentOS 5.2 and has PHP/Perl/Python installed. I can execute local binaries and shell scripts if I m... | The Office 2007 file formats are open and [well documented](http://msdn.microsoft.com/en-us/library/aa338205.aspx). Roughly speaking, all of the new file formats ending in "x" are zip compressed XML documents. For example:
> To open a Word 2007 XML file Create a
> temporary folder in which to store the
> file and its ... |
Is there a way to prevent a SystemExit exception raised from sys.exit() from being caught? | 173,278 | 33 | 2008-10-06T05:40:13Z | 173,323 | 45 | 2008-10-06T06:24:53Z | [
"python",
"exception",
"exit",
"systemexit"
] | The docs say that calling sys.exit() raises a SystemExit exception which can be caught in outer levels. I have a situation in which I want to definitively and unquestionably exit from inside a test case, however the unittest module catches SystemExit and prevents the exit. This is normally great, but the specific situa... | You can call [os.\_exit()](https://docs.python.org/2/library/os.html#os._exit) to directly exit, without throwing an exception:
```
import os
os._exit(1)
```
This bypasses all of the python shutdown logic, such as the atexit module, and will not run through the exception handling logic that you're trying to avoid... |
Is there a way to prevent a SystemExit exception raised from sys.exit() from being caught? | 173,278 | 33 | 2008-10-06T05:40:13Z | 13,723,190 | 29 | 2012-12-05T12:23:15Z | [
"python",
"exception",
"exit",
"systemexit"
] | The docs say that calling sys.exit() raises a SystemExit exception which can be caught in outer levels. I have a situation in which I want to definitively and unquestionably exit from inside a test case, however the unittest module catches SystemExit and prevents the exit. This is normally great, but the specific situa... | As Jerub said, `os._exit(1)` is your answer. But, considering it bypasses *all* cleanup procedures, including `finally:` blocks, closing files, etc, and should really be avoided at all costs, may I present a "safer-ish" way of using it?
If you problem is `SystemExit` being caught at outer levels (ie, unittest), then *... |
python dictionary update method | 173,290 | 17 | 2008-10-06T05:53:32Z | 173,299 | 44 | 2008-10-06T06:05:00Z | [
"python",
"dictionary",
"variables"
] | I have a list string tag.
I am trying to initialize a dictionary with the key as the tag string and values as the array index.
```
for i, ithTag in enumerate(tag):
tagDict.update(ithTag=i)
```
The above returns me {'ithTag': 608} *608 is the 608th index*
My problem is that while the i is being interpreted as a ... | You actually want to do this:
```
for i, tag in enumerate(tag):
tagDict[tag] = i
```
The .update() method is used for updating a dictionary using another dictionary, not for changing a single key/value pair. |
python dictionary update method | 173,290 | 17 | 2008-10-06T05:53:32Z | 173,369 | 17 | 2008-10-06T06:41:44Z | [
"python",
"dictionary",
"variables"
] | I have a list string tag.
I am trying to initialize a dictionary with the key as the tag string and values as the array index.
```
for i, ithTag in enumerate(tag):
tagDict.update(ithTag=i)
```
The above returns me {'ithTag': 608} *608 is the 608th index*
My problem is that while the i is being interpreted as a ... | If you want to be clever:
```
tagDict.update(map(reversed, enumerate(tag)))
```
Thanks to Brian for the update. This is apparently ~5% faster than the iterative version.
(EDIT: Thanks saverio for pointing out my answer was incorrect (now fixed). Probably the most efficient/Pythonic way would be Torsten Marek's answe... |
python dictionary update method | 173,290 | 17 | 2008-10-06T05:53:32Z | 179,005 | 12 | 2008-10-07T15:22:22Z | [
"python",
"dictionary",
"variables"
] | I have a list string tag.
I am trying to initialize a dictionary with the key as the tag string and values as the array index.
```
for i, ithTag in enumerate(tag):
tagDict.update(ithTag=i)
```
The above returns me {'ithTag': 608} *608 is the 608th index*
My problem is that while the i is being interpreted as a ... | It's a one-liner:
```
tagDict = dict((t, i) for i, t in enumerate(tag))
``` |
Does anyone have experience with PyS60 mobile development | 173,484 | 10 | 2008-10-06T07:37:30Z | 330,298 | 8 | 2008-12-01T08:50:45Z | [
"python",
"mobile",
"pys60"
] | I am in the position of having to make a technology choice early in a project which is targetted at mobile phones. I saw that there is a python derivative for S60 and wondered whether anyone could share experiences, good and bad, and suggest appropriate IDE's and emulators.
Please don't tell me that I should be develo... | ## PyS60 -- its cool :)
I worked quite a lot on PyS60 ver 1.3 FP2. It is a great language to port your apps on
Symbian Mobiles and Powerful too. I did my Major project in PyS60, which was a [GSM locator](http://sourceforge.net/projects/gsmlocator)(its not the latest version) app for Symbian phones.
There is also a ve... |
Is it possible to pass arguments into event bindings? | 173,687 | 23 | 2008-10-06T09:31:40Z | 173,694 | 37 | 2008-10-06T09:38:08Z | [
"python",
"events",
"wxpython"
] | I haven't found an answer elsewhere and this doesn't appear to have been asked yet on SO.
When creating an event binding in wxPython, is it possible to pass additional arguments to the event? For example, this is the normal way:
```
b = wx.Button(self, 10, "Default Button", (20, 20))
self.Bind(wx.EVT_BUTTON, ... | You can always use a lambda or another function to wrap up your method and pass another argument, not WX specific.
```
b = wx.Button(self, 10, "Default Button", (20, 20))
self.Bind(wx.EVT_BUTTON, lambda event: self.OnClick(event, 'somevalue'), b)
def OnClick(self, event, somearg):
self.log.write("Click... |
Is it possible to pass arguments into event bindings? | 173,687 | 23 | 2008-10-06T09:31:40Z | 173,826 | 11 | 2008-10-06T10:33:33Z | [
"python",
"events",
"wxpython"
] | I haven't found an answer elsewhere and this doesn't appear to have been asked yet on SO.
When creating an event binding in wxPython, is it possible to pass additional arguments to the event? For example, this is the normal way:
```
b = wx.Button(self, 10, "Default Button", (20, 20))
self.Bind(wx.EVT_BUTTON, ... | The nicest way would be to make a generator of event handlers, e.g.:
```
def getOnClick(self, additionalArgument):
def OnClick(self, event):
self.log.write("Click! (%d), arg: %s\n"
% (event.GetId(), additionalArgument))
return OnClick
```
Now you bind it with:
```
b = wx.But... |
What is the best way to run multiple subprocesses via fork()? | 174,853 | 8 | 2008-10-06T15:47:59Z | 175,038 | 10 | 2008-10-06T16:26:25Z | [
"python",
"linux"
] | A python script need to spawn multiple sub-processes via fork(). All of those child processes should run simultaneously and the parent process should be waiting for all of them to finish. Having an ability to set some timeout on a "slow" child would be nice.
The parent process goes on processing the rest of the script ... | Simple example:
```
import os
chidren = []
for job in jobs:
child = os.fork()
if child:
children.append(child)
else:
pass # really should exec the job
for child in children:
os.waitpid(child, 0)
```
Timing out a slow child is a little more work; you can use `wait` instead of `waitpid`... |
How to output CDATA using ElementTree | 174,890 | 26 | 2008-10-06T15:56:07Z | 175,101 | 21 | 2008-10-06T16:41:48Z | [
"python",
"xml"
] | I've discovered that cElementTree is about 30 times faster than `xml.dom.minidom` and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.
Can it be done? | After a bit of work, I found the answer myself. Looking at the ElementTree.py source code, I found there was special handling of XML comments and preprocessing instructions. What they do is create a factory function for the special element type that uses a special (non-string) tag value to differentiate it from regular... |
How to output CDATA using ElementTree | 174,890 | 26 | 2008-10-06T15:56:07Z | 202,122 | 10 | 2008-10-14T17:43:57Z | [
"python",
"xml"
] | I've discovered that cElementTree is about 30 times faster than `xml.dom.minidom` and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.
Can it be done? | [lxml](http://lxml.de/) has support for [CDATA](http://lxml.de/api.html#cdata) and API like ElementTree. |
How to output CDATA using ElementTree | 174,890 | 26 | 2008-10-06T15:56:07Z | 8,915,039 | 8 | 2012-01-18T18:03:56Z | [
"python",
"xml"
] | I've discovered that cElementTree is about 30 times faster than `xml.dom.minidom` and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.
Can it be done? | Here is a variant of gooli's solution that works for python 3.2:
```
import xml.etree.ElementTree as etree
def CDATA(text=None):
element = etree.Element('![CDATA[')
element.text = text
return element
etree._original_serialize_xml = etree._serialize_xml
def _serialize_xml(write, elem, qnames, namespaces):... |
How do I convert a file's format from Unicode to ASCII using Python? | 175,240 | 18 | 2008-10-06T17:11:30Z | 175,258 | 11 | 2008-10-06T17:17:01Z | [
"python",
"unicode",
"encoding",
"file",
"ascii"
] | I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format.
What is the best way to convert the entire file format using Python? | *I think this is a deeper issue than you realize*. Simply changing the file from Unicode into ASCII is easy, however, getting all of the Unicode characters to translate into reasonable ASCII counterparts (many letters are not available in both encodings) is another.
This Python Unicode tutorial may give you a better i... |
How do I convert a file's format from Unicode to ASCII using Python? | 175,240 | 18 | 2008-10-06T17:11:30Z | 175,270 | 41 | 2008-10-06T17:21:15Z | [
"python",
"unicode",
"encoding",
"file",
"ascii"
] | I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format.
What is the best way to convert the entire file format using Python? | You can convert the file easily enough just using the `unicode` function, but you'll run into problems with Unicode characters without a straight ASCII equivalent.
[This blog](http://www.peterbe.com/plog/unicode-to-ascii) recommends the `unicodedata` module, which seems to take care of roughly converting characters w... |
Python List vs. Array - when to use? | 176,011 | 195 | 2008-10-06T20:17:43Z | 176,033 | 8 | 2008-10-06T20:22:50Z | [
"python",
"arrays",
"list"
] | If you are creating a 1d array, you can implement it as a List, or else use the 'array' module in the standard library. I have always used Lists for 1d arrays.
What is the reason or circumstance where I would want to use the array module instead?
Is it for performance and memory optimization, or am I missing somethin... | My understanding is that arrays are stored more efficiently (i.e. as contiguous blocks of memory vs. pointers to Python objects), but I am not aware of any performance benefit. Additionally, with arrays you must store primitives of the same type, whereas lists can store anything. |
Python List vs. Array - when to use? | 176,011 | 195 | 2008-10-06T20:17:43Z | 176,043 | 42 | 2008-10-06T20:24:38Z | [
"python",
"arrays",
"list"
] | If you are creating a 1d array, you can implement it as a List, or else use the 'array' module in the standard library. I have always used Lists for 1d arrays.
What is the reason or circumstance where I would want to use the array module instead?
Is it for performance and memory optimization, or am I missing somethin... | For almost all cases the normal list is the right choice. The arrays module is more like a thin wrapper over C arrays, which give you kind of strongly typed containers (see [docs](http://docs.python.org/library/array.html#module-array)), with access to more C-like types such as signed/unsigned short or double, which ar... |
Python List vs. Array - when to use? | 176,011 | 195 | 2008-10-06T20:17:43Z | 176,589 | 241 | 2008-10-06T23:11:06Z | [
"python",
"arrays",
"list"
] | If you are creating a 1d array, you can implement it as a List, or else use the 'array' module in the standard library. I have always used Lists for 1d arrays.
What is the reason or circumstance where I would want to use the array module instead?
Is it for performance and memory optimization, or am I missing somethin... | Basically, Python lists are very flexible and can hold completely heterogeneous, arbitrary data, and they can be appended to very efficiently, in [amortized constant time](http://en.wikipedia.org/wiki/Dynamic_array#Geometric_expansion_and_amortized_cost). If you need to shrink and grow your array time-efficiently and w... |
Python List vs. Array - when to use? | 176,011 | 195 | 2008-10-06T20:17:43Z | 178,590 | 19 | 2008-10-07T14:00:40Z | [
"python",
"arrays",
"list"
] | If you are creating a 1d array, you can implement it as a List, or else use the 'array' module in the standard library. I have always used Lists for 1d arrays.
What is the reason or circumstance where I would want to use the array module instead?
Is it for performance and memory optimization, or am I missing somethin... | The array module is kind of one of those things that you probably don't have a need for if you don't know why you would use it (and take note that I'm not trying to say that in a condescending manner!). Most of the time, the array module is used to interface with C code. To give you a more direct answer to your questio... |
Finding the index of an item given a list containing it in Python | 176,918 | 1,222 | 2008-10-07T01:39:38Z | 176,921 | 1,857 | 2008-10-07T01:40:49Z | [
"python",
"list"
] | For a list `["foo", "bar", "baz"]` and an item in the list `"bar"`, what's the cleanest way to get its index (1) in Python? | ```
>>> ["foo", "bar", "baz"].index("bar")
1
```
Reference: [Data Structures > More on Lists](http://docs.python.org/2/tutorial/datastructures.html#more-on-lists) |
Finding the index of an item given a list containing it in Python | 176,918 | 1,222 | 2008-10-07T01:39:38Z | 178,399 | 615 | 2008-10-07T13:19:56Z | [
"python",
"list"
] | For a list `["foo", "bar", "baz"]` and an item in the list `"bar"`, what's the cleanest way to get its index (1) in Python? | One thing that is really helpful in learning Python is to use the interactive help function:
```
>>> help(["foo", "bar", "baz"])
Help on list object:
class list(object)
...
|
| index(...)
| L.index(value, [start, [stop]]) -> integer -- return first index of value
|
```
which will often lead you to the me... |
Finding the index of an item given a list containing it in Python | 176,918 | 1,222 | 2008-10-07T01:39:38Z | 7,241,298 | 75 | 2011-08-30T09:40:54Z | [
"python",
"list"
] | For a list `["foo", "bar", "baz"]` and an item in the list `"bar"`, what's the cleanest way to get its index (1) in Python? | `index()` returns the **first** index of value!
> | index(...)
> | L.index(value, [start, [stop]]) -> integer -- return first index of value
```
def all_indices(value, qlist):
indices = []
idx = -1
while True:
try:
idx = qlist.index(value, idx+1)
indices.append(idx)
... |
Finding the index of an item given a list containing it in Python | 176,918 | 1,222 | 2008-10-07T01:39:38Z | 12,054,409 | 34 | 2012-08-21T12:01:54Z | [
"python",
"list"
] | For a list `["foo", "bar", "baz"]` and an item in the list `"bar"`, what's the cleanest way to get its index (1) in Python? | ```
a = ["foo","bar","baz",'bar','any','much']
b = [item for item in range(len(a)) if a[item] == 'bar']
``` |
Finding the index of an item given a list containing it in Python | 176,918 | 1,222 | 2008-10-07T01:39:38Z | 16,034,499 | 31 | 2013-04-16T10:19:36Z | [
"python",
"list"
] | For a list `["foo", "bar", "baz"]` and an item in the list `"bar"`, what's the cleanest way to get its index (1) in Python? | Problem will arrise if the element is not in the list. You can use this function, it handles the issue:
```
# if element is found it returns index of element else returns -1
def find_element_in_list(element, list_element):
try:
index_element = list_element.index(element)
return index_element
e... |
Finding the index of an item given a list containing it in Python | 176,918 | 1,222 | 2008-10-07T01:39:38Z | 16,593,099 | 11 | 2013-05-16T16:45:29Z | [
"python",
"list"
] | For a list `["foo", "bar", "baz"]` and an item in the list `"bar"`, what's the cleanest way to get its index (1) in Python? | All of the proposed functions here reproduce inherent language behavior but obscure what's going on.
```
[i for i in range(len(mylist)) if mylist[i]==myterm] # get the indices
[each for each in mylist if each==myterm] # get the items
mylist.index(myterm) if myterm in mylist else None # get the first index and fail qui... |
Finding the index of an item given a list containing it in Python | 176,918 | 1,222 | 2008-10-07T01:39:38Z | 17,202,481 | 262 | 2013-06-19T22:31:52Z | [
"python",
"list"
] | For a list `["foo", "bar", "baz"]` and an item in the list `"bar"`, what's the cleanest way to get its index (1) in Python? | I'm honestly surprised no one has mentioned [`enumerate()`](http://docs.python.org/2/library/functions.html#enumerate) yet:
```
for i, j in enumerate(['foo', 'bar', 'baz']):
if j == 'bar':
print i
```
This can be more useful than index if there are duplicates in the list, because index() only returns the ... |
Finding the index of an item given a list containing it in Python | 176,918 | 1,222 | 2008-10-07T01:39:38Z | 17,300,987 | 63 | 2013-06-25T15:07:55Z | [
"python",
"list"
] | For a list `["foo", "bar", "baz"]` and an item in the list `"bar"`, what's the cleanest way to get its index (1) in Python? | To get all indexes:
```
indexes = [i for i,x in enumerate(xs) if x == 'foo']
``` |
Finding the index of an item given a list containing it in Python | 176,918 | 1,222 | 2008-10-07T01:39:38Z | 23,862,698 | 22 | 2014-05-26T04:26:52Z | [
"python",
"list"
] | For a list `["foo", "bar", "baz"]` and an item in the list `"bar"`, what's the cleanest way to get its index (1) in Python? | You have to set a condition to check if the element you're searching is in the list
```
if 'your_element' in mylist:
print mylist.index('your_element')
else:
print None
``` |
Finding the index of an item given a list containing it in Python | 176,918 | 1,222 | 2008-10-07T01:39:38Z | 33,765,024 | 8 | 2015-11-17T19:05:23Z | [
"python",
"list"
] | For a list `["foo", "bar", "baz"]` and an item in the list `"bar"`, what's the cleanest way to get its index (1) in Python? | If you want all indexes, then you can use numpy:
```
import numpy as np
array = [1,2,1,3,4,5,1]
item = 1
np_array = np.array(array)
item_index = np.where(np_array==item)
print item_index
# Out: (array([0, 2, 6], dtype=int64),)
```
It is clear, readable solution. |
Alert boxes in Python? | 177,287 | 16 | 2008-10-07T05:08:36Z | 177,312 | 28 | 2008-10-07T05:29:15Z | [
"python",
"alerts"
] | Is it possible to produce an alert similar to JavaScript's alert("message") in python, with an application running as a daemon.
This will be run in Windows, Most likely XP but 2000 and Vista are also very real possibilities.
Update:
This is intended to run in the background and alert the user when certain condition... | what about this:
```
import win32api
win32api.MessageBox(0, 'hello', 'title')
```
Additionally:
```
win32api.MessageBox(0, 'hello', 'title', 0x00001000)
```
will make the box appear on top of other windows, for urgent messages. See [MessageBox function](http://msdn.microsoft.com/en-us/library/windows/desktop/ms645... |
Testing socket connection in Python | 177,389 | 17 | 2008-10-07T06:30:19Z | 177,411 | 23 | 2008-10-07T06:46:53Z | [
"python",
"sockets"
] | This question will expand on: <http://stackoverflow.com/questions/68774/best-way-to-open-a-socket-in-python>
When opening a socket how can I test to see if it has been established, and that it did not timeout, or generally fail.
Edit:
I tried this:
```
try:
s.connect((address, '80'))
except:
alert('fai... | It seems that you catch not the exception you wanna catch out there :)
if the `s` is a `socket.socket()` object, then the right way to call `.connect` would be:
```
import socket
s = socket.socket()
address = '127.0.0.1'
port = 80 # port number is a number, not string
try:
s.connect((address, port))
# origi... |
Testing socket connection in Python | 177,389 | 17 | 2008-10-07T06:30:19Z | 20,541,919 | 7 | 2013-12-12T11:12:04Z | [
"python",
"sockets"
] | This question will expand on: <http://stackoverflow.com/questions/68774/best-way-to-open-a-socket-in-python>
When opening a socket how can I test to see if it has been established, and that it did not timeout, or generally fail.
Edit:
I tried this:
```
try:
s.connect((address, '80'))
except:
alert('fai... | You can use the function [connect\_ex](http://docs.python.org/2/library/socket.html#socket.socket.connect_ex). It doesn't throw an exception. Instead of that, returns a C style integer value (referred to as [errno](http://linux.die.net/man/3/errno) in C):
```
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
resu... |
Python: can I have a list with named indices? | 178,199 | 13 | 2008-10-07T12:25:25Z | 178,213 | 36 | 2008-10-07T12:29:57Z | [
"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? | This sounds like the PHP array using named indices is very similar to a python dict:
```
shows = [
{"id": 1, "name": "Sesaeme Street"},
{"id": 2, "name": "Dora The Explorer"},
]
```
See <http://docs.python.org/tutorial/datastructures.html#dictionaries> for more on this. |
Python: can I have a list with named indices? | 178,199 | 13 | 2008-10-07T12:25:25Z | 178,224 | 19 | 2008-10-07T12:33:18Z | [
"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? | PHP arrays are actually maps, which is equivalent to dicts in Python.
Thus, this is the Python equivalent:
`showlist = [{'id':1, 'name':'Sesaeme Street'}, {'id':2, 'name':'Dora the Explorer'}]`
Sorting example:
```
from operator import attrgetter
showlist.sort(key=attrgetter('id'))
```
BUT! With the example you p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.