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 [here](http://malektips.com/dos0017.html), which describes a callable "wait.bat", implemented as follows: ``` @ping 127.0.0.1 -n 2 -w 1000 > nul @ping 127.0.0.1 -n %1% -w 1000> nul ``` You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep. [Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command](http://malektips.com/xp_dos_0002.html) (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) [Windows NT](http://en.wikipedia.org/wiki/Windows_NT), is there a better way? I modified the `sleep.py` script in the [accepted answer](http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290), so that it defaults to one second if no arguments are passed on the command line: ``` import time, sys time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1) ```
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 [here](http://malektips.com/dos0017.html), which describes a callable "wait.bat", implemented as follows: ``` @ping 127.0.0.1 -n 2 -w 1000 > nul @ping 127.0.0.1 -n %1% -w 1000> nul ``` You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep. [Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command](http://malektips.com/xp_dos_0002.html) (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) [Windows NT](http://en.wikipedia.org/wiki/Windows_NT), is there a better way? I modified the `sleep.py` script in the [accepted answer](http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290), so that it defaults to one second if no arguments are passed on the command line: ``` import time, sys time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1) ```
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 [here](http://malektips.com/dos0017.html), which describes a callable "wait.bat", implemented as follows: ``` @ping 127.0.0.1 -n 2 -w 1000 > nul @ping 127.0.0.1 -n %1% -w 1000> nul ``` You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep. [Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command](http://malektips.com/xp_dos_0002.html) (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) [Windows NT](http://en.wikipedia.org/wiki/Windows_NT), is there a better way? I modified the `sleep.py` script in the [accepted answer](http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290), so that it defaults to one second if no arguments are passed on the command line: ``` import time, sys time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1) ```
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 [here](http://malektips.com/dos0017.html), which describes a callable "wait.bat", implemented as follows: ``` @ping 127.0.0.1 -n 2 -w 1000 > nul @ping 127.0.0.1 -n %1% -w 1000> nul ``` You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep. [Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command](http://malektips.com/xp_dos_0002.html) (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) [Windows NT](http://en.wikipedia.org/wiki/Windows_NT), is there a better way? I modified the `sleep.py` script in the [accepted answer](http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290), so that it defaults to one second if no arguments are passed on the command line: ``` import time, sys time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1) ```
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 accepts a parameter to ignore the key press. Parameter List: /T timeout Specifies the number of seconds to wait. Valid range is -1 to 99999 seconds. /NOBREAK Ignore key presses and wait specified time. /? Displays this help message. NOTE: A timeout value of -1 means to wait indefinitely for a key press. Examples: TIMEOUT /? TIMEOUT /T 10 TIMEOUT /T 300 /NOBREAK TIMEOUT /T -1 ``` Note: Does not work with input redirection - trivial example: ``` C:\>echo 1 | timeout /t 1 /nobreak ERROR: Input redirection is not supported, exiting the process immediately. ```
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 [here](http://malektips.com/dos0017.html), which describes a callable "wait.bat", implemented as follows: ``` @ping 127.0.0.1 -n 2 -w 1000 > nul @ping 127.0.0.1 -n %1% -w 1000> nul ``` You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep. [Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command](http://malektips.com/xp_dos_0002.html) (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) [Windows NT](http://en.wikipedia.org/wiki/Windows_NT), is there a better way? I modified the `sleep.py` script in the [accepted answer](http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290), so that it defaults to one second if no arguments are passed on the command line: ``` import time, sys time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1) ```
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+S+%1 REM WAIT FOR SUCH A SECOND :WAIT FOR /F "TOKENS=1-3 DELIMS=:." %%A IN ("%TIME%") DO SET /A H=%%A, M=1%%B%%100, S=1%%C%%100, CURRENT=(H*60+M)*60+S IF %CURRENT% LSS %ENDING% GOTO WAIT ``` You may also insert the day in the calculation so the method also works when the delay interval pass over midnight.
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 [here](http://malektips.com/dos0017.html), which describes a callable "wait.bat", implemented as follows: ``` @ping 127.0.0.1 -n 2 -w 1000 > nul @ping 127.0.0.1 -n %1% -w 1000> nul ``` You can then include calls to wait.bat in your own batch file, passing in the number of seconds to sleep. [Apparently the Windows 2003 Resource Kit provides a Unix-like sleep command](http://malektips.com/xp_dos_0002.html) (at last!). In the meantime, for those of us still using Windows XP, Windows 2000 or (sadly) [Windows NT](http://en.wikipedia.org/wiki/Windows_NT), is there a better way? I modified the `sleep.py` script in the [accepted answer](http://stackoverflow.com/questions/166044/sleeping-in-a-dos-batch-file#166290), so that it defaults to one second if no arguments are passed on the command line: ``` import time, sys time.sleep(float(sys.argv[1]) if len(sys.argv) > 1 else 1) ```
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. This allows you to handle time less than a second, and I think it's slightly more accurate. e.g. (test that 1.1.1.1 isn't taken) ``` ECHO Waiting 15 seconds PING 1.1.1.1 -n 1 -w 15000 > NUL or PING -n 15 -w 1000 127.1 >NUL ```
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 output (not just errors) and log it to a file. Any unhandled exceptions ought to log to the current file and then allow the exception to pass on as per usual (i.e. the logging process ought to be transparent). I'm sure someone must have done something along these lines before, but I've not managed to turn up anything that looks useful via google.
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 only way I can see of retaining the same pointer is doing something like the following: ``` for i in range(len(a)): a.pop() ``` This seems pretty long-winded though, is there a better way of solving this?
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 local proxy.
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(): addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )] print '%s: %s' % (ifaceName, ', '.join(addresses)) ``` On my computer it printed: ``` {45639BDC-1050-46E0-9BE9-075C30DE1FBC}: 192.168.0.100 {D43A468B-F3AE-4BF9-9391-4863A4500583}: 10.5.9.207 ``` Author of this module claims it should work on Windows, UNIX and Mac OS X.
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 ctypes import Structure, windll, sizeof from ctypes import POINTER, byref from ctypes import c_ulong, c_uint, c_ubyte, c_char MAX_ADAPTER_DESCRIPTION_LENGTH = 128 MAX_ADAPTER_NAME_LENGTH = 256 MAX_ADAPTER_ADDRESS_LENGTH = 8 class IP_ADDR_STRING(Structure): pass LP_IP_ADDR_STRING = POINTER(IP_ADDR_STRING) IP_ADDR_STRING._fields_ = [ ("next", LP_IP_ADDR_STRING), ("ipAddress", c_char * 16), ("ipMask", c_char * 16), ("context", c_ulong)] class IP_ADAPTER_INFO (Structure): pass LP_IP_ADAPTER_INFO = POINTER(IP_ADAPTER_INFO) IP_ADAPTER_INFO._fields_ = [ ("next", LP_IP_ADAPTER_INFO), ("comboIndex", c_ulong), ("adapterName", c_char * (MAX_ADAPTER_NAME_LENGTH + 4)), ("description", c_char * (MAX_ADAPTER_DESCRIPTION_LENGTH + 4)), ("addressLength", c_uint), ("address", c_ubyte * MAX_ADAPTER_ADDRESS_LENGTH), ("index", c_ulong), ("type", c_uint), ("dhcpEnabled", c_uint), ("currentIpAddress", LP_IP_ADDR_STRING), ("ipAddressList", IP_ADDR_STRING), ("gatewayList", IP_ADDR_STRING), ("dhcpServer", IP_ADDR_STRING), ("haveWins", c_uint), ("primaryWinsServer", IP_ADDR_STRING), ("secondaryWinsServer", IP_ADDR_STRING), ("leaseObtained", c_ulong), ("leaseExpires", c_ulong)] GetAdaptersInfo = windll.iphlpapi.GetAdaptersInfo GetAdaptersInfo.restype = c_ulong GetAdaptersInfo.argtypes = [LP_IP_ADAPTER_INFO, POINTER(c_ulong)] adapterList = (IP_ADAPTER_INFO * 10)() buflen = c_ulong(sizeof(adapterList)) rc = GetAdaptersInfo(byref(adapterList[0]), byref(buflen)) if rc == 0: for a in adapterList: adNode = a.ipAddressList while True: ipAddr = adNode.ipAddress if ipAddr: yield ipAddr adNode = adNode.next if not adNode: break ``` Usage: ``` >>> for addr in getIPAddresses(): >>> print addr 192.168.0.100 10.5.9.207 ``` As it relies on `windll`, this will work only on Windows.
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 solution weeds out the ones starting with "127.". Works with Python 3 and 2.5, possibly other versions too. Does not deal with several network devices or IPv6. Works on Linux and Windows. **Update:** The above technique stopped working on recent Linux distros. This can be used instead: ``` import socket print([(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]) ``` **Update:** Created a long one-liner that combines the two one-liners above. Should work everywhere (Linux, Windows, OS X, Python 2.x and Python 3): ``` import socket print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")][:1], [[(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0]) ``` Note that this may throw an exception if no IP is configured. As an alias: `alias myip="python -c 'import socket; print([l for l in ([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith(\"127.\")][:1], [[(s.connect((\"8.8.8.8\", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) if l][0][0])'"`
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.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', bytes(ifname[:15], 'utf-8')) # Python 2.7: remove the second argument for the bytes call )[20:24]) def get_lan_ip(): ip = socket.gethostbyname(socket.gethostname()) if ip.startswith("127.") and os.name != "nt": interfaces = ["eth0","eth1","eth2","wlan0","wlan1","wifi0","ath0","ath1","ppp0"] for ifname in interfaces: try: ip = get_interface_ip(ifname) break; except IOError: pass return ip ``` Tested with windows and linux (and doesnt require additional modules for those) intended for use on systems which are in a single IPv4 based LAN. The fixed list of interface names does not work for recent linux versions, which have adopted the systemd v197 change regarding predictable interface names as pointed out by [Alexander](https://stackoverflow.com/questions/166506/finding-local-ip-addresses-using-pythons-stdlib/1947766?noredirect=1#comment35654143_1947766). In such cases, you need to manually replace the list with the interface names on your system, or use another solution like [netifaces](http://alastairs-place.net/projects/netifaces/).
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.* * Requires more fallback code, tied to existence of particular addresses on the internet * This will also not work if you're behind a NAT * Probably creates a UDP connection, not independent of (usually ISP's) DNS availability (see other answers for ideas like using 8.8.8.8: Google's (coincidentally also DNS) server) * Very poor form to incorporate third-party dependency (like `google.com`) in code as a means of specifying the network interface, unless you specifically want the public IP of the interface which will route you to the specific website you want. **Spamming innocent third parties is bad. Bad. BAD.** --- **Reflector method** (Do note that this does not answer the OP's question of the local IP address, e.g. 192.168...; it gives you your public IP address, which might be more desirable depending on use case.) You can query some site like whatismyip.com (but with an API), such as: ``` from urllib.request import urlopen import re def getPublicIp(): data = str(urlopen('http://checkip.dyndns.com/').read()) # data = '<html><head><title>Current IP Check</title></head><body>Current IP Address: 65.96.168.198</body></html>\r\n' return re.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1) ``` or if using python2: ``` from urllib import urlopen import re def getPublicIp(): data = str(urlopen('http://checkip.dyndns.com/').read()) # data = '<html><head><title>Current IP Check</title></head><body>Current IP Address: 65.96.168.198</body></html>\r\n' return re.compile(r'Address: (\d+\.\d+\.\d+\.\d+)').search(data).group(1) ``` Advantages: * One upside of this method is it's cross-platform * It works from behind ugly NATs (e.g. your home router). Disadvantages (and workarounds): * Requires this website to be up, the format to not change (almost certainly won't), and your DNS servers to be working. One can mitigate this issue by also querying other third-party IP address reflectors in case of failure. * Possible attack vector if you don't query multiple reflectors (to prevent a compromised reflector from telling you that your address is something it's not), or if you don't use HTTPS (to prevent a man-in-the-middle attack pretending to be the server) --- *edit*: Though initially I thought these methods were really bad (unless you use many fallbacks, the code may be irrelevant many years from now), it does pose the question "what is the internet?". A computer may have many interfaces pointing to many different networks. For a more thorough description of the topic, google for `gateways and routes`. A computer may be able to access an internal network via an internal gateway, or access the world-wide web via a gateway on for example a router (usually the case). The local IP address that the OP asks about is only well-defined with respect to a single link layer, so you have to specify that ("is it the network card, or the ethernet cable, which we're talking about?"). There may be multiple non-unique answers to this question as posed. However the global IP address on the world-wide web is probably well-defined (in the absence of massive network fragmentation): probably the return path via the gateway which can access the TLDs.
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, SIOCGIFADDR, ifreq) ... except: ... return None ... ip = struct.unpack('16sH2x4s8x', res)[2] ... return socket.inet_ntoa(ip) ... >>> get_ip('eth0') '10.80.40.234' >>> ```
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.getsockname()[0] ```
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(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]) )[20:24]) ``` Example Result: > > > get\_ip\_address('eth0') > > > '38.113.228.130'
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 access.) ``` import socket def get_ip(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # doesn't even have to be reachable s.connect(('10.255.255.255', 0)) IP = s.getsockname()[0] except: IP = '127.0.0.1' finally: s.close() return IP ```
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 you prefer ASP: ``` <% Dim UserIPAddress UserIPAddress = Request.ServerVariables("REMOTE_ADDR") %> ``` Note: I don't know ASP, but I figured it might be useful to have here so I googled.
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 PHP to call the Python script. Any better ideas? Thanks in advance!
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 data to the Python script's standard input, or read data from the Python script's standard output in php. popen() will only let you read or write, but not both. If you want both, check out [proc\_open()](http://us.php.net/manual/en/function.proc-open.php), but with two way communication between programs you need to be careful to avoid deadlocks, where each program is waiting for the other to do something. If you want to pass user supplied data to the Python script, then the big thing to be careful about is command injection. If you aren't careful, your user could send you data like "; evilcommand ;" and make your program execute arbitrary commands against your will. [escapeshellarg()](http://www.php.net/manual/en/function.escapeshellarg.php) and [escapeshellcmd()](http://www.php.net/manual/en/function.escapeshellcmd.php) can help with this, but personally I like to remove everything that isn't a known good character, using something like ``` preg_replace('/[^a-zA-Z0-9]/', '', $str) ```
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 PHP to call the Python script. Any better ideas? Thanks in advance!
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 attackers to run arbitrary commands on your machine.
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 PHP to call the Python script. Any better ideas? Thanks in advance!
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 PHP to call the Python script. Any better ideas? Thanks in advance!
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: if you run any time.sleep() in you python code, it will not outputs the results on browser. For full codes working, visit [How to execute python script from php and show output on browser](http://blog.idealmind.com.br/php/how-to-execute-python-script-from-php-and-show-output-on-browser/)
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 PHP to call the Python script. Any better ideas? Thanks in advance!
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: toRemove.append(var) for var in toRemove: del a[var] ``` This might seem like an unusual example, but it's surprising the number of times I've had to do something like this. Doing this with sets would be much nicer, but I clearly want to retain the 'values' for the dict. This method is annoying because it requires two loops and an extra array. Is there a cleaner and more efficient way of doing this.
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 (presumably not including directories) files = filter(os.path.isfile, glob.glob(search_dir + "*")) files.sort(key=lambda x: os.path.getmtime(x)) ``` That should do what you're looking for based on file mtime. **EDIT**: Note that you can also use os.listdir() in place of glob.glob() if desired - the reason I used glob in my original code was that I was wanting to use glob to only search for files with a particular set of file extensions, which glob() was better suited to. To use listdir here's what it would look like: ``` import os search_dir = "/mydir/" os.chdir(search_dir) files = filter(os.path.isfile, os.listdir(search_dir)) files = [os.path.join(search_dir, f) for f in files] # add path to each file files.sort(key=lambda x: os.path.getmtime(x)) ```
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 creation time, then sorts against the creation time. Note that this method only calls os.stat() once for each file, which will be more efficient than calling it for each comparison in a sort.
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 omitted if directories should be included. Then, we sort the list in-place, using the modify date as the key.
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 Windows). ``` #!/usr/bin/env python from stat import S_ISREG, ST_CTIME, ST_MODE import os, sys, time # path to the directory (relative or absolute) dirpath = sys.argv[1] if len(sys.argv) == 2 else r'.' # get all entries in the directory w/ stats entries = (os.path.join(dirpath, fn) for fn in os.listdir(dirpath)) entries = ((os.stat(path), path) for path in entries) # leave only regular files, insert creation date entries = ((stat[ST_CTIME], path) for stat, path in entries if S_ISREG(stat[ST_MODE])) #NOTE: on Windows `ST_CTIME` is a creation date # but on Unix it could be something else #NOTE: use `ST_MTIME` to sort by a modification date for cdate, path in sorted(entries): print time.ctime(cdate), os.path.basename(path) ``` Example: ``` $ python stat_creation_date.py Thu Feb 11 13:31:07 2009 stat_creation_date.py ```
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.open()](http://www.python.org/doc/2.5.2/lib/os-fd-ops.html) states: > To wrap a file descriptor in a "file > object", use fdopen(). So I tried: ``` >>> import tempfile >>> tup = tempfile.mkstemp() >>> import os >>> f = os.fdopen(tup[0]) >>> f.write('foo\n') Traceback (most recent call last): File "<stdin>", line 1, in ? IOError: [Errno 9] Bad file descriptor ```
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.open()](http://www.python.org/doc/2.5.2/lib/os-fd-ops.html) states: > To wrap a file descriptor in a "file > object", use fdopen(). So I tried: ``` >>> import tempfile >>> tup = tempfile.mkstemp() >>> import os >>> f = os.fdopen(tup[0]) >>> f.write('foo\n') Traceback (most recent call last): File "<stdin>", line 1, in ? IOError: [Errno 9] Bad file descriptor ```
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/) will give you all the modules in the language, but newcomers to Python are likely to find themselves saying "Oh, I didn't know I could have done it *this way* using Python!" unless the important features in the language are pointed out by the experienced developers. I'm **not** specifically looking for new modules in Python 2.6, but modules that can be found in this latest release.
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 processes, such as a `Queue` class and a `Lock` class which are each used just like those objects would be in multithreaded code, as well as some other classes for sharing memory between processes. You can find the documentation at <http://docs.python.org/library/multiprocessing.html>
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.contextmanager def remember_cwd(): curdir= os.getcwd() try: yield finally: os.chdir(curdir) ``` which can be used if needed at the function call time as: ``` print "getcwd before:", os.getcwd() with remember_cwd(): walk_around_the_filesystem() print "getcwd after:", os.getcwd() ``` It's a nice option to have. EDIT: I added error handling as suggested by codeape. Since my answer has been voted up, it's fair to offer a complete answer, all other issues aside.
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, **kwargs): cwd = os.getcwd() try: return function(*args, **kwargs) finally: os.chdir(cwd) return decorator ``` and as a context manager: ``` @contextlib.contextmanager def remember_cwd(): curdir = os.getcwd() try: yield finally: os.chdir(curdir) ```
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](http://lateral.netmanagers.com.ar/weblog/posts/BB963.html) from Roberto Alsina)
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 - all using only the standard library. # Python - Batteries Included If you don't feel like programming and would rather ask a question on stackoverflow.org instead, or (as suggested in the comments) left off the `homework` tag, well, here it is: ``` import smtplib import zipfile import tempfile from email import encoders from email.message import Message from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart def send_file_zipped(the_file, recipients, sender='[email protected]'): zf = tempfile.TemporaryFile(prefix='mail', suffix='.zip') zip = zipfile.ZipFile(zf, 'w') zip.write(the_file) zip.close() zf.seek(0) # Create the message themsg = MIMEMultipart() themsg['Subject'] = 'File %s' % the_file themsg['To'] = ', '.join(recipients) themsg['From'] = sender themsg.preamble = 'I am not using a MIME-aware mail reader.\n' msg = MIMEBase('application', 'zip') msg.set_payload(zf.read()) encoders.encode_base64(msg) msg.add_header('Content-Disposition', 'attachment', filename=the_file + '.zip') themsg.attach(msg) themsg = themsg.as_string() # send the message smtp = smtplib.SMTP() smtp.connect() smtp.sendmail(sender, recipients, themsg) smtp.close() ``` With this function, you can just do: ``` send_file_zipped('result.txt', ['[email protected]']) ``` You're welcome.
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 won't be able to sufficiently scale in terms of performance or capabilities. Requirements are: * Cross-platform (Linux, MacOS X, Windows) * Low complexity overhead * Plays well with wxpython (at least won't step on each other's toes unduly) * Interactivity. Detect when objects are clicked on, moused over, etc. Note that high performance isn't on the list, but the ability to handle ~100 bitmap objects on the screen would be good. Your thoughts?
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 mailing list about wxpython and pyglet being used together. It however does not offer selection of objects via mouse clicks - this you will have to handle yourself. Generally speaking for a 2D application this is not too difficult to do. [mactorii](https://github.com/freespace/mactorii) is an OS X application of mine written in pure python+pyglet, and has some basic animation (scrolling) and click detection. It doesn't use wxpython, but perhaps it will give you an idea of what is involved. Note however mactorii is using the old pyglet api, so the run loop I have in there is obsolete. I will get around to updating it one day... :P
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', 'win32api', 'win32con', 'win32event', 'win32file', 'win32pipe', 'win32process', 'win32security'] So how do I solve this problem? Thanks.
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 the options and experiment.
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 = models.IntegerField() ``` A Review is has several "scores", the overall\_score is the average of the scores. When a review or a score is saved, I need to recalculate the overall\_score average. Right now I'm using a overridden save method. Would there be any benefits to using Django's signal dispatcher?
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 generation of slugs from some text field in a model. That's an example of something which, if you needed to implement it for a number of models, would benefit from using a `pre_save` signal, where the signal handler could take the name of the slug field and the name of the field to generate the slug from. Once you have something like that in place, any enhanced functionality you put in place will also apply to all models - e.g. looking up the slug you're about to add for the type of model in question, to ensure uniqueness. Reusable applications often benefit from the use of signals - if the functionality they provide can be applied to any model, they generally (unless it's unavoidable) won't want users to have to directly modify their models in order to benefit from it. With [django-mptt](https://github.com/django-mptt/django-mptt/), for example, I used the `pre_save` signal to manage a set of fields which describe a tree structure for the model which is about to be created or updated and the `pre_delete` signal to remove tree structure details for the object being deleted and its entire sub-tree of objects before it and they are deleted. Due to the use of signals, users don't have to add or modify `save` or `delete` methods on their models to have this management done for them, they just have to let django-mptt know which models they want it to manage.
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](http://fishshell.com/) has a core written in C, but much of its functionality is implemented in itself. Unlike many rare shells, it can be used as your login shell. * [Hotwire](https://code.google.com/p/hotwire-shell/) deserves another mention. Its basic design appears to be "PowerShell in Python," but it also does some clever things with UI. The last release was in 2008. * [Zoidberg](http://www.pardus.nl/projects/zoidberg/) is written in Perl and uses Perl syntax. A nice-looking project, shame it seems to have stalled. * [Scsh](http://www.scsh.net/) would be a pain to use as a login shell (an example command from the docs: `(run/strings (find "." -name *.c -print))`), but it looks like a good "Perl in Scheme."
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 between columns would do it but the logic didn't work correctly. I found an [ActiveState page](http://code.activestate.com/recipes/302380/) that has a fairly complicated way of doing it but it's from 4 years ago. Is there an easy way to do it nowadays? --- **Edit** Here is the list that I want to use. ``` skills_defs = ["ACM:Aircraft Mechanic", "BC:Body Combat", "BIO:Biology", "CBE:Combat Engineer", "CHM:Chemistry", "CMP:Computers", "CRM:Combat Rifeman", "CVE:Civil Engineer", "DIS:Disguise", "ELC:Electronics","EQ:Equestrian", "FO:Forward Observer", "FOR:Forage", "FRG:Forgery", "FRM:Farming", "FSH:Fishing", "GEO:Geology", "GS:Gunsmith", "HW:Heavy Weapons", "IF:Indirect Fire", "INS:Instruction", "INT:Interrogation", "JP:Jet Pilot", "LB:Longbow", "LAP:Light Aircraft Pilot", "LCG:Large Caliber Gun", "LNG:Language", "LP:Lockpick", "MC:Melee Combat", "MCY:Motorcycle", "MEC:Mechanic", "MED:Medical", "MET:Meterology", "MNE:Mining Engineer", "MTL:Metallurgy", "MTN:Mountaineering", "NWH:Nuclear Warhead", "PAR:Parachute", "PST:Pistol", "RCN:Recon", "RWP:Rotary Wing Pilot", "SBH:Small Boat Handling","SCD:Scuba Diving", "SCR:Scrounging", "SWM:Swimming", "TW:Thrown Weapon", "TVD:Tracked Vehicle Driver", "WVD:Wheeled Vehicle Driver"] ``` I just want to output this list into a simple, 2 column format to reduce space. Ideally there should be a standard amount of space between the columns but I can work with it. ``` ACM:Aircraft Mechanic BC:Body Combat BIO:Biology CBE:Combat Engineer CHM:Chemistry CMP:Computers CRM:Combat Rifeman CVE:Civil Engineer DIS:Disguise ELC:Electronics EQ:Equestrian FO:Forward Observer FOR:Forage FRG:Forgery FRM:Farming FSH:Fishing GEO:Geology GS:Gunsmith HW:Heavy Weapons IF:Indirect Fire INS:Instruction INT:Interrogation JP:Jet Pilot LB:Longbow LAP:Light Aircraft Pilot LCG:Large Caliber Gun LNG:Language LP:Lockpick MC:Melee Combat MCY:Motorcycle MEC:Mechanic MED:Medical MET:Meterology MNE:Mining Engineer MTL:Metallurgy MTN:Mountaineering NWH:Nuclear Warhead PAR:Parachute PST:Pistol RCN:Recon RWP:Rotary Wing Pilot SBH:Small Boat Handling SCD:Scuba Diving SCR:Scrounging SWM:Swimming TW:Thrown Weapon TVD:Tracked Vehicle Driver WVD:Wheeled Vehicle Driver ```
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 B C D E F G H I J ... ``` Oops... got caught by S.Lott (thank you). A more general solution, handles any number of columns and odd lists. Slightly modified from [S.lott](http://stackoverflow.com/questions/171662/formatting-a-list-of-text-into-columns#173823), using generators to save space. ``` def fmtcols(mylist, cols): lines = ("\t".join(mylist[i:i+cols]) for i in xrange(0,len(mylist),cols)) return '\n'.join(lines) ```
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. I've an generator that generates factor in this way: (factor1, multiplicity1) (factor2, multiplicity2) (factor3, multiplicity3) and so on... i.e. the output of ``` for i in factorGenerator(100): print i ``` is: ``` (2, 2) (5, 2) ``` I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make ``` for i in divisorGen(100): print i ``` output this: ``` 1 2 4 5 10 20 25 50 100 ``` --- **UPDATE:** Many thanks to Greg Hewgill and his "smart way" :) Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D **UPDATE 2:** Stop saying this is a duplicate of [this](http://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number) post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers.
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 guaranteed answers. This fact is used by encryption algorithms and the like to help secure them. If someone were to solve this problem, most if not all of our current 'secure' communication would be rendered insecure. Python code: ``` import math def divisorGenerator(n): large_divisors = [] for i in xrange(1, int(math.sqrt(n) + 1)): if n % i == 0: yield i if i*i != n: large_divisors.append(n / i) for divisor in reversed(large_divisors): yield divisor print list(divisorGenerator(100)) ``` Which should output a list like: ``` [1, 2, 4, 5, 10, 20, 25, 50, 100] ```
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. I've an generator that generates factor in this way: (factor1, multiplicity1) (factor2, multiplicity2) (factor3, multiplicity3) and so on... i.e. the output of ``` for i in factorGenerator(100): print i ``` is: ``` (2, 2) (5, 2) ``` I don't know how much is this useful for what I want to do (I coded it for other problems), anyway I'd like a smarter way to make ``` for i in divisorGen(100): print i ``` output this: ``` 1 2 4 5 10 20 25 50 100 ``` --- **UPDATE:** Many thanks to Greg Hewgill and his "smart way" :) Calculating all divisors of 100000000 took 0.01s with his way against the 39s that the dumb way took on my machine, very cool :D **UPDATE 2:** Stop saying this is a duplicate of [this](http://stackoverflow.com/questions/110344/algorithm-to-calculate-the-number-of-divisors-of-a-given-number) post. Calculating the number of divisor of a given number doesn't need to calculate all the divisors. It's a different problem, if you think it's not then look for "Divisor function" on wikipedia. Read the questions and the answer before posting, if you do not understand what is the topic just don't add not useful and already given answers.
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 while True: f[i] += 1 if f[i] <= factors[i][1]: break f[i] = 0 i += 1 if i >= nfactors: return ``` The overall efficiency of this algorithm will depend entirely on the efficiency of the factorGenerator.
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 app. Does such an OpenID dev server exist? Is this the best way to go about it?
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 the provider does a client side redirect.
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 app. Does such an OpenID dev server exist? Is this the best way to go about it?
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/examples/server/).
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 you already started or plan on starting soon? Or do you plan on waiting until the final version comes out to get into full swing?
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 need Python 3.0 support", and has a good reason for it aside from the fact that 3.0 looks shiny. 2. **Wait until our dependencies have migrated.** A large system like Twisted has a number of dependencies. For starters, ours include: * [Zope Interface](http://www.zope.org/Products/%5AopeInterface) * [PyCrypto](http://www.dlitz.net/software/pycrypto/) * [PyOpenSSL](https://launchpad.net/pyopenssl/) * [pywin32](http://sourceforge.net/projects/pywin32/) * [PyGTK](http://www.pygtk.org/) (though this dependency is sadly very light right now, by the time migration rolls around, I hope Twisted will have more GUI tools) * [pyasn1](http://pyasn1.sourceforge.net/) * [PyPAM](http://www.pangalactic.org/PyPAM/) * [gmpy](http://gmpy.sourceforge.net/) Some of these projects have their own array of dependencies so we'll have to wait for those as well. 3. **Wait until somebody cares enough *to help*.** There are, charitably, 5 people who work on Twisted - and I say "charitably" because that's counting me, and I haven't committed in months. We have [over 1000 open tickets](http://twistedmatrix.com/trac/report/1) right now, and it would be nice to actually fix some of those — fix bugs, add features, and generally make Twisted a better product in its own right — before spending time on getting it ported over to a substantially new version of the language. This potentially includes [sponsors](http://twistedmatrix.com/trac/wiki/TwistedSoftwareFoundation) caring enough to pay for us to do it, but I hope that there will be an influx of volunteers who care about 3.0 support and want to help move the community forward. 4. **Follow Guido's advice.** This means ***[we will not change our API incompatibly](http://www.artima.com/weblogs/viewpost.jsp?thread=227041)***, and we will follow the [transitional development guidelines](http://www.artima.com/weblogs/viewpost.jsp?thread=208549) that Guido posted last year. That starts with having unit tests, and running [the 2to3 conversion tool](http://docs.python.org/library/2to3.html) over the Twisted codebase. 5. **Report bugs against, and file patches for, the 2to3 tool**. When we get to the point where we're actually using it, I anticipate that there will be a lot of problems with running `2to3` in the future. Running it over Twisted right now takes an extremely long time and (last I checked, which was quite a while ago) can't parse a few of the files in the Twisted repository, so the resulting output won't import. I think there will have to be a fair amount of success stories from small projects and a lot of hammering on the tool before it will actually work for us. However, the Python development team has been very helpful in responding to our bug reports, and early responses to these problems have been encouraging, so I expect that all of these issues will be fixed in time. 6. **Maintain 2.x compatibility for several years.** Right now, Twisted supports python 2.3 to 2.5. Currently, we're working on 2.6 support (which we'll obviously have to finish before 3.0!). Our plan is to we revise our supported versions of Python based on the long-term supported versions of [Ubuntu](http://en.wikipedia.org/wiki/Ubuntu) - release 8.04, which includes Python 2.5, will be supported until 2013. According to Guido's advice we will need to drop support for 2.5 in order to support 3.0, but I am hoping we can find a way around that (we are pretty creative with version-compatibility hacks). So, we are planning to support Python 2.5 until at least 2013. In two years, Ubuntu will release another long-term supported version of Ubuntu: if they still exist, and stay on schedule, that will be 10.04. Personally I am guessing that this will ship with Python 2.x, perhaps python 2.8, as `/usr/bin/python`, because there is a huge amount of Python software packaged with the distribution and it will take a long time to update it all. So, five years from *then*, in 2015, we can start looking at dropping 2.x support. During this period, we will continue to follow Guido's advice about migration: running 2to3 over our 2.x codebase, and modifying the 2.x codebase to keep its tests passing in both versions. The upshot of this is that Python 3.x will not be a *source* language for Twisted until well after my 35th birthday — it will be a target runtime (and a set of guidelines and restrictions) for my python 2.x code. I expect to be writing programs in Python 2.x for the next ten years or so. So, that's the plan. I'm hoping that it ends up looking laughably conservative in a year or so; that the 3.x transition is easy as pie, and everyone rapidly upgrades. Other things could happen, too: the 2.x and 3.x branches could converge, someone might end up writing a `3to2`, or another runtime (PyPy comes to mind) might allow for running 2.x and 3.x code in the same process directly, making our conversion process easier. For the time being, however, we're assuming that, for many years, we will have people with large codebases they're maintaining (or people writing new code who want to use *other* libraries which have not yet been migrated) who still want new features and bug fixes in Twisted. Pretty soon I expect we will also have bleeding-edge users that want to use Twisted on python 3. I'd like to provide all of those people with a positive experience for as long as possible.
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 you already started or plan on starting soon? Or do you plan on waiting until the final version comes out to get into full swing?
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 redirects imports and functions to their respective locations (as well as unifying other incompatible changes). ### Obvious advantages: * No need for separate branches for Python 2 and Python 3 * No conversion tools, such as 2to3.
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 messages being sent. I believe encryption is the sollution to that. Since the nodes are not maintaining a session and communication must work in a stateless, connectionless fashion, I am guessing that asymmetric encryption is ruled out. So here is what I would like to do: * messages are sent as UDP datagrams * each message contains a timestamp to make messages differ (counter replay attacks) * each message is encrypted with a shared secret symmetric key and sent over the network * other end can decrypt with shared secret symmetric key Keys can obviously be compromised by compromising any single node. At the same time, in this scenario, access to any single compromised node reveals all interesting information anyway, so the key is not the weakest link. What cypher should I use for this encryption? What key length? I would prefer to use something supported by [ezPyCrypto](http://www.freenet.org.nz/ezPyCrypto/). Assuming, as most point out, I go with AES. What modes should I be using? I couldn't figure out how to do it with ezPyCrypto, [PyCrypto](http://www.dlitz.net/software/pycrypto/) seems to be hung on a moderator swap and googles [keyczar](http://www.keyczar.org/) does not explain how to set this up - I fear if I don't just *get* it, then I run a risk of introducing insecurity. So barebones would be better. [This guy](http://www.josh-davis.org/pythonAES) claims to have a nice module for AES in python, but he also asserts that this is his first python project - Allthough he is probably loads smarter than I, maybe he got tripped up? **EDIT:** I moved the search for the python implementation to [another question](http://stackoverflow.com/questions/172486/what-pure-python-library-to-use-for-aes-256-encryption) to stop clobber...
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're using strong cipher suites, as appropriate to the protocol. If neither SSL/TLS or IPSec fits your scenario/environment, your next choice should be [AES](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard) (aka Rijndael). Use keys at least 256 bits long, if you want you can go longer. Keys should be randomly generated, by a cryptographically secure random number generator (and not a simple rnd() call). Set the cipher mode to [CBC](http://en.wikipedia.org/wiki/Cipher_block_chaining). Use PKCS7 padding. Generate a unique, crypto-random Initialization Vector (IV). Don't forget to properly protect and manage your keys, and maybe consider periodic key rotations. Depending on your data, you may want to also implement a keyed hash, to provide for message integrity - use [SHA-256](http://en.wikipedia.org/wiki/SHA-256) for hashing. There are also rare situations where you may want to go with a stream cipher, but thats usually more complicated and I would recommend you avoid it your first time out. Now, I'm not familiar ezpycrypto (or really python in general), and cant really state that it supports all this; but everything here is pretty standard and recommended best practice, if your crypto library doesnt support it, I would suggest finding one that does ;-).
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 messages being sent. I believe encryption is the sollution to that. Since the nodes are not maintaining a session and communication must work in a stateless, connectionless fashion, I am guessing that asymmetric encryption is ruled out. So here is what I would like to do: * messages are sent as UDP datagrams * each message contains a timestamp to make messages differ (counter replay attacks) * each message is encrypted with a shared secret symmetric key and sent over the network * other end can decrypt with shared secret symmetric key Keys can obviously be compromised by compromising any single node. At the same time, in this scenario, access to any single compromised node reveals all interesting information anyway, so the key is not the weakest link. What cypher should I use for this encryption? What key length? I would prefer to use something supported by [ezPyCrypto](http://www.freenet.org.nz/ezPyCrypto/). Assuming, as most point out, I go with AES. What modes should I be using? I couldn't figure out how to do it with ezPyCrypto, [PyCrypto](http://www.dlitz.net/software/pycrypto/) seems to be hung on a moderator swap and googles [keyczar](http://www.keyczar.org/) does not explain how to set this up - I fear if I don't just *get* it, then I run a risk of introducing insecurity. So barebones would be better. [This guy](http://www.josh-davis.org/pythonAES) claims to have a nice module for AES in python, but he also asserts that this is his first python project - Allthough he is probably loads smarter than I, maybe he got tripped up? **EDIT:** I moved the search for the python implementation to [another question](http://stackoverflow.com/questions/172486/what-pure-python-library-to-use-for-aes-256-encryption) to stop clobber...
> 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 usually very hard). If you just slap a cipher on your streaming data, without careful key management and other understanding of the subtleties of cryptographic systems, you will likely open yourself up to all kinds of vulnerabilities. For example, the scheme you describe will be vulnerable to [man-in-the-middle attacks](http://wikipedia.org/wiki/Man-in-the-middle_attack) without some specific plan for key distribution among the nodes, and may be vulnerable to [chosen-plaintext](http://wikipedia.org/wiki/Chosen-plaintext_attack) and/or [known-plaintext attacks](http://wikipedia.org/wiki/Known-plaintext_attack) depending on how your distributed system communicates with the outside world, and the exact choice of cipher and [mode of operation](http://wikipedia.org/wiki/Block_cipher_mode). So... you will have to read up on crypto in general before you can use it securely.
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 each line to include the break sequence (CR,LF,CRLF), use the `splitlines` method with a `True` argument: ``` inputString.splitlines(True) # --> ['Line 1\n', 'Line 2\n', 'Line 3'] ```
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-break (ASCII decimal code 10), independently from the platform where you run it. However, [the linebreak representation is platform-dependent](https://en.wikipedia.org/wiki/Newline#Representations). On Windows, `\n` is two characters, `CR` and `LF` (ASCII decimal codes 13 and 10, AKA `\r` and `\n`), while on any modern Unix (including OS X), it's the single character `LF`. `print`, for example, works correctly even if you have a string with line endings that don't match your platform: ``` >>> print " a \n b \r\n c " a b c ``` However, explicitly splitting on "\n", will yield platform-dependent behaviour: ``` >>> " a \n b \r\n c ".split("\n") [' a ', ' b \r', ' c '] ``` Even if you use `os.linesep`, it will only split according to the newline separator on your platform, and will fail if you're processing text created in other platforms, or with a bare `\n`: ``` >>> " a \n b \r\n c ".split(os.linesep) [' a \n b ', ' c '] ``` `splitlines` solves all these problems: ``` >>> " a \n b \r\n c ".splitlines() [' a ', ' b ', ' c '] ``` --- [Reading files in text mode](https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files) partially mitigates the newline representation problem, as it converts Python's `\n` into the platform's newline representation. However, text mode only exists on Windows. On Unix systems, all files are opened in binary mode, so `split('\n')` on a Windows file will lead to undesired behaviour. Also, it's not unusual to process strings with potentially different newlines from other sources, such as from a socket.
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 are some good ways to greatly improve performance? For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?
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't always successful, but in general it works. It can be done by hand, but obviously is tedious. You said apart from in-code optimization, so I won't delve into this, but keep your mind open for typical mistakes (`for i in range(10000000)` comes to mind) that people do.
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 are some good ways to greatly improve performance? For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?
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 as c functions for python.
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 are some good ways to greatly improve performance? For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?
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 non-obvious slowdown are string concatenation and generators. Since Python's strings are immutable, doing something like this: ``` result = u"" for item in my_list: result += unicode (item) ``` will copy the *entire* string twice per iteration. This has been well-covered, and the solution is to use `"".join`: ``` result = "".join (unicode (item) for item in my_list) ``` Generators are another culprit. They're very easy to use and can simplify some tasks enormously, but a poorly-applied generator will be much slower than simply appending items to a list and returning the list. Finally, **don't be afraid to rewrite bits in C!** Python, as a dynamic high-level language, is simply not capable of matching C's speed. If there's one function that you can't optimize any more in Python, consider extracting it to an extension module. My favorite technique for this is to maintain both Python and C versions of a module. The Python version is written to be as clear and obvious as possible -- any bugs should be easy to diagnose and fix. Write your tests against this module. Then write the C version, and test it. Its behavior should in all cases equal that of the Python implementation -- if they differ, it should be very easy to figure out which is wrong and correct the problem.
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 are some good ways to greatly improve performance? For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?
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 more useful rules are in the [General Rules for Optimization](http://www.cs.cmu.edu/~jch/java/rules.html). 1. Don't optimize as you go. First get it right. Then get it fast. Optimizing a wrong program is still wrong. 2. Remember the 80/20 rule. 3. Always run "before" and "after" benchmarks. Otherwise, you won't know if you've found the 80%. 4. Use the right algorithms and data structures. This rule should be first. Nothing matters as much as algorithm and data structure. **Bottom Line** You can't prevent or avoid the "optimize this program" effort. It's part of the job. You have to plan for it and do it carefully, just like the design, code and test activities.
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 are some good ways to greatly improve performance? For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?
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.html> There are limitations though, please see: <http://tinyurl.com/shedskin-limitations>
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 are some good ways to greatly improve performance? For the first question, imagine you are handed a decently written project and you need to improve performance, but you can't seem to get much of a gain through refactoring/optimization. What would you do to speed it up in this case short of rewriting it in something like C?
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 wont. The latter is preferable * Beware of code that first constructs a big data structure followed by its consumation. Think the difference between range and xrange. In general it is often worth thinking about memory usage of the program. Using generators can sometimes bring O(n) memory use down to O(1). * Python is generally non-optimizing. Hoist invariant code out of loops, eliminate common subexpressions where possible in tight loops. * If something is expensive, then precompute or memoize it. Regular expressions can be compiled for instance. * Need to crunch numbers? You might want to check `numpy` out. * Many python programs are slow because they are bound by disk I/O or database access. Make sure you have something worthwhile to do while you wait on the data to arrive rather than just blocking. A weapon could be something like the `Twisted` framework. * Note that many crucial data-processing libraries have C-versions, be it XML, JSON or whatnot. They are often considerably faster than the Python interpreter. If all of the above fails for profiled and measured code, then begin thinking about the C-rewrite path.
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 must. We use Apache 2.2 but will be switching over to Nginx once it goes live. What are my options? Anyone had experience with this?
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 parts. > > Save a Word 2007 document, containing > text, pictures, and other elements, as > a .docx file. > > Add a .zip extension to the end of the > file name. > > Double-click the file. It will open in > the ZIP application. You can see the > parts that comprise the file. > > Extract the parts to the folder that > you created previously. The other file formats are roughly similar. I don't know of any open source libraries for interacting with them as yet - but depending on your exact requirements, it doesn't look too difficult to read and write simple documents. Certainly it should be a lot easier than with the older formats. If you need to read the older formats, OpenOffice has an API and can read and write Office 2003 and older documents with more or less success.
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 situation I am trying to handle is one where our test framework has detected that it is configured to point to a non-test database. In this case I want to exit and prevent any further tests from being run. Of course since unittest traps the SystemExit and continues happily on it's way, it is thwarting me. The only option I have thought of so far is using ctypes or something similar to call exit(3) directly but this seems like a pretty fugly hack for something that should be really simple.
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 in this situation. The argument is the exit code that will be returned by the process.
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 situation I am trying to handle is one where our test framework has detected that it is configured to point to a non-test database. In this case I want to exit and prevent any further tests from being run. Of course since unittest traps the SystemExit and continues happily on it's way, it is thwarting me. The only option I have thought of so far is using ctypes or something similar to call exit(3) directly but this seems like a pretty fugly hack for something that should be really simple.
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 ***be the outer level yourself!*** Wrap your main code in a try/except block, catch SystemExit, and call os.\_exit there, *and **only** there!* This way you may call `sys.exit` normally anywhere in the code, let it bubble out to the top level, gracefully closing all files and running all cleanups, and *then* calling os.\_exit. You can even choose which exits are the "emergency" ones. The code below is an example of such approach: ``` import sys, os EMERGENCY = 255 # can be any number actually try: # wrap your whole code here ... # ... some code if x: sys.exit() # ... some more code if y: sys.exit(EMERGENCY) # use only for emergency exits # ... except SystemExit as e: if e.code != EMERGENCY: raise # normal exit, let unittest catch it else: os._exit(EMERGENCY) # try to stop *that*, sucker! ```
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 variable, Python is treating the "ithTag" as a string instead of a variable. I'm confused, it is kind of hard to google these kind of specific questions. I hope I worded the title of this question correctly, Thanks!
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 variable, Python is treating the "ithTag" as a string instead of a variable. I'm confused, it is kind of hard to google these kind of specific questions. I hope I worded the title of this question correctly, Thanks!
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 answer, slightly modified: ``` tagDict.update((t, i) for (i,t) in enumerate(tag)) ``` )
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 variable, Python is treating the "ithTag" as a string instead of a variable. I'm confused, it is kind of hard to google these kind of specific questions. I hope I worded the title of this question correctly, Thanks!
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 developing on Windows Mobile, I have already decided not to do that so will mark those answers down.
## 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 very neat py2sis utility which converts your py apps to portabble sis apps that can be installed on any Sumbian phones. The ease of use of Python scripting laanguage and a good set of warapped APIs for Mobile functions just enables you to do anything very neatly and quickly. The latest Video and Camera APIs let you do neary everything that can be done with the phone. I'd suggest you few very good resources to start with 1. [Forum Nokia](http://www.forum.nokia.com/Resources_and_Information/Tools/Runtimes/Python_for_S60/) 2. [Nokia OpenSource Resource center](http://opensource.nokia.com/projects/pythonfors60/) 3. [A very good tutorial (for beginners)](http://www.mobilenin.com/pys60/menu.htm) Just access these, download the Emulator, and TAKE OFF for a ride with PyS60. M sure you'll love it. P.S. : as the post is so old, I believe u must already be either loving it or finished off with it. But I just cudn't resist answering. :)
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, self.OnClick, b) def OnClick(self, event): self.log.write("Click! (%d)\n" % event.GetId()) ``` But is it possible to have another argument passed to the method? Such that the method can tell if more than one widget is calling it but still return the same value? It would greatly reduce copy & pasting the same code but with different callers.
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! (%d)\n" % event.GetId()) ``` If you're out to reduce the amount of code to type, you might also try a little automatism like: ``` class foo(whateverwxobject): def better_bind(self, type, instance, handler, *args, **kwargs): self.Bind(type, lambda event: handler(event, *args, **kwargs), instance) def __init__(self): self.better_bind(wx.EVT_BUTTON, b, self.OnClick, 'somevalue') ```
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, self.OnClick, b) def OnClick(self, event): self.log.write("Click! (%d)\n" % event.GetId()) ``` But is it possible to have another argument passed to the method? Such that the method can tell if more than one widget is calling it but still return the same value? It would greatly reduce copy & pasting the same code but with different callers.
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.Button(self, 10, "Default Button", (20, 20)) b.Bind(wx.EVT_BUTTON, self.getOnClick('my additional data')) ```
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 after all kids are collected. What is the best way to work it out? Thanks.
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`, and cull the returned values from the list of children, instead of waiting on each one in turn (as here). If you set up an `alarm` with a `SIGALRM` handler, you can terminate the waiting after a specified delay. This is all standard UNIX stuff, not Python-specific...
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 elements. ``` def Comment(text=None): element = Element(Comment) element.text = text return element ``` Then in the `_write` function of ElementTree that actually outputs the XML, there's a special case handling for comments: ``` if tag is Comment: file.write("<!-- %s -->" % _escape_cdata(node.text, encoding)) ``` In order to support CDATA sections, I create a factory function called `CDATA`, extended the ElementTree class and changed the `_write` function to handle the CDATA elements. This still doesn't help if you want to parse an XML with CDATA sections and then output it again with the CDATA sections, but it at least allows you to create XMLs with CDATA sections programmatically, which is what I needed to do. The implementation seems to work with both ElementTree and cElementTree. ``` import elementtree.ElementTree as etree #~ import cElementTree as etree def CDATA(text=None): element = etree.Element(CDATA) element.text = text return element class ElementTreeCDATA(etree.ElementTree): def _write(self, file, node, encoding, namespaces): if node.tag is CDATA: text = node.text.encode(encoding) file.write("\n<![CDATA[%s]]>\n" % text) else: etree.ElementTree._write(self, file, node, encoding, namespaces) if __name__ == "__main__": import sys text = """ <?xml version='1.0' encoding='utf-8'?> <text> This is just some sample text. </text> """ e = etree.Element("data") cdata = CDATA(text) e.append(cdata) et = ElementTreeCDATA(e) et.write(sys.stdout, "utf-8") ```
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): if elem.tag == '![CDATA[': write("\n<%s%s]]>\n" % ( elem.tag, elem.text)) return return etree._original_serialize_xml( write, elem, qnames, namespaces) etree._serialize_xml = etree._serialize['xml'] = _serialize_xml if __name__ == "__main__": import sys text = """ <?xml version='1.0' encoding='utf-8'?> <text> This is just some sample text. </text> """ e = etree.Element("data") cdata = CDATA(text) e.append(cdata) et = etree.ElementTree(e) et.write(sys.stdout.buffer.raw, "utf-8") ```
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 idea of what happens to Unicode strings that are translated to ASCII: <http://www.reportlab.com/i18n/python_unicode_tutorial.html> **Here's a useful quote from the site:** > Python 1.6 also gets a "unicode" > built-in function, to which you can > specify the encoding: ``` > >>> unicode('hello') u'hello' > >>> unicode('hello', 'ascii') u'hello' > >>> unicode('hello', 'iso-8859-1') u'hello' > >>> ``` > All three of these return the same > thing, since the characters in 'Hello' > are common to all three encodings. > > Now let's encode something with a > European accent, which is outside of > ASCII. What you see at a console may > depend on your operating system > locale; Windows lets me type in > ISO-Latin-1. ``` > >>> a = unicode('André','latin-1') > >>> a u'Andr\202' ``` > If you can't type an acute letter e, > you can enter the string 'Andr\202', > which is unambiguous. > > Unicode supports all the common > operations such as iteration and > splitting. We won't run over them > here.
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 without direct corresponding ASCII values, e.g. ``` >>> title = u"Klüft skräms inför på fédéral électoral große" ``` is typically converted to ``` Klft skrms infr p fdral lectoral groe ``` which is pretty wrong. However, using the `unicodedata` module, the result can be much closer to the original text: ``` >>> import unicodedata >>> unicodedata.normalize('NFKD', title).encode('ascii','ignore') 'Kluft skrams infor pa federal electoral groe' ```
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 something obvious?
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 something obvious?
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 are not part of the built-in types. I'd say use the arrays module only if you really need it, in all other cases stick with lists.
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 something obvious?
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 without hassle, they are the way to go. But they use **a lot more space than C arrays**. The `array.array` type, on the other hand, is just a thin wrapper on C arrays. It can hold only homogeneous data, all of the same type, and so it uses only `sizeof(one object) * length` bytes of memory. Mostly, you should use it when you need to expose a C array to an extension or a system call (for example, `ioctl` or `fctnl`). It's also a good way to represent a **mutable** string (`array('B', bytes)`) until that actually becomes available in Python 3.0. However, if you want to do **math** on a homogeneous array of numeric data, then you're much better off using NumPy, which can automatically vectorize operations on complex multi-dimensional arrays. **To make a long story short**: `array.array` is useful when you need a homogeneous C array of data for reasons *other than doing math*.
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 something obvious?
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 question about performance: Arrays are more efficient than lists for some uses. If you need to allocate an array that you KNOW will not change, then arrays can be faster and use less memory. GvR has an [optimization anecdote](http://www.python.org/doc/essays/list2str/) in which the array module comes out to be the winner (long read, but worth it). On the other hand, part of the reason why lists eat up more memory than arrays is because python will allocate a few extra elements when all allocated elements get used. This means that appending items to lists is faster. So if you plan on adding items, a list is the way to go. TL;DR I'd only use an array if you had an exceptional optimization need or you need to interface with C code (and can't use [pyrex](http://www.cosc.canterbury.ac.nz/greg.ewing/python/Pyrex/)).
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 method you are looking for.
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) except ValueError: break return indices all_indices("foo", ["foo","bar","baz","foo"]) ```
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 except ValueError: return None ```
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 quietly ``` Why write a function with exception handling if the language provides the methods to do what you want itself?
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 first occurrence, while enumerate returns all occurrences. As a list comprehension: ``` [i for i, j in enumerate(['foo', 'bar', 'baz']) if j == 'foo'] ``` --- Here's also another small solution with [`itertools.count()`](http://docs.python.org/2/library/itertools.html#itertools.count) (which is pretty much the same approach as enumerate): ``` from itertools import izip as zip, count # izip for maximum efficiency [i for i, j in zip(count(), ['foo', 'bar', 'baz']) if j == 'foo'] ``` This is more efficient for larger lists than using `enumerate()`: ``` $ python -m timeit -s "from itertools import izip as zip, count" "[i for i, j in zip(count(), ['foo', 'bar', 'baz']*500) if j == 'foo']" 10000 loops, best of 3: 174 usec per loop $ python -m timeit "[i for i, j in enumerate(['foo', 'bar', 'baz']*500) if j == 'foo']" 10000 loops, best of 3: 196 usec per loop ```
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 conditions are met, I figure that the easiest way to alert the user would be to produce a pop-up, as it needs to be handled immediately, and other options such as just logging, or sending an email are not efficient enough.
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/ms645505%28v=vs.85%29.aspx) for other options.
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('failed' + address, 'down') ``` but the alert function is called even when that connection should have worked.
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)) # originally, it was # except Exception, e: # but this syntax is not supported anymore. except Exception as e: print("something's wrong with %s:%d. Exception is %s" % (address, port, e)) finally: s.close() ``` Always try to see what kind of exception is what you're catching in a try-except loop. You can check what types of exceptions in a socket module represent what kind of errors (timeout, unable to resolve address, etc) and make separate `except` statement for each one of them - this way you'll be able to react differently for different kind of problems.
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('failed' + address, 'down') ``` but the alert function is called even when that connection should have worked.
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) result = s.connect_ex((host, port)) s.close() if result: print "problem with socket!" else: print "everything it's ok!" ```
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 provided, a simpler datastructure would be better: ``` shows = {1: 'Sesaeme Street', 2:'Dora the Explorer'} ```