title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
Finding a public facing IP address in Python?
166,545
<p>How can I find the public facing IP for my net work in Python?</p>
14
2008-10-03T12:20:07Z
1,794,595
<p>One way is , you can make a request to the page at</p> <p><a href="http://www.biranchi.com/ip.php" rel="nofollow">http://www.biranchi.com/ip.php</a></p> <p>it returns the IP address of your system</p>
4
2009-11-25T04:19:57Z
[ "python", "ip-address" ]
Finding a public facing IP address in Python?
166,545
<p>How can I find the public facing IP for my net work in Python?</p>
14
2008-10-03T12:20:07Z
10,843,037
<p>All of the answers I see above would report the IP address of any web proxy in use, not necessarily the public facing IP address of your system (anything not being run through a web proxy may have an entirely different IP address).</p>
1
2012-06-01T00:35:58Z
[ "python", "ip-address" ]
Finding a public facing IP address in Python?
166,545
<p>How can I find the public facing IP for my net work in Python?</p>
14
2008-10-03T12:20:07Z
16,304,401
<p>If you don't mind expletives then try:</p> <p><a href="http://wtfismyip.com/json" rel="nofollow">http://wtfismyip.com/json</a></p> <p>Bind it up in the usual urllib stuff as others have shown.</p> <p>There's also:</p> <p><a href="http://www.networksecuritytoolkit.org/nst/tools/ip.php" rel="nofollow">http://www.networksecuritytoolkit.org/nst/tools/ip.php</a></p>
3
2013-04-30T16:10:35Z
[ "python", "ip-address" ]
Finding a public facing IP address in Python?
166,545
<p>How can I find the public facing IP for my net work in Python?</p>
14
2008-10-03T12:20:07Z
36,406,616
<pre><code>import urllib2 text = urllib2.urlopen('http://www.whatismyip.org').read() urlRE=re.findall('[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}',text) urlRE ['146.148.123.123'] </code></pre> <p>Try putting whatever 'findmyipsite' you can find into a list and iterating through them for comparison. This one seems to work well.</p>
1
2016-04-04T15:20:27Z
[ "python", "ip-address" ]
Finding a public facing IP address in Python?
166,545
<p>How can I find the public facing IP for my net work in Python?</p>
14
2008-10-03T12:20:07Z
38,436,633
<p><a href="https://api.ipify.org/?format=json" rel="nofollow">https://api.ipify.org/?format=json</a> is pretty straight forward</p> <p>can be parsed by just running <code>requests.get("https://api.ipify.org/?format=json").json()['ip']</code></p>
0
2016-07-18T12:23:19Z
[ "python", "ip-address" ]
Finding a public facing IP address in Python?
166,545
<p>How can I find the public facing IP for my net work in Python?</p>
14
2008-10-03T12:20:07Z
38,445,997
<p>This is simple as</p> <pre><code>&gt;&gt;&gt; import urllib &gt;&gt;&gt; urllib.urlopen('http://icanhazip.com/').read().strip('\n') 'xx.xx.xx.xx' </code></pre>
0
2016-07-18T21:07:25Z
[ "python", "ip-address" ]
Calling Python in PHP
166,944
<p>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.</p> <p>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.</p> <p>Any better ideas? Thanks in advance!</p>
55
2008-10-03T13:44:41Z
167,200
<p>Depending on what you are doing, <a href="http://php.net/manual/en/function.system.php">system()</a> or <a href="http://php.net/manual/en/function.popen.php">popen()</a> 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 <a href="http://us.php.net/manual/en/function.proc-open.php">proc_open()</a>, 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.</p> <p>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.</p> <p><a href="http://www.php.net/manual/en/function.escapeshellarg.php">escapeshellarg()</a> and <a href="http://www.php.net/manual/en/function.escapeshellcmd.php">escapeshellcmd()</a> can help with this, but personally I like to remove everything that isn't a known good character, using something like</p> <pre><code>preg_replace('/[^a-zA-Z0-9]/', '', $str) </code></pre>
82
2008-10-03T14:40:12Z
[ "php", "python" ]
Calling Python in PHP
166,944
<p>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.</p> <p>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.</p> <p>Any better ideas? Thanks in advance!</p>
55
2008-10-03T13:44:41Z
167,205
<p>I do this kind of thing all the time for quick-and-dirty scripts. It's quite common to have a CGI or PHP script that just uses system/popen to call some external program.</p> <p>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.</p>
7
2008-10-03T14:40:38Z
[ "php", "python" ]
Calling Python in PHP
166,944
<p>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.</p> <p>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.</p> <p>Any better ideas? Thanks in advance!</p>
55
2008-10-03T13:44:41Z
168,678
<p>There's also a PHP extension: <a href="http://www.csh.rit.edu/~jon/projects/pip/">Pip - Python in PHP</a>, which I've never tried but had it bookmarked for just such an occasion</p>
15
2008-10-03T20:13:22Z
[ "php", "python" ]
Calling Python in PHP
166,944
<p>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.</p> <p>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.</p> <p>Any better ideas? Thanks in advance!</p>
55
2008-10-03T13:44:41Z
11,601,572
<p>You can run a python script via php, and outputs on browser.</p> <p>Basically you have to call the python script this way:</p> <pre><code>$command = "python /path/to/python_script.py 2&gt;&amp;1"; $pid = popen( $command,"r"); while( !feof( $pid ) ) { echo fread($pid, 256); flush(); ob_flush(); usleep(100000); } pclose($pid); </code></pre> <p>Note: if you run any time.sleep() in you python code, it will not outputs the results on browser.</p> <p>For full codes working, visit <a href="http://blog.idealmind.com.br/php/how-to-execute-python-script-from-php-and-show-output-on-browser/">How to execute python script from php and show output on browser</a></p>
8
2012-07-22T15:33:38Z
[ "php", "python" ]
Calling Python in PHP
166,944
<p>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.</p> <p>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.</p> <p>Any better ideas? Thanks in advance!</p>
55
2008-10-03T13:44:41Z
18,921,091
<p>The backquote operator will also allow you to run python scripts using similar syntax to above</p> <p>In a python file called python.py:</p> <pre><code>hello = "hello" world = "world" print hello + " " + world </code></pre> <p>In a php file called python.php:</p> <pre><code>$python = `python python.py`; echo $python; </code></pre>
12
2013-09-20T16:01:27Z
[ "php", "python" ]
Calling Python in PHP
166,944
<p>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.</p> <p>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.</p> <p>Any better ideas? Thanks in advance!</p>
55
2008-10-03T13:44:41Z
37,870,761
<p>If you want to execute your Python script in PHP, it's necessary to do this command in your php script:</p> <pre><code>exec('your script python.py') </code></pre>
-3
2016-06-16T23:03:45Z
[ "php", "python" ]
Removing a subset of a dict from within a list
167,120
<p>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:</p> <pre><code>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] </code></pre> <p>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.</p> <p>This method is annoying because it requires two loops and an extra array. Is there a cleaner and more efficient way of doing this.</p>
5
2008-10-03T14:24:35Z
167,134
<p>Consider <a href="http://docs.python.org/library/stdtypes.html#dict.pop" rel="nofollow">dict.pop</a>:</p> <pre><code>for key in exclusion: a.pop(key, None) </code></pre> <p>The <code>None</code> keeps pop from raising an exception when <code>key</code> isn't a key.</p>
11
2008-10-03T14:28:29Z
[ "python", "list", "containers" ]
Removing a subset of a dict from within a list
167,120
<p>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:</p> <pre><code>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] </code></pre> <p>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.</p> <p>This method is annoying because it requires two loops and an extra array. Is there a cleaner and more efficient way of doing this.</p>
5
2008-10-03T14:24:35Z
167,158
<p>Why not just use the <code>keys</code> method, instead of <code>iterkeys</code>? That way you can do it in one loop because it returns a list, not an iterator.</p>
2
2008-10-03T14:32:12Z
[ "python", "list", "containers" ]
Removing a subset of a dict from within a list
167,120
<p>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:</p> <pre><code>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] </code></pre> <p>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.</p> <p>This method is annoying because it requires two loops and an extra array. Is there a cleaner and more efficient way of doing this.</p>
5
2008-10-03T14:24:35Z
167,167
<pre><code>a = dict((key,value) for (key,value) in a.iteritems() if key not in exclusion) </code></pre>
3
2008-10-03T14:34:20Z
[ "python", "list", "containers" ]
Removing a subset of a dict from within a list
167,120
<p>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:</p> <pre><code>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] </code></pre> <p>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.</p> <p>This method is annoying because it requires two loops and an extra array. Is there a cleaner and more efficient way of doing this.</p>
5
2008-10-03T14:24:35Z
167,335
<p>You could change your exclusion list to a set, then just use intersection to get the overlap.</p> <pre><code>exclusion = set([3, 4, 5]) for key in exclusion.intersection(a): del a[key] </code></pre>
1
2008-10-03T15:09:12Z
[ "python", "list", "containers" ]
Problem With Python Sockets: How To Get Reliably POSTed data whatever the browser?
167,426
<p>I wrote small Python+Ajax programs (listed at the end) with socket module to study the COMET concept of asynchronous communications.<br/> The idea is to allow browsers to send messages real time each others via my python program.<br/> The trick is to let the "GET messages/..." connexion opened waiting for a message to answer back.<br/> My problem is mainly on the reliability of what I have via socket.recv...<br/> When I POST from Firefox, it is working well.<br/> When I POST from Chrome or IE, the "data" I get in Python is empty.</p> <p>Does anybody know about this problem between browsers?<br/> Are some browsers injecting some EOF or else characters killing the receiving of "recv"?<br/> Is there any solution known to this problem?</p> <p>Thanks for your help,</p> <p>J.</p> <p>The server.py in Python:</p> <pre><code> import socket connected={} def inRequest(text): content='' if text[0:3]=='GET': method='GET' else: method='POST' k=len(text)-1 while k&gt;0 and text[k]!='\n' and text[k]!='\r': k=k-1 content=text[k+1:] text=text[text.index(' ')+1:] url=text[:text.index(' ')] return {"method":method,"url":url,"content":content} mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) mySocket.bind ( ( '', 80 ) ) mySocket.listen ( 10 ) while True: channel, details = mySocket.accept() data=channel.recv(4096) req=inRequest(data) url=req["url"] if url=="/client.html" or url=="/clientIE.html": f=open('C:\\async\\'+url) channel.send ('HTTP/1.1 200 OK\n\n'+f.read()) f.close() channel.close() elif '/messages' in url: if req["method"]=='POST': target=url[10:] if target in connected: connected[target].send("HTTP/1.1 200 OK\n\n"+req["content"]) print req["content"]+" sent to "+target connected[target].close() channel.close() elif req["method"]=='GET': user=url[10:] connected[user]=channel print user+' is connected' </code></pre> <p>The client.html in HTML+Javascript:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script&gt; var user='' function post(el) { if (window.XMLHttpRequest) { var text=el.value; var req=new XMLHttpRequest(); el.value=''; var target=document.getElementById('to').value } else if (window.ActiveXObject) { var text=el.content; var req=new ActiveXObject("Microsoft.XMLHTTP"); el.content=''; } else return; req.open('POST','messages/'+target,true) req.send(text); } function get(u) { if (user=='') user=u.value var req=new XMLHttpRequest() req.open('GET','messages/'+user,true) req.onload=function() { var message=document.createElement('p'); message.innerHTML=req.responseText; document.getElementById('messages').appendChild(message); get(user); } req.send(null) } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;span&gt;From&lt;/span&gt; &lt;input id="user"/&gt; &lt;input type="button" value="sign in" onclick="get(document.getElementById('user'))"/&gt; &lt;span&gt;To&lt;/span&gt; &lt;input id="to"/&gt; &lt;span&gt;:&lt;/span&gt; &lt;input id="message"/&gt; &lt;input type="button" value="post" onclick="post(document.getElementById('message'))"/&gt; &lt;div id="messages"&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
1
2008-10-03T15:28:36Z
167,997
<p>I would recommend using a JS/Ajax library on the client-side just to eliminate the possibility of cross-browser issues with your code. For the same reason I would recommend using a python http server library like <a href="http://docs.python.org/library/simplehttpserver.html" rel="nofollow">SimpleHTTPServer</a> or something from <a href="http://twistedmatrix.com/trac/wiki/Documentation" rel="nofollow">Twisted</a> if the former does not allow low-level control.</p> <p>Another idea - use something like Wireshark to check what's been sent by the browsers.</p>
0
2008-10-03T17:31:22Z
[ "javascript", "python", "sockets", "comet" ]
Problem With Python Sockets: How To Get Reliably POSTed data whatever the browser?
167,426
<p>I wrote small Python+Ajax programs (listed at the end) with socket module to study the COMET concept of asynchronous communications.<br/> The idea is to allow browsers to send messages real time each others via my python program.<br/> The trick is to let the "GET messages/..." connexion opened waiting for a message to answer back.<br/> My problem is mainly on the reliability of what I have via socket.recv...<br/> When I POST from Firefox, it is working well.<br/> When I POST from Chrome or IE, the "data" I get in Python is empty.</p> <p>Does anybody know about this problem between browsers?<br/> Are some browsers injecting some EOF or else characters killing the receiving of "recv"?<br/> Is there any solution known to this problem?</p> <p>Thanks for your help,</p> <p>J.</p> <p>The server.py in Python:</p> <pre><code> import socket connected={} def inRequest(text): content='' if text[0:3]=='GET': method='GET' else: method='POST' k=len(text)-1 while k&gt;0 and text[k]!='\n' and text[k]!='\r': k=k-1 content=text[k+1:] text=text[text.index(' ')+1:] url=text[:text.index(' ')] return {"method":method,"url":url,"content":content} mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) mySocket.bind ( ( '', 80 ) ) mySocket.listen ( 10 ) while True: channel, details = mySocket.accept() data=channel.recv(4096) req=inRequest(data) url=req["url"] if url=="/client.html" or url=="/clientIE.html": f=open('C:\\async\\'+url) channel.send ('HTTP/1.1 200 OK\n\n'+f.read()) f.close() channel.close() elif '/messages' in url: if req["method"]=='POST': target=url[10:] if target in connected: connected[target].send("HTTP/1.1 200 OK\n\n"+req["content"]) print req["content"]+" sent to "+target connected[target].close() channel.close() elif req["method"]=='GET': user=url[10:] connected[user]=channel print user+' is connected' </code></pre> <p>The client.html in HTML+Javascript:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script&gt; var user='' function post(el) { if (window.XMLHttpRequest) { var text=el.value; var req=new XMLHttpRequest(); el.value=''; var target=document.getElementById('to').value } else if (window.ActiveXObject) { var text=el.content; var req=new ActiveXObject("Microsoft.XMLHTTP"); el.content=''; } else return; req.open('POST','messages/'+target,true) req.send(text); } function get(u) { if (user=='') user=u.value var req=new XMLHttpRequest() req.open('GET','messages/'+user,true) req.onload=function() { var message=document.createElement('p'); message.innerHTML=req.responseText; document.getElementById('messages').appendChild(message); get(user); } req.send(null) } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;span&gt;From&lt;/span&gt; &lt;input id="user"/&gt; &lt;input type="button" value="sign in" onclick="get(document.getElementById('user'))"/&gt; &lt;span&gt;To&lt;/span&gt; &lt;input id="to"/&gt; &lt;span&gt;:&lt;/span&gt; &lt;input id="message"/&gt; &lt;input type="button" value="post" onclick="post(document.getElementById('message'))"/&gt; &lt;div id="messages"&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
1
2008-10-03T15:28:36Z
170,005
<p>The problem you have is that</p> <ul> <li>your tcp socket handling isn't reading as much as it should</li> <li>your http handling is not complete</li> </ul> <p>I recommend the following lectures:</p> <ul> <li><a href="http://www.w3.org/Protocols/rfc2616/rfc2616.html" rel="nofollow">rfc2616</a></li> <li><a href="http://www.kohala.com/start/unpv12e.html" rel="nofollow">The sockets Networking API</a> by Stevens</li> </ul> <p>See the example below for a working http server that can process posts</p> <pre><code>index = ''' &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;form action="/" method="POST"&gt; &lt;textarea name="foo"&gt;&lt;/textarea&gt; &lt;button type="submit"&gt;post&lt;/button&gt; &lt;/form&gt; &lt;h3&gt;data posted&lt;/h3&gt; &lt;div&gt; %s &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; ''' bufsize = 4048 import socket import re from urlparse import urlparse class Headers(object): def __init__(self, headers): self.__dict__.update(headers) def __getitem__(self, name): return getattr(self, name) def get(self, name, default=None): return getattr(self, name, default) class Request(object): header_re = re.compile(r'([a-zA-Z-]+):? ([^\r]+)', re.M) def __init__(self, sock): header_off = -1 data = '' while header_off == -1: data += sock.recv(bufsize) header_off = data.find('\r\n\r\n') header_string = data[:header_off] self.content = data[header_off+4:] lines = self.header_re.findall(header_string) self.method, path = lines.pop(0) path, protocol = path.split(' ') self.headers = Headers( (name.lower().replace('-', '_'), value) for name, value in lines ) if self.method in ['POST', 'PUT']: content_length = int(self.headers.get('content_length', 0)) while len(self.content) &lt; content_length: self.content += sock.recv(bufsize) self.query = urlparse(path)[4] acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM) acceptor.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1, ) acceptor.bind(('', 2501 )) acceptor.listen(10) if __name__ == '__main__': while True: sock, info = acceptor.accept() request = Request(sock) sock.send('HTTP/1.1 200 OK\n\n' + (index % request.content) ) sock.close() </code></pre>
1
2008-10-04T08:47:12Z
[ "javascript", "python", "sockets", "comet" ]
Problem With Python Sockets: How To Get Reliably POSTed data whatever the browser?
167,426
<p>I wrote small Python+Ajax programs (listed at the end) with socket module to study the COMET concept of asynchronous communications.<br/> The idea is to allow browsers to send messages real time each others via my python program.<br/> The trick is to let the "GET messages/..." connexion opened waiting for a message to answer back.<br/> My problem is mainly on the reliability of what I have via socket.recv...<br/> When I POST from Firefox, it is working well.<br/> When I POST from Chrome or IE, the "data" I get in Python is empty.</p> <p>Does anybody know about this problem between browsers?<br/> Are some browsers injecting some EOF or else characters killing the receiving of "recv"?<br/> Is there any solution known to this problem?</p> <p>Thanks for your help,</p> <p>J.</p> <p>The server.py in Python:</p> <pre><code> import socket connected={} def inRequest(text): content='' if text[0:3]=='GET': method='GET' else: method='POST' k=len(text)-1 while k&gt;0 and text[k]!='\n' and text[k]!='\r': k=k-1 content=text[k+1:] text=text[text.index(' ')+1:] url=text[:text.index(' ')] return {"method":method,"url":url,"content":content} mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM ) mySocket.bind ( ( '', 80 ) ) mySocket.listen ( 10 ) while True: channel, details = mySocket.accept() data=channel.recv(4096) req=inRequest(data) url=req["url"] if url=="/client.html" or url=="/clientIE.html": f=open('C:\\async\\'+url) channel.send ('HTTP/1.1 200 OK\n\n'+f.read()) f.close() channel.close() elif '/messages' in url: if req["method"]=='POST': target=url[10:] if target in connected: connected[target].send("HTTP/1.1 200 OK\n\n"+req["content"]) print req["content"]+" sent to "+target connected[target].close() channel.close() elif req["method"]=='GET': user=url[10:] connected[user]=channel print user+' is connected' </code></pre> <p>The client.html in HTML+Javascript:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;script&gt; var user='' function post(el) { if (window.XMLHttpRequest) { var text=el.value; var req=new XMLHttpRequest(); el.value=''; var target=document.getElementById('to').value } else if (window.ActiveXObject) { var text=el.content; var req=new ActiveXObject("Microsoft.XMLHTTP"); el.content=''; } else return; req.open('POST','messages/'+target,true) req.send(text); } function get(u) { if (user=='') user=u.value var req=new XMLHttpRequest() req.open('GET','messages/'+user,true) req.onload=function() { var message=document.createElement('p'); message.innerHTML=req.responseText; document.getElementById('messages').appendChild(message); get(user); } req.send(null) } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;span&gt;From&lt;/span&gt; &lt;input id="user"/&gt; &lt;input type="button" value="sign in" onclick="get(document.getElementById('user'))"/&gt; &lt;span&gt;To&lt;/span&gt; &lt;input id="to"/&gt; &lt;span&gt;:&lt;/span&gt; &lt;input id="message"/&gt; &lt;input type="button" value="post" onclick="post(document.getElementById('message'))"/&gt; &lt;div id="messages"&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
1
2008-10-03T15:28:36Z
170,354
<p><br/> Thank you very much Florian, your code is working!!!!<br/> I reuse the template and complete the <strong>main</strong> with my COMET mecanism and it is working much better<br/> Chrome and Firefox are working perfectly well<br/> IE has still a problem with the "long GET" system<br/> When it received the answer to the GET it does not stop to re executing the loop to print the messages.<br/> Investigating right now the question<br/></p> <p>Here is my updated code for very basic JQuery+Python cross browser system.<br/></p> <p>The Python program, based on Florian's code:<br/></p> <pre><code>bufsize = 4048 import socket import re from urlparse import urlparse connected={} class Headers(object): def __init__(self, headers): self.__dict__.update(headers) def __getitem__(self, name): return getattr(self, name) def get(self, name, default=None): return getattr(self, name, default) class Request(object): header_re = re.compile(r'([a-zA-Z-]+):? ([^\r]+)', re.M) def __init__(self, sock): header_off = -1 data = '' while header_off == -1: data += sock.recv(bufsize) header_off = data.find('\r\n\r\n') header_string = data[:header_off] self.content = data[header_off+4:] furl=header_string[header_string.index(' ')+1:] self.url=furl[:furl.index(' ')] lines = self.header_re.findall(header_string) self.method, path = lines.pop(0) path, protocol = path.split(' ') self.headers = Headers( (name.lower().replace('-', '_'), value) for name, value in lines ) if self.method in ['POST', 'PUT']: content_length = int(self.headers.get('content_length', 0)) while len(self.content) &lt; content_length: self.content += sock.recv(bufsize) self.query = urlparse(path)[4] acceptor = socket.socket(socket.AF_INET, socket.SOCK_STREAM) acceptor.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1, ) acceptor.bind(('', 8007 )) acceptor.listen(10) if __name__ == '__main__': while True: sock, info = acceptor.accept() request = Request(sock) m=request.method u=request.url[1:] if m=='GET' and (u=='client.html' or u=='jquery.js'): f=open('c:\\async\\'+u,'r') sock.send('HTTP/1.1 200 OK\n\n'+f.read()) f.close() sock.close() elif 'messages' in u: if m=='POST': target=u[9:] if target in connected: connected[target].send("HTTP/1.1 200 OK\n\n"+request.content) connected[target].close() sock.close() elif m=='GET': user=u[9:] connected[user]=sock print user+' is connected' </code></pre> <p>And the HTML with Jquery compacted:</p> <pre><code> &lt;html&gt; &lt;head&gt; &lt;style&gt; input {width:80px;} span {font-size:12px;} button {font-size:10px;} &lt;/style&gt; &lt;script type="text/javascript" src='jquery.js'&gt;&lt;/script&gt; &lt;script&gt; var user=''; function post(el) {$.post('messages/'+$('#to').val(),$('#message').val());} function get(u) { if (user=='') user=u.value $.get('messages/'+user,function(data) { $("&lt;p&gt;"+data+"&lt;/p&gt;").appendTo($('#messages'));get(user);}); } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;span&gt;From&lt;/span&gt;&lt;input id="user"/&gt;&lt;button onclick="get(document.getElementById('user'))"&gt;log&lt;/button&gt; &lt;span&gt;To&lt;/span&gt;&lt;input id="to"/&gt; &lt;span&gt;:&lt;/span&gt;&lt;input id="message"/&gt;&lt;button onclick="post()"&gt;post&lt;/button&gt; &lt;div id="messages"&gt;&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
0
2008-10-04T13:46:12Z
[ "javascript", "python", "sockets", "comet" ]
How do I enter a pound sterling character (£) into the Python interactive shell on Mac OS X?
167,439
<p><strong>Update:</strong> Thanks for the suggestions guys. After further research, I’ve reformulated the question here: <a href="http://stackoverflow.com/questions/217020/pythoneditline-on-os-x-163-sign-seems-to-be-bound-to-ed-prev-word">Python/editline on OS X: £ sign seems to be bound to ed-prev-word</a></p> <p>On Mac OS X I can’t enter a pound sterling sign (£) into the Python interactive shell.</p> <ul> <li>Mac OS X 10.5.5</li> <li>Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17)</li> <li>European keyboard (£ is shift-3)</li> </ul> <p>When I type “£” (i.e. press shift-3) at an empty Python shell, nothing appears.</p> <p>If I’ve already typed some characters, e.g.</p> <pre><code>&gt;&gt;&gt; 1234567890 1234567890 1234567890 </code></pre> <p>... then pressing shift-3 will make the cursor position itself after the most recent space, or the start of the line if there are no spaces left between the cursor and the start of the line.</p> <p>In a normal bash shell, pressing shift-3 types a “£” as expected.</p> <p>Any idea how I can type a literal “£” in the Python interactive shell?</p>
5
2008-10-03T15:30:59Z
167,465
<p>Must be your setup, I can use the £ (Also european keyboard) under IDLE or the python command line just fine. (python 2.5).</p> <p>edit: I'm using windows, so mayby its a problem with the how python works under the mac OS?</p>
0
2008-10-03T15:36:35Z
[ "python", "bash", "osx", "shell", "terminal" ]
How do I enter a pound sterling character (£) into the Python interactive shell on Mac OS X?
167,439
<p><strong>Update:</strong> Thanks for the suggestions guys. After further research, I’ve reformulated the question here: <a href="http://stackoverflow.com/questions/217020/pythoneditline-on-os-x-163-sign-seems-to-be-bound-to-ed-prev-word">Python/editline on OS X: £ sign seems to be bound to ed-prev-word</a></p> <p>On Mac OS X I can’t enter a pound sterling sign (£) into the Python interactive shell.</p> <ul> <li>Mac OS X 10.5.5</li> <li>Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17)</li> <li>European keyboard (£ is shift-3)</li> </ul> <p>When I type “£” (i.e. press shift-3) at an empty Python shell, nothing appears.</p> <p>If I’ve already typed some characters, e.g.</p> <pre><code>&gt;&gt;&gt; 1234567890 1234567890 1234567890 </code></pre> <p>... then pressing shift-3 will make the cursor position itself after the most recent space, or the start of the line if there are no spaces left between the cursor and the start of the line.</p> <p>In a normal bash shell, pressing shift-3 types a “£” as expected.</p> <p>Any idea how I can type a literal “£” in the Python interactive shell?</p>
5
2008-10-03T15:30:59Z
167,466
<p>In unicode it is 00A003. With the Unicode escape it would be u'\u00a003'. </p> <p>Edit: @ Patrick McElhaney said you might need to use 00A3.</p>
2
2008-10-03T15:37:38Z
[ "python", "bash", "osx", "shell", "terminal" ]
How do I enter a pound sterling character (£) into the Python interactive shell on Mac OS X?
167,439
<p><strong>Update:</strong> Thanks for the suggestions guys. After further research, I’ve reformulated the question here: <a href="http://stackoverflow.com/questions/217020/pythoneditline-on-os-x-163-sign-seems-to-be-bound-to-ed-prev-word">Python/editline on OS X: £ sign seems to be bound to ed-prev-word</a></p> <p>On Mac OS X I can’t enter a pound sterling sign (£) into the Python interactive shell.</p> <ul> <li>Mac OS X 10.5.5</li> <li>Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17)</li> <li>European keyboard (£ is shift-3)</li> </ul> <p>When I type “£” (i.e. press shift-3) at an empty Python shell, nothing appears.</p> <p>If I’ve already typed some characters, e.g.</p> <pre><code>&gt;&gt;&gt; 1234567890 1234567890 1234567890 </code></pre> <p>... then pressing shift-3 will make the cursor position itself after the most recent space, or the start of the line if there are no spaces left between the cursor and the start of the line.</p> <p>In a normal bash shell, pressing shift-3 types a “£” as expected.</p> <p>Any idea how I can type a literal “£” in the Python interactive shell?</p>
5
2008-10-03T15:30:59Z
167,472
<p>I'd imagine that the terminal emulator is eating the keystroke as a control code. Maybe see if it has a config file you can mess around with?</p>
1
2008-10-03T15:39:05Z
[ "python", "bash", "osx", "shell", "terminal" ]
How do I enter a pound sterling character (£) into the Python interactive shell on Mac OS X?
167,439
<p><strong>Update:</strong> Thanks for the suggestions guys. After further research, I’ve reformulated the question here: <a href="http://stackoverflow.com/questions/217020/pythoneditline-on-os-x-163-sign-seems-to-be-bound-to-ed-prev-word">Python/editline on OS X: £ sign seems to be bound to ed-prev-word</a></p> <p>On Mac OS X I can’t enter a pound sterling sign (£) into the Python interactive shell.</p> <ul> <li>Mac OS X 10.5.5</li> <li>Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17)</li> <li>European keyboard (£ is shift-3)</li> </ul> <p>When I type “£” (i.e. press shift-3) at an empty Python shell, nothing appears.</p> <p>If I’ve already typed some characters, e.g.</p> <pre><code>&gt;&gt;&gt; 1234567890 1234567890 1234567890 </code></pre> <p>... then pressing shift-3 will make the cursor position itself after the most recent space, or the start of the line if there are no spaces left between the cursor and the start of the line.</p> <p>In a normal bash shell, pressing shift-3 types a “£” as expected.</p> <p>Any idea how I can type a literal “£” in the Python interactive shell?</p>
5
2008-10-03T15:30:59Z
167,515
<p>Not the best solution, but you could type:</p> <pre><code> pound = u'\u00A3' </code></pre> <p>Then you have it in a variable you can use in the rest of your session.</p>
5
2008-10-03T15:47:29Z
[ "python", "bash", "osx", "shell", "terminal" ]
How do I enter a pound sterling character (£) into the Python interactive shell on Mac OS X?
167,439
<p><strong>Update:</strong> Thanks for the suggestions guys. After further research, I’ve reformulated the question here: <a href="http://stackoverflow.com/questions/217020/pythoneditline-on-os-x-163-sign-seems-to-be-bound-to-ed-prev-word">Python/editline on OS X: £ sign seems to be bound to ed-prev-word</a></p> <p>On Mac OS X I can’t enter a pound sterling sign (£) into the Python interactive shell.</p> <ul> <li>Mac OS X 10.5.5</li> <li>Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17)</li> <li>European keyboard (£ is shift-3)</li> </ul> <p>When I type “£” (i.e. press shift-3) at an empty Python shell, nothing appears.</p> <p>If I’ve already typed some characters, e.g.</p> <pre><code>&gt;&gt;&gt; 1234567890 1234567890 1234567890 </code></pre> <p>... then pressing shift-3 will make the cursor position itself after the most recent space, or the start of the line if there are no spaces left between the cursor and the start of the line.</p> <p>In a normal bash shell, pressing shift-3 types a “£” as expected.</p> <p>Any idea how I can type a literal “£” in the Python interactive shell?</p>
5
2008-10-03T15:30:59Z
167,998
<p><code>u'\N{pound sign}'</code></p> <p>If you are using ipython, put</p> <p><code>execute pound = u'\N{pound sign}'</code></p> <p>in your ipythonrc file (in "Section: Python code to execute") this way you will always have "pound" defined as the pound symbol in the interactive shell.</p>
2
2008-10-03T17:31:58Z
[ "python", "bash", "osx", "shell", "terminal" ]
What is best way to remove duplicate lines matching regex from string using Python?
167,923
<p>This is a pretty straight forward attempt. I haven't been using python for too long. Seems to work but I am sure I have much to learn. Someone let me know if I am way off here. Needs to find patterns, write the first line which matches, and then add a summary message for remaining consecutive lines which match pattern and return modified string.</p> <p>Just to be clear...regex <code>.*Dog.*</code> would take </p> <pre><code>Cat Dog My Dog Her Dog Mouse </code></pre> <p>and return </p> <pre><code>Cat Dog ::::: Pattern .*Dog.* repeats 2 more times. Mouse #!/usr/bin/env python # import re import types def remove_repeats (l_string, l_regex): """Take a string, remove similar lines and replace with a summary message. l_regex accepts strings and tuples. """ # Convert string to tuple. if type(l_regex) == types.StringType: l_regex = l_regex, for t in l_regex: r = '' p = '' for l in l_string.splitlines(True): if l.startswith('::::: Pattern'): r = r + l else: if re.search(t, l): # If line matches regex. m += 1 if m == 1: # If this is first match in a set of lines add line to file. r = r + l elif m &gt; 1: # Else update the message string. p = "::::: Pattern '" + t + "' repeats " + str(m-1) + ' more times.\n' else: if p: # Write the message string if it has value. r = r + p p = '' m = 0 r = r + l if p: # Write the message if loop ended in a pattern. r = r + p p = '' l_string = r # Reset string to modified string. return l_string </code></pre>
2
2008-10-03T17:13:37Z
168,009
<p>The rematcher function seems to do what you want:</p> <pre><code>def rematcher(re_str, iterable): matcher= re.compile(re_str) in_match= 0 for item in iterable: if matcher.match(item): if in_match == 0: yield item in_match+= 1 else: if in_match &gt; 1: yield "%s repeats %d more times\n" % (re_str, in_match-1) in_match= 0 yield item if in_match &gt; 1: yield "%s repeats %d more times\n" % (re_str, in_match-1) import sys, re for line in rematcher(".*Dog.*", sys.stdin): sys.stdout.write(line) </code></pre> <h1>EDIT</h1> <p>In your case, the final string should be:</p> <pre><code>final_string= '\n'.join(rematcher(".*Dog.*", your_initial_string.split("\n"))) </code></pre>
1
2008-10-03T17:34:20Z
[ "python", "regex" ]
What is best way to remove duplicate lines matching regex from string using Python?
167,923
<p>This is a pretty straight forward attempt. I haven't been using python for too long. Seems to work but I am sure I have much to learn. Someone let me know if I am way off here. Needs to find patterns, write the first line which matches, and then add a summary message for remaining consecutive lines which match pattern and return modified string.</p> <p>Just to be clear...regex <code>.*Dog.*</code> would take </p> <pre><code>Cat Dog My Dog Her Dog Mouse </code></pre> <p>and return </p> <pre><code>Cat Dog ::::: Pattern .*Dog.* repeats 2 more times. Mouse #!/usr/bin/env python # import re import types def remove_repeats (l_string, l_regex): """Take a string, remove similar lines and replace with a summary message. l_regex accepts strings and tuples. """ # Convert string to tuple. if type(l_regex) == types.StringType: l_regex = l_regex, for t in l_regex: r = '' p = '' for l in l_string.splitlines(True): if l.startswith('::::: Pattern'): r = r + l else: if re.search(t, l): # If line matches regex. m += 1 if m == 1: # If this is first match in a set of lines add line to file. r = r + l elif m &gt; 1: # Else update the message string. p = "::::: Pattern '" + t + "' repeats " + str(m-1) + ' more times.\n' else: if p: # Write the message string if it has value. r = r + p p = '' m = 0 r = r + l if p: # Write the message if loop ended in a pattern. r = r + p p = '' l_string = r # Reset string to modified string. return l_string </code></pre>
2
2008-10-03T17:13:37Z
168,052
<p>Updated your code to be a bit more effective</p> <pre><code>#!/usr/bin/env python # import re import types def remove_repeats (l_string, l_regex): """Take a string, remove similar lines and replace with a summary message. l_regex accepts strings/patterns or tuples of strings/patterns. """ # Convert string/pattern to tuple. if not hasattr(l_regex, '__iter__'): l_regex = l_regex, ret = [] last_regex = None count = 0 for line in l_string.splitlines(True): if last_regex: # Previus line matched one of the regexes if re.match(last_regex, line): # This one does too count += 1 continue # skip to next line elif count &gt; 1: ret.append("::::: Pattern %r repeats %d more times.\n" % (last_regex, count-1)) count = 0 last_regex = None ret.append(line) # Look for other patterns that could match for regex in l_regex: if re.match(regex, line): # Found one last_regex = regex count = 1 break # exit inner loop return ''.join(ret) </code></pre>
1
2008-10-03T17:44:00Z
[ "python", "regex" ]
What is best way to remove duplicate lines matching regex from string using Python?
167,923
<p>This is a pretty straight forward attempt. I haven't been using python for too long. Seems to work but I am sure I have much to learn. Someone let me know if I am way off here. Needs to find patterns, write the first line which matches, and then add a summary message for remaining consecutive lines which match pattern and return modified string.</p> <p>Just to be clear...regex <code>.*Dog.*</code> would take </p> <pre><code>Cat Dog My Dog Her Dog Mouse </code></pre> <p>and return </p> <pre><code>Cat Dog ::::: Pattern .*Dog.* repeats 2 more times. Mouse #!/usr/bin/env python # import re import types def remove_repeats (l_string, l_regex): """Take a string, remove similar lines and replace with a summary message. l_regex accepts strings and tuples. """ # Convert string to tuple. if type(l_regex) == types.StringType: l_regex = l_regex, for t in l_regex: r = '' p = '' for l in l_string.splitlines(True): if l.startswith('::::: Pattern'): r = r + l else: if re.search(t, l): # If line matches regex. m += 1 if m == 1: # If this is first match in a set of lines add line to file. r = r + l elif m &gt; 1: # Else update the message string. p = "::::: Pattern '" + t + "' repeats " + str(m-1) + ' more times.\n' else: if p: # Write the message string if it has value. r = r + p p = '' m = 0 r = r + l if p: # Write the message if loop ended in a pattern. r = r + p p = '' l_string = r # Reset string to modified string. return l_string </code></pre>
2
2008-10-03T17:13:37Z
1,250,162
<p>First, your regular expression will match more slowly than if you had left off the greedy match.</p> <pre><code>.*Dog.* </code></pre> <p>is equivalent to</p> <pre><code>Dog </code></pre> <p>but the latter matches more quickly because no backtracking is involved. The longer the strings, the more likely "Dog" appears multiple times and thus the more backtracking work the regex engine has to do. As it is, ".*D" virtually guarantees backtracking.</p> <p>That said, how about:</p> <pre><code>#! /usr/bin/env python import re # regular expressions import fileinput # read from STDIN or file my_regex = '.*Dog.*' my_matches = 0 for line in fileinput.input(): line = line.strip() if re.search(my_regex, line): if my_matches == 0: print(line) my_matches = my_matches + 1 else: if my_matches != 0: print('::::: Pattern %s repeats %i more times.' % (my_regex, my_matches - 1)) print(line) my_matches = 0 </code></pre> <p>It's not clear what should happen with non-neighboring matches.</p> <p>It's also not clear what should happen with single-line matches surrounded by non-matching lines. Append "Doggy" and "Hula" to the input file and you'll get the matching message "0" more times.</p>
0
2009-08-08T23:45:20Z
[ "python", "regex" ]
Naming conventions in a Python library
168,022
<p>I'm implementing a search algorithm (let's call it MyAlg) in a python package. Since the algorithm is super-duper complicated, the package has to contain an auxiliary class for algorithm options. Currently I'm developing the entire package by myself (and I'm not a programmer), however I expect 1-2 programmers to join the project later. This would be my first project that will involve external programmers. Thus, in order to make their lifes easier, how should I name this class: Options, OptionsMyAlg, MyAlgOptions or anything else?</p> <p>What would you suggest me to read in this topic except for <a href="http://www.joelonsoftware.com/articles/Wrong.html" rel="nofollow">http://www.joelonsoftware.com/articles/Wrong.html</a> ?</p> <p>Thank you Yuri [cross posted from here: <a href="http://discuss.joelonsoftware.com/default.asp?design.4.684669.0" rel="nofollow">http://discuss.joelonsoftware.com/default.asp?design.4.684669.0</a> will update the answers in both places]</p>
1
2008-10-03T17:37:47Z
168,072
<p>I suggest you read <a href="http://www.python.org/dev/peps/pep-0008/" rel="nofollow">PEP8</a> (styleguide for Python code).</p>
6
2008-10-03T17:48:02Z
[ "python", "naming-conventions" ]
Naming conventions in a Python library
168,022
<p>I'm implementing a search algorithm (let's call it MyAlg) in a python package. Since the algorithm is super-duper complicated, the package has to contain an auxiliary class for algorithm options. Currently I'm developing the entire package by myself (and I'm not a programmer), however I expect 1-2 programmers to join the project later. This would be my first project that will involve external programmers. Thus, in order to make their lifes easier, how should I name this class: Options, OptionsMyAlg, MyAlgOptions or anything else?</p> <p>What would you suggest me to read in this topic except for <a href="http://www.joelonsoftware.com/articles/Wrong.html" rel="nofollow">http://www.joelonsoftware.com/articles/Wrong.html</a> ?</p> <p>Thank you Yuri [cross posted from here: <a href="http://discuss.joelonsoftware.com/default.asp?design.4.684669.0" rel="nofollow">http://discuss.joelonsoftware.com/default.asp?design.4.684669.0</a> will update the answers in both places]</p>
1
2008-10-03T17:37:47Z
168,085
<p>Just naming it <code>Options</code> should be fine. The Python standard library generally takes the philosophy that namespaces make it easy and manageable for different packages to have identically named things. For example, <code>open</code> is both a builtin and a function in the <code>os</code> module, several different modules define an <code>Error</code> exception class, and so on.</p> <p>This is why it's generally considered bad form to say <code>from some_module import *</code> since it makes it unclear to which <code>open</code> your code refers, etc.</p>
2
2008-10-03T17:50:55Z
[ "python", "naming-conventions" ]
Naming conventions in a Python library
168,022
<p>I'm implementing a search algorithm (let's call it MyAlg) in a python package. Since the algorithm is super-duper complicated, the package has to contain an auxiliary class for algorithm options. Currently I'm developing the entire package by myself (and I'm not a programmer), however I expect 1-2 programmers to join the project later. This would be my first project that will involve external programmers. Thus, in order to make their lifes easier, how should I name this class: Options, OptionsMyAlg, MyAlgOptions or anything else?</p> <p>What would you suggest me to read in this topic except for <a href="http://www.joelonsoftware.com/articles/Wrong.html" rel="nofollow">http://www.joelonsoftware.com/articles/Wrong.html</a> ?</p> <p>Thank you Yuri [cross posted from here: <a href="http://discuss.joelonsoftware.com/default.asp?design.4.684669.0" rel="nofollow">http://discuss.joelonsoftware.com/default.asp?design.4.684669.0</a> will update the answers in both places]</p>
1
2008-10-03T17:37:47Z
168,107
<p>If it all fits in one file, name the class Options. Then your users can write:</p> <pre><code>import myalg searchOpts = myalg.Options() searchOpts.whatever() mySearcher = myalg.SearchAlg(searchOpts) mySearcher.search("where's waldo?") </code></pre> <p>Note the Python Style Guide referenced in another answer suggests that packages should be named with all lowercase letters.</p>
2
2008-10-03T17:56:15Z
[ "python", "naming-conventions" ]
Django: How do I create a generic url routing to views?
168,113
<p>I have a pretty standard django app, and am wondering how to set the url routing so that I don't have to explicitly map each url to a view. </p> <p>For example, let's say that I have the following views: <code>Project, Links, Profile, Contact</code>. I'd rather not have my <code>urlpatterns</code> look like this:</p> <pre><code>(r'^Project/$', 'mysite.app.views.project'), (r'^Links/$', 'mysite.app.views.links'), (r'^Profile/$', 'mysite.app.views.profile'), (r'^Contact/$', 'mysite.app.views.contact'), </code></pre> <p>And so on. In <a href="http://www.pylonshq.com">Pylons</a>, it would be as simple as:</p> <pre><code>map.connect(':controller/:action/:id') </code></pre> <p>And it would automatically grab the right controller and function. Is there something similar in Django?</p>
6
2008-10-03T17:58:05Z
168,328
<pre><code>mods = ('Project','Links','Profile','Contact') urlpatterns = patterns('', *(('^%s/$'%n, 'mysite.app.views.%s'%n.lower()) for n in mods) ) </code></pre>
5
2008-10-03T18:49:41Z
[ "python", "django", "pylons" ]
Django: How do I create a generic url routing to views?
168,113
<p>I have a pretty standard django app, and am wondering how to set the url routing so that I don't have to explicitly map each url to a view. </p> <p>For example, let's say that I have the following views: <code>Project, Links, Profile, Contact</code>. I'd rather not have my <code>urlpatterns</code> look like this:</p> <pre><code>(r'^Project/$', 'mysite.app.views.project'), (r'^Links/$', 'mysite.app.views.links'), (r'^Profile/$', 'mysite.app.views.profile'), (r'^Contact/$', 'mysite.app.views.contact'), </code></pre> <p>And so on. In <a href="http://www.pylonshq.com">Pylons</a>, it would be as simple as:</p> <pre><code>map.connect(':controller/:action/:id') </code></pre> <p>And it would automatically grab the right controller and function. Is there something similar in Django?</p>
6
2008-10-03T17:58:05Z
168,601
<p>Unless you have a really <em>huge</em> number of views, writing them down explicitly is not too bad, from a style perspective.</p> <p>You can shorten your example, though, by using the prefix argument of the <code>patterns</code> function:</p> <pre><code>urlpatterns = patterns('mysite.app.views', (r'^Project/$', 'project'), (r'^Links/$', 'links'), (r'^Profile/$', 'profile'), (r'^Contact/$', 'contact'), ) </code></pre>
5
2008-10-03T19:51:36Z
[ "python", "django", "pylons" ]
Django: How do I create a generic url routing to views?
168,113
<p>I have a pretty standard django app, and am wondering how to set the url routing so that I don't have to explicitly map each url to a view. </p> <p>For example, let's say that I have the following views: <code>Project, Links, Profile, Contact</code>. I'd rather not have my <code>urlpatterns</code> look like this:</p> <pre><code>(r'^Project/$', 'mysite.app.views.project'), (r'^Links/$', 'mysite.app.views.links'), (r'^Profile/$', 'mysite.app.views.profile'), (r'^Contact/$', 'mysite.app.views.contact'), </code></pre> <p>And so on. In <a href="http://www.pylonshq.com">Pylons</a>, it would be as simple as:</p> <pre><code>map.connect(':controller/:action/:id') </code></pre> <p>And it would automatically grab the right controller and function. Is there something similar in Django?</p>
6
2008-10-03T17:58:05Z
168,656
<p>You might be able to use a special view function along these lines:</p> <pre><code>def router(request, function, module): m =__import__(module, globals(), locals(), [function.lower()]) try: return m.__dict__[function.lower()](request) except KeyError: raise Http404() </code></pre> <p>and then a urlconf like this:</p> <pre><code>(r'^(?P&lt;function&gt;.+)/$', router, {"module": 'mysite.app.views'}), </code></pre> <p>This code is untested but the general idea should work, even though you should remember:</p> <p><strong>Explicit is better than implicit.</strong></p>
5
2008-10-03T20:06:35Z
[ "python", "django", "pylons" ]
Initializing cherrypy.session early
168,167
<p>I love CherryPy's API for sessions, except for one detail. Instead of saying <code>cherrypy.session["spam"]</code> I'd like to be able to just say <code>session["spam"]</code>.</p> <p>Unfortunately, I can't simply have a global <code>from cherrypy import session</code> in one of my modules, because the <code>cherrypy.session</code> object isn't created until the first time a page request is made. Is there some way to get CherryPy to initialize its session object immediately instead of on the first page request?</p> <p>I have two ugly alternatives if the answer is no:</p> <p>First, I can do something like this</p> <pre><code>def import_session(): global session while not hasattr(cherrypy, "session"): sleep(0.1) session = cherrypy.session Thread(target=import_session).start() </code></pre> <p>This feels like a big kludge, but I really hate writing <code>cherrypy.session["spam"]</code> every time, so to me it's worth it.</p> <p>My second solution is to do something like</p> <pre><code>class SessionKludge: def __getitem__(self, name): return cherrypy.session[name] def __setitem__(self, name, val): cherrypy.session[name] = val session = SessionKludge() </code></pre> <p>but this feels like an even bigger kludge and I'd need to do more work to implement the other dictionary functions such as <code>.get</code></p> <p>So I'd definitely prefer a simple way to initialize the object myself. Does anyone know how to do this?</p>
2
2008-10-03T18:16:08Z
169,779
<p>For CherryPy 3.1, you would need to find the right subclass of Session, run its 'setup' classmethod, and then set cherrypy.session to a ThreadLocalProxy. That all happens in cherrypy.lib.sessions.init, in the following chunks:</p> <pre><code># Find the storage class and call setup (first time only). storage_class = storage_type.title() + 'Session' storage_class = globals()[storage_class] if not hasattr(cherrypy, "session"): if hasattr(storage_class, "setup"): storage_class.setup(**kwargs) # Create cherrypy.session which will proxy to cherrypy.serving.session if not hasattr(cherrypy, "session"): cherrypy.session = cherrypy._ThreadLocalProxy('session') </code></pre> <p>Reducing (replace FileSession with the subclass you want):</p> <pre><code>FileSession.setup(**kwargs) cherrypy.session = cherrypy._ThreadLocalProxy('session') </code></pre> <p>The "kwargs" consist of "timeout", "clean_freq", and any subclass-specific entries from tools.sessions.* config.</p>
5
2008-10-04T05:12:53Z
[ "python", "cherrypy" ]
How do I build and install P4Python for Mac OS X?
168,273
<p>I've been unable to build <a href="http://www.perforce.com/perforce/loadsupp.html#api" rel="nofollow">P4Python</a> for an Intel Mac OS X 10.5.5.</p> <p>These are my steps:</p> <ol> <li>I downloaded p4python.tgz (from <a href="http://filehost.perforce.com/perforce/r07.3/tools/" rel="nofollow">http://filehost.perforce.com/perforce/r07.3/tools/</a>) and expanded it into "P4Python-2007.3".</li> <li>I downloaded p4api.tar (from <a href="http://filehost.perforce.com/perforce/r07.3/bin.macosx104x86/" rel="nofollow">http://filehost.perforce.com/perforce/r07.3/bin.macosx104x86/</a>) and expanded it into "p4api-2007.3.143793".</li> <li>I placed "p4api-2007.3.143793" into "P4Python-2007.3" and edited setup.cfg to set "p4_api=./p4api-2007.3.143793".</li> <li><p>I added the line 'extra_link_args = ["-framework", "Carbon"]' to setup.py after:</p> <pre><code>elif unameOut[0] == "Darwin": unix = "MACOSX" release = "104" platform = self.architecture(unameOut[4]) </code></pre></li> <li><p>I ran <code>python setup.py build</code> and got:</p></li> </ol> <p>$ python setup.py build</p> <pre><code>API Release 2007.3 running build running build_py running build_ext building 'P4API' extension gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DID_OS="MACOSX104X86" -DID_REL="2007.3" -DID_PATCH="151416" -DID_API="2007.3" -DID_Y="2008" -DID_M="04" -DID_D="09" -I./p4api-2007.3.143793 -I./p4api-2007.3.143793/include/p4 -I/build/toolchain/mac32/python-2.4.3/include/python2.4 -c P4API.cpp -o build/temp.darwin-9.5.0-i386-2.4/P4API.o -DOS_MACOSX -DOS_MACOSX104 -DOS_MACOSXX86 -DOS_MACOSX104X86 cc1plus: warning: command line option "-Wstrict-prototypes" is valid for C/ObjC but not for C++ P4API.cpp: In function âint P4Adapter_init(P4Adapter*, PyObject*, PyObject*)â: P4API.cpp:105: error: âPy_ssize_tâ was not declared in this scope P4API.cpp:105: error: expected `;' before âposâ P4API.cpp:107: error: âposâ was not declared in this scope P4API.cpp: In function âPyObject* P4Adapter_run(P4Adapter*, PyObject*)â: P4API.cpp:177: error: âPy_ssize_tâ was not declared in this scope P4API.cpp:177: error: expected `;' before âiâ P4API.cpp:177: error: âiâ was not declared in this scope error: command 'gcc' failed with exit status 1 </code></pre> <p><code>which gcc</code> returns /usr/bin/gcc and <code>gcc -v</code> returns:</p> <pre><code>Using built-in specs. Target: i686-apple-darwin9 Configured with: /var/tmp/gcc/gcc-5465~16/src/configure --disable-checking -enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.0/ --with-gxx-include-dir=/include/c++/4.0.0 --with-slibdir=/usr/lib --build=i686-apple-darwin9 --with-arch=apple --with-tune=generic --host=i686-apple-darwin9 --target=i686-apple-darwin9 Thread model: posix gcc version 4.0.1 (Apple Inc. build 5465) </code></pre> <p><code>python -V</code> returns Python 2.4.3.</p>
2
2008-10-03T18:38:40Z
170,068
<p>From <a href="http://bugs.mymediasystem.org/?do=details&amp;task_id=676" rel="nofollow">http://bugs.mymediasystem.org/?do=details&amp;task_id=676</a> suggests that Py_ssize_t was added in python 2.5, so it won't work (without some modifications) with python 2.4.</p> <p>Either install/compile your own copy of python 2.5/2.6, or work out how to change P4Python, or look for an alternative python-perforce library.</p>
1
2008-10-04T09:53:03Z
[ "python", "osx", "perforce", "p4python" ]
How do I build and install P4Python for Mac OS X?
168,273
<p>I've been unable to build <a href="http://www.perforce.com/perforce/loadsupp.html#api" rel="nofollow">P4Python</a> for an Intel Mac OS X 10.5.5.</p> <p>These are my steps:</p> <ol> <li>I downloaded p4python.tgz (from <a href="http://filehost.perforce.com/perforce/r07.3/tools/" rel="nofollow">http://filehost.perforce.com/perforce/r07.3/tools/</a>) and expanded it into "P4Python-2007.3".</li> <li>I downloaded p4api.tar (from <a href="http://filehost.perforce.com/perforce/r07.3/bin.macosx104x86/" rel="nofollow">http://filehost.perforce.com/perforce/r07.3/bin.macosx104x86/</a>) and expanded it into "p4api-2007.3.143793".</li> <li>I placed "p4api-2007.3.143793" into "P4Python-2007.3" and edited setup.cfg to set "p4_api=./p4api-2007.3.143793".</li> <li><p>I added the line 'extra_link_args = ["-framework", "Carbon"]' to setup.py after:</p> <pre><code>elif unameOut[0] == "Darwin": unix = "MACOSX" release = "104" platform = self.architecture(unameOut[4]) </code></pre></li> <li><p>I ran <code>python setup.py build</code> and got:</p></li> </ol> <p>$ python setup.py build</p> <pre><code>API Release 2007.3 running build running build_py running build_ext building 'P4API' extension gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DID_OS="MACOSX104X86" -DID_REL="2007.3" -DID_PATCH="151416" -DID_API="2007.3" -DID_Y="2008" -DID_M="04" -DID_D="09" -I./p4api-2007.3.143793 -I./p4api-2007.3.143793/include/p4 -I/build/toolchain/mac32/python-2.4.3/include/python2.4 -c P4API.cpp -o build/temp.darwin-9.5.0-i386-2.4/P4API.o -DOS_MACOSX -DOS_MACOSX104 -DOS_MACOSXX86 -DOS_MACOSX104X86 cc1plus: warning: command line option "-Wstrict-prototypes" is valid for C/ObjC but not for C++ P4API.cpp: In function âint P4Adapter_init(P4Adapter*, PyObject*, PyObject*)â: P4API.cpp:105: error: âPy_ssize_tâ was not declared in this scope P4API.cpp:105: error: expected `;' before âposâ P4API.cpp:107: error: âposâ was not declared in this scope P4API.cpp: In function âPyObject* P4Adapter_run(P4Adapter*, PyObject*)â: P4API.cpp:177: error: âPy_ssize_tâ was not declared in this scope P4API.cpp:177: error: expected `;' before âiâ P4API.cpp:177: error: âiâ was not declared in this scope error: command 'gcc' failed with exit status 1 </code></pre> <p><code>which gcc</code> returns /usr/bin/gcc and <code>gcc -v</code> returns:</p> <pre><code>Using built-in specs. Target: i686-apple-darwin9 Configured with: /var/tmp/gcc/gcc-5465~16/src/configure --disable-checking -enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.0/ --with-gxx-include-dir=/include/c++/4.0.0 --with-slibdir=/usr/lib --build=i686-apple-darwin9 --with-arch=apple --with-tune=generic --host=i686-apple-darwin9 --target=i686-apple-darwin9 Thread model: posix gcc version 4.0.1 (Apple Inc. build 5465) </code></pre> <p><code>python -V</code> returns Python 2.4.3.</p>
2
2008-10-03T18:38:40Z
175,097
<p>Very outdated, but maybe you can use <a href="http://public.perforce.com:8080/@md=d&amp;cd=//guest/miki_tebeka/p4py/&amp;c=5Fm@//guest/miki_tebeka/p4py/main/?ac=83" rel="nofollow">http://public.perforce.com:8080/@md=d&amp;cd=//guest/miki_tebeka/p4py/&amp;c=5Fm@//guest/miki_tebeka/p4py/main/?ac=83</a> for now</p>
0
2008-10-06T16:40:48Z
[ "python", "osx", "perforce", "p4python" ]
How do I build and install P4Python for Mac OS X?
168,273
<p>I've been unable to build <a href="http://www.perforce.com/perforce/loadsupp.html#api" rel="nofollow">P4Python</a> for an Intel Mac OS X 10.5.5.</p> <p>These are my steps:</p> <ol> <li>I downloaded p4python.tgz (from <a href="http://filehost.perforce.com/perforce/r07.3/tools/" rel="nofollow">http://filehost.perforce.com/perforce/r07.3/tools/</a>) and expanded it into "P4Python-2007.3".</li> <li>I downloaded p4api.tar (from <a href="http://filehost.perforce.com/perforce/r07.3/bin.macosx104x86/" rel="nofollow">http://filehost.perforce.com/perforce/r07.3/bin.macosx104x86/</a>) and expanded it into "p4api-2007.3.143793".</li> <li>I placed "p4api-2007.3.143793" into "P4Python-2007.3" and edited setup.cfg to set "p4_api=./p4api-2007.3.143793".</li> <li><p>I added the line 'extra_link_args = ["-framework", "Carbon"]' to setup.py after:</p> <pre><code>elif unameOut[0] == "Darwin": unix = "MACOSX" release = "104" platform = self.architecture(unameOut[4]) </code></pre></li> <li><p>I ran <code>python setup.py build</code> and got:</p></li> </ol> <p>$ python setup.py build</p> <pre><code>API Release 2007.3 running build running build_py running build_ext building 'P4API' extension gcc -fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd -DNDEBUG -g -O3 -Wall -Wstrict-prototypes -DID_OS="MACOSX104X86" -DID_REL="2007.3" -DID_PATCH="151416" -DID_API="2007.3" -DID_Y="2008" -DID_M="04" -DID_D="09" -I./p4api-2007.3.143793 -I./p4api-2007.3.143793/include/p4 -I/build/toolchain/mac32/python-2.4.3/include/python2.4 -c P4API.cpp -o build/temp.darwin-9.5.0-i386-2.4/P4API.o -DOS_MACOSX -DOS_MACOSX104 -DOS_MACOSXX86 -DOS_MACOSX104X86 cc1plus: warning: command line option "-Wstrict-prototypes" is valid for C/ObjC but not for C++ P4API.cpp: In function âint P4Adapter_init(P4Adapter*, PyObject*, PyObject*)â: P4API.cpp:105: error: âPy_ssize_tâ was not declared in this scope P4API.cpp:105: error: expected `;' before âposâ P4API.cpp:107: error: âposâ was not declared in this scope P4API.cpp: In function âPyObject* P4Adapter_run(P4Adapter*, PyObject*)â: P4API.cpp:177: error: âPy_ssize_tâ was not declared in this scope P4API.cpp:177: error: expected `;' before âiâ P4API.cpp:177: error: âiâ was not declared in this scope error: command 'gcc' failed with exit status 1 </code></pre> <p><code>which gcc</code> returns /usr/bin/gcc and <code>gcc -v</code> returns:</p> <pre><code>Using built-in specs. Target: i686-apple-darwin9 Configured with: /var/tmp/gcc/gcc-5465~16/src/configure --disable-checking -enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.0/ --with-gxx-include-dir=/include/c++/4.0.0 --with-slibdir=/usr/lib --build=i686-apple-darwin9 --with-arch=apple --with-tune=generic --host=i686-apple-darwin9 --target=i686-apple-darwin9 Thread model: posix gcc version 4.0.1 (Apple Inc. build 5465) </code></pre> <p><code>python -V</code> returns Python 2.4.3.</p>
2
2008-10-03T18:38:40Z
478,587
<p>The newer version 2008.1 will build with Python 2.4.</p> <p>I had posted the minor changes required to do that on my P4Python page, but they were rolled in to the official version.</p> <p>Robert</p>
1
2009-01-26T00:18:32Z
[ "python", "osx", "perforce", "p4python" ]
How do you get a directory listing sorted by creation date in python?
168,409
<p>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?</p>
52
2008-10-03T19:10:08Z
168,424
<p>I've done this in the past for a Python script to determine the last updated files in a directory: </p> <pre><code>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)) </code></pre> <p>That should do what you're looking for based on file mtime.</p> <p><strong>EDIT</strong>: 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: </p> <pre><code>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)) </code></pre>
65
2008-10-03T19:12:48Z
[ "python", "windows", "directory" ]
How do you get a directory listing sorted by creation date in python?
168,409
<p>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?</p>
52
2008-10-03T19:10:08Z
168,430
<p>Maybe you should use shell commands. In Unix/Linux, find piped with sort will probably be able to do what you want. </p>
-3
2008-10-03T19:14:18Z
[ "python", "windows", "directory" ]
How do you get a directory listing sorted by creation date in python?
168,409
<p>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?</p>
52
2008-10-03T19:10:08Z
168,435
<p>Here's a one-liner:</p> <pre><code>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)]) </code></pre> <p>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.</p> <p>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.</p>
15
2008-10-03T19:15:23Z
[ "python", "windows", "directory" ]
How do you get a directory listing sorted by creation date in python?
168,409
<p>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?</p>
52
2008-10-03T19:10:08Z
168,580
<p>Here's my version:</p> <pre><code>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 </code></pre> <p>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.</p>
12
2008-10-03T19:46:53Z
[ "python", "windows", "directory" ]
How do you get a directory listing sorted by creation date in python?
168,409
<p>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?</p>
52
2008-10-03T19:10:08Z
168,658
<pre><code>sorted(filter(os.path.isfile, os.listdir('.')), key=lambda p: os.stat(p).st_mtime) </code></pre> <p>You could use <code>os.walk('.').next()[-1]</code> instead of filtering with <code>os.path.isfile</code>, but that leaves dead symlinks in the list, and <code>os.stat</code> will fail on them.</p>
4
2008-10-03T20:07:15Z
[ "python", "windows", "directory" ]
How do you get a directory listing sorted by creation date in python?
168,409
<p>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?</p>
52
2008-10-03T19:10:08Z
539,024
<p>Here's a more verbose version of <a href="http://stackoverflow.com/questions/168409/how-do-you-get-a-directory-listing-sorted-by-creation-date-in-python/168435#168435"><code>@Greg Hewgill</code>'s answer</a>. It is the most conforming to the question requirements. It makes a distinction between creation and modification dates (at least on Windows).</p> <pre><code>#!/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) </code></pre> <p>Example:</p> <pre><code>$ python stat_creation_date.py Thu Feb 11 13:31:07 2009 stat_creation_date.py </code></pre>
31
2009-02-11T21:58:21Z
[ "python", "windows", "directory" ]
How do you get a directory listing sorted by creation date in python?
168,409
<p>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?</p>
52
2008-10-03T19:10:08Z
4,914,674
<p>There is an <code>os.path.getmtime</code> function that gives the number of seconds since the epoch and should be faster than os.stat.</p> <pre><code>os.chdir(directory) sorted(filter(os.path.isfile, os.listdir('.')), key=os.path.getmtime) </code></pre>
8
2011-02-06T16:47:48Z
[ "python", "windows", "directory" ]
How do you get a directory listing sorted by creation date in python?
168,409
<p>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?</p>
52
2008-10-03T19:10:08Z
7,801,791
<p>this is a basic step for learn:</p> <pre><code>import os, stat, sys import time dirpath = sys.argv[1] if len(sys.argv) == 2 else r'.' listdir = os.listdir(dirpath) for i in listdir: os.chdir(dirpath) data_001 = os.path.realpath(i) listdir_stat1 = os.stat(data_001) listdir_stat2 = ((os.stat(data_001), data_001)) print time.ctime(listdir_stat1.st_ctime), data_001 </code></pre>
0
2011-10-18T02:29:25Z
[ "python", "windows", "directory" ]
How do you get a directory listing sorted by creation date in python?
168,409
<p>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?</p>
52
2008-10-03T19:10:08Z
18,783,474
<p>Here's my answer using glob without filter if you want to read files with a certain extension in date order (Python 3). </p> <pre><code>dataset_path='/mydir/' files = glob.glob(dataset_path+"/morepath/*.extension") files.sort(key=os.path.getmtime) </code></pre>
5
2013-09-13T09:59:29Z
[ "python", "windows", "directory" ]
How do you get a directory listing sorted by creation date in python?
168,409
<p>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?</p>
52
2008-10-03T19:10:08Z
30,381,619
<p>Without changing directory:</p> <pre><code>import os path = '/path/to/files/' name_list = os.listdir(path) full_list = [os.path.join(path,i) for i in name_list] time_sorted_list = sorted(full_list, key=os.path.getmtime) print time_sorted_list # if you want just the filenames sorted, simply remove the dir from each sorted_filename_list = [ os.path.basename(i) for i in time_sorted_list] print sorted_filename_list </code></pre>
5
2015-05-21T18:28:30Z
[ "python", "windows", "directory" ]
Python - How do I convert "an OS-level handle to an open file" to a file object?
168,559
<p><a href="http://www.python.org/doc/2.5.2/lib/module-tempfile.html">tempfile.mkstemp()</a> returns:</p> <blockquote> <p>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.</p> </blockquote> <p>How do I convert that OS-level handle to a file object?</p> <p>The <a href="http://www.python.org/doc/2.5.2/lib/os-fd-ops.html">documentation for os.open()</a> states: </p> <blockquote> <p>To wrap a file descriptor in a "file object", use fdopen().</p> </blockquote> <p>So I tried:</p> <pre><code>&gt;&gt;&gt; import tempfile &gt;&gt;&gt; tup = tempfile.mkstemp() &gt;&gt;&gt; import os &gt;&gt;&gt; f = os.fdopen(tup[0]) &gt;&gt;&gt; f.write('foo\n') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? IOError: [Errno 9] Bad file descriptor </code></pre>
41
2008-10-03T19:41:04Z
168,584
<p>You can use </p> <pre><code>os.write(tup[0], "foo\n") </code></pre> <p>to write to the handle.</p> <p>If you want to open the handle for writing you need to add the <strong>"w"</strong> mode</p> <pre><code>f = os.fdopen(tup[0], "w") f.write("foo") </code></pre>
45
2008-10-03T19:47:17Z
[ "python", "temporary-files", "mkstemp", "fdopen" ]
Python - How do I convert "an OS-level handle to an open file" to a file object?
168,559
<p><a href="http://www.python.org/doc/2.5.2/lib/module-tempfile.html">tempfile.mkstemp()</a> returns:</p> <blockquote> <p>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.</p> </blockquote> <p>How do I convert that OS-level handle to a file object?</p> <p>The <a href="http://www.python.org/doc/2.5.2/lib/os-fd-ops.html">documentation for os.open()</a> states: </p> <blockquote> <p>To wrap a file descriptor in a "file object", use fdopen().</p> </blockquote> <p>So I tried:</p> <pre><code>&gt;&gt;&gt; import tempfile &gt;&gt;&gt; tup = tempfile.mkstemp() &gt;&gt;&gt; import os &gt;&gt;&gt; f = os.fdopen(tup[0]) &gt;&gt;&gt; f.write('foo\n') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? IOError: [Errno 9] Bad file descriptor </code></pre>
41
2008-10-03T19:41:04Z
168,640
<p>You forgot to specify the open mode ('w') in fdopen(). The default is 'r', causing the write() call to fail.</p> <p>I think mkstemp() creates the file for reading only. Calling fdopen with 'w' probably reopens it for writing (you <em>can</em> reopen the file created by mkstemp).</p>
6
2008-10-03T20:00:14Z
[ "python", "temporary-files", "mkstemp", "fdopen" ]
Python - How do I convert "an OS-level handle to an open file" to a file object?
168,559
<p><a href="http://www.python.org/doc/2.5.2/lib/module-tempfile.html">tempfile.mkstemp()</a> returns:</p> <blockquote> <p>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.</p> </blockquote> <p>How do I convert that OS-level handle to a file object?</p> <p>The <a href="http://www.python.org/doc/2.5.2/lib/os-fd-ops.html">documentation for os.open()</a> states: </p> <blockquote> <p>To wrap a file descriptor in a "file object", use fdopen().</p> </blockquote> <p>So I tried:</p> <pre><code>&gt;&gt;&gt; import tempfile &gt;&gt;&gt; tup = tempfile.mkstemp() &gt;&gt;&gt; import os &gt;&gt;&gt; f = os.fdopen(tup[0]) &gt;&gt;&gt; f.write('foo\n') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? IOError: [Errno 9] Bad file descriptor </code></pre>
41
2008-10-03T19:41:04Z
168,705
<p>What's your goal, here? Is <code>tempfile.TemporaryFile</code> inappropriate for your purposes?</p>
1
2008-10-03T20:19:54Z
[ "python", "temporary-files", "mkstemp", "fdopen" ]
Python - How do I convert "an OS-level handle to an open file" to a file object?
168,559
<p><a href="http://www.python.org/doc/2.5.2/lib/module-tempfile.html">tempfile.mkstemp()</a> returns:</p> <blockquote> <p>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.</p> </blockquote> <p>How do I convert that OS-level handle to a file object?</p> <p>The <a href="http://www.python.org/doc/2.5.2/lib/os-fd-ops.html">documentation for os.open()</a> states: </p> <blockquote> <p>To wrap a file descriptor in a "file object", use fdopen().</p> </blockquote> <p>So I tried:</p> <pre><code>&gt;&gt;&gt; import tempfile &gt;&gt;&gt; tup = tempfile.mkstemp() &gt;&gt;&gt; import os &gt;&gt;&gt; f = os.fdopen(tup[0]) &gt;&gt;&gt; f.write('foo\n') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? IOError: [Errno 9] Bad file descriptor </code></pre>
41
2008-10-03T19:41:04Z
1,296,063
<p>Here's how to do it using a with statement:</p> <pre><code>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') </code></pre>
13
2009-08-18T19:44:31Z
[ "python", "temporary-files", "mkstemp", "fdopen" ]
Python - How do I convert "an OS-level handle to an open file" to a file object?
168,559
<p><a href="http://www.python.org/doc/2.5.2/lib/module-tempfile.html">tempfile.mkstemp()</a> returns:</p> <blockquote> <p>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.</p> </blockquote> <p>How do I convert that OS-level handle to a file object?</p> <p>The <a href="http://www.python.org/doc/2.5.2/lib/os-fd-ops.html">documentation for os.open()</a> states: </p> <blockquote> <p>To wrap a file descriptor in a "file object", use fdopen().</p> </blockquote> <p>So I tried:</p> <pre><code>&gt;&gt;&gt; import tempfile &gt;&gt;&gt; tup = tempfile.mkstemp() &gt;&gt;&gt; import os &gt;&gt;&gt; f = os.fdopen(tup[0]) &gt;&gt;&gt; f.write('foo\n') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? IOError: [Errno 9] Bad file descriptor </code></pre>
41
2008-10-03T19:41:04Z
2,414,333
<pre><code>temp = tempfile.NamedTemporaryFile(delete=False) temp.file.write('foo\n') temp.close() </code></pre>
4
2010-03-10T03:33:07Z
[ "python", "temporary-files", "mkstemp", "fdopen" ]
Python - How do I convert "an OS-level handle to an open file" to a file object?
168,559
<p><a href="http://www.python.org/doc/2.5.2/lib/module-tempfile.html">tempfile.mkstemp()</a> returns:</p> <blockquote> <p>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.</p> </blockquote> <p>How do I convert that OS-level handle to a file object?</p> <p>The <a href="http://www.python.org/doc/2.5.2/lib/os-fd-ops.html">documentation for os.open()</a> states: </p> <blockquote> <p>To wrap a file descriptor in a "file object", use fdopen().</p> </blockquote> <p>So I tried:</p> <pre><code>&gt;&gt;&gt; import tempfile &gt;&gt;&gt; tup = tempfile.mkstemp() &gt;&gt;&gt; import os &gt;&gt;&gt; f = os.fdopen(tup[0]) &gt;&gt;&gt; f.write('foo\n') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? IOError: [Errno 9] Bad file descriptor </code></pre>
41
2008-10-03T19:41:04Z
16,942,329
<p>I can't comment on the answers, so I will post my comment here:</p> <p>To create a temporary file for write access you can use tempfile.mkstemp and specify "w" as the last parameter, like:</p> <pre><code>f = tempfile.mkstemp("", "", "", "w") # first three params are 'suffix, 'prefix', 'dir'... os.write(f[0], "write something") </code></pre>
0
2013-06-05T14:15:44Z
[ "python", "temporary-files", "mkstemp", "fdopen" ]
Now that Python 2.6 is out, what modules currently in the language should every programmer know about?
168,727
<p>A lot of useful features in Python are somewhat "hidden" inside modules. Named tuples (new in <a href="http://docs.python.org/whatsnew/2.6.html" rel="nofollow">Python 2.6</a>), for instance, are found in the <a href="http://docs.python.org/library/collections.html" rel="nofollow">collections</a> module. </p> <p>The <a href="http://docs.python.org/library/" rel="nofollow">Library Documentation page</a> 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 <em>this way</em> using Python!" unless the important features in the language are pointed out by the experienced developers.</p> <p>I'm <strong>not</strong> specifically looking for new modules in Python 2.6, but modules that can be found in this latest release.</p>
9
2008-10-03T20:23:12Z
168,766
<p>May be <a href="http://www.python.org/dev/peps/pep-0361/" rel="nofollow">PEP 0631</a> and <a href="http://docs.python.org/whatsnew/2.6.html" rel="nofollow">What's new in 2.6</a> can provide elements of answer. This last article explains the new features in Python 2.6, released on October 1 2008.</p>
5
2008-10-03T20:30:29Z
[ "python", "module", "language-features" ]
Now that Python 2.6 is out, what modules currently in the language should every programmer know about?
168,727
<p>A lot of useful features in Python are somewhat "hidden" inside modules. Named tuples (new in <a href="http://docs.python.org/whatsnew/2.6.html" rel="nofollow">Python 2.6</a>), for instance, are found in the <a href="http://docs.python.org/library/collections.html" rel="nofollow">collections</a> module. </p> <p>The <a href="http://docs.python.org/library/" rel="nofollow">Library Documentation page</a> 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 <em>this way</em> using Python!" unless the important features in the language are pointed out by the experienced developers.</p> <p>I'm <strong>not</strong> specifically looking for new modules in Python 2.6, but modules that can be found in this latest release.</p>
9
2008-10-03T20:23:12Z
168,768
<p>The most impressive new module is probably the <code>multiprocessing</code> 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 <code>threading</code> module. But more importantly because it introduces a lot of great classes for communicating between processes, such as a <code>Queue</code> class and a <code>Lock</code> 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.</p> <p>You can find the documentation at <a href="http://docs.python.org/library/multiprocessing.html" rel="nofollow">http://docs.python.org/library/multiprocessing.html</a></p>
12
2008-10-03T20:31:13Z
[ "python", "module", "language-features" ]
Now that Python 2.6 is out, what modules currently in the language should every programmer know about?
168,727
<p>A lot of useful features in Python are somewhat "hidden" inside modules. Named tuples (new in <a href="http://docs.python.org/whatsnew/2.6.html" rel="nofollow">Python 2.6</a>), for instance, are found in the <a href="http://docs.python.org/library/collections.html" rel="nofollow">collections</a> module. </p> <p>The <a href="http://docs.python.org/library/" rel="nofollow">Library Documentation page</a> 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 <em>this way</em> using Python!" unless the important features in the language are pointed out by the experienced developers.</p> <p>I'm <strong>not</strong> specifically looking for new modules in Python 2.6, but modules that can be found in this latest release.</p>
9
2008-10-03T20:23:12Z
168,795
<p>The <a href="http://docs.python.org/library/json.html" rel="nofollow">new <code>json</code> module</a> is a real boon to web programmers!! (It was known as <a href="http://undefined.org/python/#simplejson" rel="nofollow"><code>simplejson</code></a> before being merged into the standard library.)</p> <p>It's ridiculously easy to use: <code>json.dumps(obj)</code> encodes a built-in-type Python object to a JSON string, while <code>json.loads(string)</code> decodes a JSON string into a Python object.</p> <p>Really really handy.</p>
6
2008-10-03T20:39:54Z
[ "python", "module", "language-features" ]
Now that Python 2.6 is out, what modules currently in the language should every programmer know about?
168,727
<p>A lot of useful features in Python are somewhat "hidden" inside modules. Named tuples (new in <a href="http://docs.python.org/whatsnew/2.6.html" rel="nofollow">Python 2.6</a>), for instance, are found in the <a href="http://docs.python.org/library/collections.html" rel="nofollow">collections</a> module. </p> <p>The <a href="http://docs.python.org/library/" rel="nofollow">Library Documentation page</a> 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 <em>this way</em> using Python!" unless the important features in the language are pointed out by the experienced developers.</p> <p>I'm <strong>not</strong> specifically looking for new modules in Python 2.6, but modules that can be found in this latest release.</p>
9
2008-10-03T20:23:12Z
335,299
<p><strong>Essential Libraries</strong></p> <p>The main challenge for an experienced programmer coming from another language to Python is figuring out how one language maps to another. Here are a few essential libraries and how they relate to Java equivalents.</p> <pre><code>os, os.path </code></pre> <p>Has functionality like in java.io.File, java.lang.Process, and others. But cleaner and more sophisticated, with a Unix flavor. Use os.path instead of os for higher-level functionality.</p> <pre><code>sys </code></pre> <p>Manipulate the sys.path (which is like the classpath), register exit handlers (like in java Runtime object), and access the standard I/O streams, as in java.lang.System. </p> <pre><code>unittest </code></pre> <p>Very similar (and based on) jUnit, with test fixtures and runnable harnesses.</p> <pre><code>logging </code></pre> <p>Functionality almost identical to log4j with loglevels and loggers. ( logging is also in the standard java.util.Logging library)</p> <pre><code>datetime </code></pre> <p>Allows parsing and formatting dates and times, like in java.text.DateFormat, java.util.Date and related.</p> <pre><code>ConfigParser </code></pre> <p>Allows persistant configuration as in a java Properties file (but also allows nesting). Use this when you don't want the complexity of XML or a database backend.</p> <pre><code>socket, urllib </code></pre> <p>Similar functionality to what is in java.net, for working with either sockets, or retrieving content via URLs/URIs.</p> <p>Also, keep in mind that a lot of basic functionality, such as reading files, and working with collections, is in the core python language, whereas in Java it lives in packages. </p>
3
2008-12-02T20:24:27Z
[ "python", "module", "language-features" ]
Python - How do I write a decorator that restores the cwd?
169,070
<p>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.</p>
19
2008-10-03T22:04:01Z
169,079
<pre><code>def preserve_cwd(function): def decorator(*args, **kwargs): cwd = os.getcwd() result = function(*args, **kwargs) os.chdir(cwd) return result return decorator </code></pre> <p>Here's how it's used:</p> <pre><code>@preserve_cwd def test(): print 'was:',os.getcwd() os.chdir('/') print 'now:',os.getcwd() &gt;&gt;&gt; print os.getcwd() /Users/dspitzer &gt;&gt;&gt; test() was: /Users/dspitzer now: / &gt;&gt;&gt; print os.getcwd() /Users/dspitzer </code></pre>
3
2008-10-03T22:06:46Z
[ "python", "decorator", "cwd" ]
Python - How do I write a decorator that restores the cwd?
169,070
<p>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.</p>
19
2008-10-03T22:04:01Z
169,112
<p>The answer for a decorator has been given; it works at the function definition stage as requested.</p> <p>With Python 2.5+, you also have an option to do that at the function <em>call</em> stage using a context manager:</p> <pre><code>from __future__ import with_statement # needed for 2.5 ≤ Python &lt; 2.6 import contextlib, os @contextlib.contextmanager def remember_cwd(): curdir= os.getcwd() try: yield finally: os.chdir(curdir) </code></pre> <p>which can be used if needed at the function call time as:</p> <pre><code>print "getcwd before:", os.getcwd() with remember_cwd(): walk_around_the_filesystem() print "getcwd after:", os.getcwd() </code></pre> <p>It's a nice option to have.</p> <p>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.</p>
27
2008-10-03T22:19:30Z
[ "python", "decorator", "cwd" ]
Python - How do I write a decorator that restores the cwd?
169,070
<p>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.</p>
19
2008-10-03T22:04:01Z
170,174
<p>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.</p> <p>as a decorator:</p> <pre><code>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 </code></pre> <p>and as a context manager:</p> <pre><code>@contextlib.contextmanager def remember_cwd(): curdir = os.getcwd() try: yield finally: os.chdir(curdir) </code></pre>
16
2008-10-04T11:29:33Z
[ "python", "decorator", "cwd" ]
Python - How do I write a decorator that restores the cwd?
169,070
<p>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.</p>
19
2008-10-03T22:04:01Z
14,019,583
<p>The <a href="https://github.com/jaraco/path.py">path.py</a> module (which you really should use if dealing with paths in python scripts) has a context manager:</p> <pre><code>subdir = d / 'subdir' #subdir is a path object, in the path.py module with subdir: # here current dir is subdir #not anymore </code></pre> <p>(credits goes to <a href="http://lateral.netmanagers.com.ar/weblog/posts/BB963.html">this blog post</a> from Roberto Alsina)</p>
8
2012-12-24T09:38:59Z
[ "python", "decorator", "cwd" ]
How can I compress a folder and email the compressed file in Python?
169,362
<p>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? </p>
7
2008-10-03T23:53:35Z
169,395
<p>Look at <a href="http://www.python.org/doc/2.5.2/lib/module-zipfile.html" rel="nofollow">zipfile</a> for compressing a folder and it's subfolders.</p> <p>Look at <a href="http://www.python.org/doc/2.5.2/lib/module-smtplib.html" rel="nofollow">smtplib</a> for an email client.</p>
1
2008-10-04T00:10:26Z
[ "python" ]
How can I compress a folder and email the compressed file in Python?
169,362
<p>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? </p>
7
2008-10-03T23:53:35Z
169,403
<p>You can use <a href="http://www.python.org/doc/2.5.2/lib/module-zipfile.html" rel="nofollow">zipfile</a> that ships with python, and <a href="http://snippets.dzone.com/posts/show/2038" rel="nofollow">here</a> you can find an example of sending an email with attachments with the standard smtplib</p>
0
2008-10-04T00:14:54Z
[ "python" ]
How can I compress a folder and email the compressed file in Python?
169,362
<p>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? </p>
7
2008-10-03T23:53:35Z
169,406
<p>You can use the <a href="http://docs.python.org/dev/library/zipfile.html">zipfile</a> module to compress the file using the zip standard, the <a href="http://docs.python.org/dev/library/email.html">email</a> module to create the email with the attachment, and the <a href="http://docs.python.org/dev/library/smtplib.html">smtplib</a> module to send it - all using only the standard library.</p> <h1>Python - Batteries Included</h1> <p>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 <code>homework</code> tag, well, here it is:</p> <pre><code>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() </code></pre> <p>With this function, you can just do:</p> <pre><code>send_file_zipped('result.txt', ['[email protected]']) </code></pre> <p>You're welcome.</p>
18
2008-10-04T00:17:28Z
[ "python" ]
2D animation in Python
169,810
<p>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.</p> <p>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.</p> <p>Requirements are:</p> <ul> <li>Cross-platform (Linux, MacOS X, Windows)</li> <li>Low complexity overhead</li> <li>Plays well with wxpython (at least won't step on each other's toes unduly)</li> <li>Interactivity. Detect when objects are clicked on, moused over, etc. </li> </ul> <p>Note that high performance isn't on the list, but the ability to handle ~100 bitmap objects on the screen would be good.</p> <p>Your thoughts?</p>
6
2008-10-04T05:36:23Z
169,825
<p>I am a fan of <a href="http://pyglet.org" rel="nofollow">pyglet</a> which is a completely self contained library for doing graphical work under win32, linux, and OS X. </p> <p>It has very low overhead, and you can see this for yourself from the tutorial on the website. It <em>should</em> play well with wxpython, or at least I seem to recall posts to the mailing list about wxpython and pyglet being used together.</p> <p>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.</p> <p><a href="https://github.com/freespace/mactorii" rel="nofollow">mactorii</a> 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</p>
10
2008-10-04T05:50:03Z
[ "python", "animation", "2d" ]
2D animation in Python
169,810
<p>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.</p> <p>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.</p> <p>Requirements are:</p> <ul> <li>Cross-platform (Linux, MacOS X, Windows)</li> <li>Low complexity overhead</li> <li>Plays well with wxpython (at least won't step on each other's toes unduly)</li> <li>Interactivity. Detect when objects are clicked on, moused over, etc. </li> </ul> <p>Note that high performance isn't on the list, but the ability to handle ~100 bitmap objects on the screen would be good.</p> <p>Your thoughts?</p>
6
2008-10-04T05:36:23Z
1,568,711
<p>You can try pygame, its very easy to handle and similar to SDL under c++</p>
3
2009-10-14T20:16:46Z
[ "python", "animation", "2d" ]
How to package Twisted program with py2exe?
169,897
<p>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. </p> <p>And I found the py2exe said:</p> <blockquote> <p>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']</p> </blockquote> <p>So how do I solve this problem?</p> <p>Thanks.</p>
10
2008-10-04T07:08:05Z
169,913
<p>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.</p> <p>You can explicitly specify modules to include on the py2exe command line:</p> <pre><code>python setup.py py2exe -p win32com -i twisted.web.resource </code></pre> <p>Something like that. Read up on the options and experiment.</p>
10
2008-10-04T07:21:29Z
[ "python", "twisted", "py2exe" ]
How to package Twisted program with py2exe?
169,897
<p>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. </p> <p>And I found the py2exe said:</p> <blockquote> <p>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']</p> </blockquote> <p>So how do I solve this problem?</p> <p>Thanks.</p>
10
2008-10-04T07:08:05Z
31,598,939
<p>Had same issue with email module. I got it working by explicitly including modules in setup.py:</p> <p>OLD setup.py:</p> <pre><code>setup(console = ['main.py']) </code></pre> <p>New setup.py:</p> <pre><code>setup(console = ['main.py'], options={"py2exe":{"includes":["email.mime.multipart","email.mime.text"]}}) </code></pre>
0
2015-07-23T22:10:36Z
[ "python", "twisted", "py2exe" ]
USB Driver Development on a Mac using Python
170,278
<p>I would like to write a driver to talk to my Suunto t3 watch in Python on a Mac. My day job is doing basic web work in C# so my familiarity with Python and developing on a Mac is limited.</p> <p>Can you suggest how one would start doing driver development in general and then more specifically on a Mac. I.e. how to easily see what data is being transmitted to the device? I have Python 2.5 (MacPorts) up and running.</p>
4
2008-10-04T12:45:46Z
170,368
<p>If the watch supports a <a href="http://www.usb.org/developers/devclass_docs#approved" rel="nofollow">standard USB device class specification</a> such as HID or serial communication, there might already be a Macintosh driver for it built into the OS. Otherwise, you're going to have to get information about the vendor commands used to communicate with it from one of three sources: the manufacturer; reverse engineering the protocol used by the Windows driver; or from others who have already reverse engineered the protocol in order to support the device on Linux or BSD.</p> <p>USB is a packet-based bus and it's very important to understand the various transaction types. Reading the <a href="http://www.usb.org/developers/docs/" rel="nofollow">USB specification</a> is a good place to start.</p> <p>You can see what data is being transmitted to the device using a USB bus analyzer, which is an expensive proposition for a hobbyist but is well within the reach of most businesses doing USB development. For example, the <a href="http://www.getcatalyst.com/product-conquest.html" rel="nofollow">Catalyst Conquest</a> is $1199. Another established manufacturer is <a href="http://www.lecroy.com/tm/products/ProtocolAnalyzers/usb.asp?menuid=67" rel="nofollow">LeCroy (formerly CATC)</a>. There are also software USB analyzers that hook into the OS's USB stack, but they don't show all of the traffic on the bus, and may not be as reliable.</p> <p>I'm not a Mac expert, so take this paragraph with a grain of salt: Apple has a driver development kit called the <a href="http://developer.apple.com/referencelibrary/GettingStarted/GS_HardwareDrivers/index.html" rel="nofollow">I/O Kit</a>, which apparently requires you to write your driver in C++, unless they also have some sort of user-mode driver framework. If you're writing it in Python, it will probably be more like a Python library that interfaces to someone else's (Apple's?) generic USB driver.</p>
3
2008-10-04T13:55:06Z
[ "python", "osx", "usb", "drivers" ]
USB Driver Development on a Mac using Python
170,278
<p>I would like to write a driver to talk to my Suunto t3 watch in Python on a Mac. My day job is doing basic web work in C# so my familiarity with Python and developing on a Mac is limited.</p> <p>Can you suggest how one would start doing driver development in general and then more specifically on a Mac. I.e. how to easily see what data is being transmitted to the device? I have Python 2.5 (MacPorts) up and running.</p>
4
2008-10-04T12:45:46Z
170,409
<p>The Mac already has the underlying infrastructure to support USB, so you'll need a Python library that can take advantage of it. For any Python project that needs serial support, whether it's USB, RS-232 or GPIB, I'd recommend the PyVisa library at SourceForge. See <a href="http://pyvisa.sourceforge.net/" rel="nofollow">http://pyvisa.sourceforge.net/</a>.</p> <p>If your device doesn't have a VISA driver, you'll have to deal with the USB system directly. You can use another library on SourceForge for that: <a href="http://pyusb.berlios.de/" rel="nofollow">http://pyusb.berlios.de/</a></p>
4
2008-10-04T14:20:31Z
[ "python", "osx", "usb", "drivers" ]
Django signals vs. overriding save method
170,337
<p>I'm having trouble wrapping my head around this. Right now I have some models that looks kind of like this:</p> <pre><code> 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() </code></pre> <p>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?</p>
49
2008-10-04T13:37:12Z
170,369
<p>If you'll use signals you'd be able to update Review score each time related score model gets saved. But if don't need such functionality i don't see any reason to put this into signal, that's pretty model-related stuff.</p>
2
2008-10-04T13:55:25Z
[ "python", "django", "django-models", "django-signals" ]
Django signals vs. overriding save method
170,337
<p>I'm having trouble wrapping my head around this. Right now I have some models that looks kind of like this:</p> <pre><code> 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() </code></pre> <p>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?</p>
49
2008-10-04T13:37:12Z
170,501
<p>It is a kind sort of denormalisation. Look at this <a href="http://groups.google.com/group/django-developers/msg/248e53722acab49e" rel="nofollow">pretty solution</a>. In-place composition field definition.</p>
1
2008-10-04T15:21:21Z
[ "python", "django", "django-models", "django-signals" ]
Django signals vs. overriding save method
170,337
<p>I'm having trouble wrapping my head around this. Right now I have some models that looks kind of like this:</p> <pre><code> 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() </code></pre> <p>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?</p>
49
2008-10-04T13:37:12Z
171,703
<p>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.</p> <p>One common task in overridden <code>save</code> 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 <code>pre_save</code> 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.</p> <p>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.</p> <p>With <a href="https://github.com/django-mptt/django-mptt/">django-mptt</a>, for example, I used the <code>pre_save</code> 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 <code>pre_delete</code> 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 <code>save</code> or <code>delete</code> 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.</p>
57
2008-10-05T08:38:39Z
[ "python", "django", "django-models", "django-signals" ]
Django signals vs. overriding save method
170,337
<p>I'm having trouble wrapping my head around this. Right now I have some models that looks kind of like this:</p> <pre><code> 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() </code></pre> <p>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?</p>
49
2008-10-04T13:37:12Z
5,435,579
<p>Signals are useful when you have to execute some long term process and don't want to block your user waiting for save to complete.</p>
-14
2011-03-25T16:53:35Z
[ "python", "django", "django-models", "django-signals" ]
Django signals vs. overriding save method
170,337
<p>I'm having trouble wrapping my head around this. Right now I have some models that looks kind of like this:</p> <pre><code> 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() </code></pre> <p>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?</p>
49
2008-10-04T13:37:12Z
35,888,559
<p>You asked: </p> <p><em>Would there be any benefits to using Django's signal dispatcher?</em></p> <p>I found this in the django docs:</p> <blockquote> <p>Overridden model methods are not called on bulk operations</p> <p>Note that the delete() method for an object is not necessarily called when deleting objects in bulk using a QuerySet or as a result of a cascading delete. To ensure customized delete logic gets executed, you can use pre_delete and/or post_delete signals.</p> <p>Unfortunately, there isn’t a workaround when creating or updating objects in bulk, since none of save(), pre_save, and post_save are called.</p> </blockquote> <p>From: <a href="https://docs.djangoproject.com/en/dev/topics/db/models/#overriding-predefined-model-methods" rel="nofollow">Overriding predefined model methods</a></p>
4
2016-03-09T10:10:16Z
[ "python", "django", "django-models", "django-signals" ]
How do I write to a log from mod_python under apache?
170,353
<p>I seem to only be able to write to the Apache error log via stderr. Anyone know of a more structured logging architecture that I could use from my python web project, like commons?</p>
2
2008-10-04T13:46:06Z
170,366
<p>I've used the builtin <a href="http://www.python.org/doc/2.5.2/lib/module-logging.html" rel="nofollow">Python logging module</a> in (non-web) projects in the past, with success - it should work in a web-hosted environment as well.</p>
2
2008-10-04T13:54:49Z
[ "python", "apache", "logging" ]
How do I write to a log from mod_python under apache?
170,353
<p>I seem to only be able to write to the Apache error log via stderr. Anyone know of a more structured logging architecture that I could use from my python web project, like commons?</p>
2
2008-10-04T13:46:06Z
170,792
<p>There isn't any built in support for mod_python logging to Apache currently. If you really want to work within the Apache logs you can check out this thread (make sure you get the second version of the posted code, rather than the first):</p> <ul> <li><a href="http://www.dojoforum.com/node/13239" rel="nofollow">http://www.dojoforum.com/node/13239</a></li> <li><a href="http://www.modpython.org/pipermail/mod_python/2005-October/019295.html" rel="nofollow">http://www.modpython.org/pipermail/mod_python/2005-October/019295.html</a></li> </ul> <p>If you're just looking to use a more structured logging system, the Python standard logging module referred to by Blair is very feature complete. Aside from the Python.org docs Blair linked, here's a more in-depth look at the module's features from onLamp: </p> <ul> <li><a href="http://www.onlamp.com/pub/a/python/2005/06/02/logging.html" rel="nofollow">http://www.onlamp.com/pub/a/python/2005/06/02/logging.html</a></li> </ul> <p>And for a quickie example usage: </p> <ul> <li><a href="http://hackmap.blogspot.com/2007/06/note-to-self-using-python-logging.html" rel="nofollow">http://hackmap.blogspot.com/2007/06/note-to-self-using-python-logging.html</a></li> </ul>
3
2008-10-04T18:16:55Z
[ "python", "apache", "logging" ]
How do I write to a log from mod_python under apache?
170,353
<p>I seem to only be able to write to the Apache error log via stderr. Anyone know of a more structured logging architecture that I could use from my python web project, like commons?</p>
2
2008-10-04T13:46:06Z
183,615
<p>I concur with Blair Conrad's post about the Python logging module. The standard log handlers sometimes drop messages however. It's worth using the logging module's SocketHandler and building a receiver to listen for messages and write them to file.</p> <p>Here's mine: <a href="http://www.djangosnippets.org/snippets/1116/" rel="nofollow">Example SocketHandler receiver</a>.</p>
0
2008-10-08T16:19:16Z
[ "python", "apache", "logging" ]
How do I write to a log from mod_python under apache?
170,353
<p>I seem to only be able to write to the Apache error log via stderr. Anyone know of a more structured logging architecture that I could use from my python web project, like commons?</p>
2
2008-10-04T13:46:06Z
14,752,499
<p>This must have changed in the past four years. If you come across this question and want to do this then you can do it through the request object, i.e</p> <pre><code>def handler(req) : req.log_error('Hello apache') </code></pre>
2
2013-02-07T13:39:14Z
[ "python", "apache", "logging" ]
UNIX shell written in a reasonable language?
171,267
<p>Has anyone ever heard of a UNIX shell written in a reasonable language, like Python?</p>
10
2008-10-05T00:42:54Z
171,271
<p>Well, there's emacs, which is arguably a shell written in lisp :)</p> <p>Seriously though, are you looking for a reimplementation of an existing shell design in a different language such as Python? Or are you looking for a new implementation of a shell language that looks similar to your language of choice?</p>
5
2008-10-05T00:45:09Z
[ "python", "unix", "shell" ]
UNIX shell written in a reasonable language?
171,267
<p>Has anyone ever heard of a UNIX shell written in a reasonable language, like Python?</p>
10
2008-10-05T00:42:54Z
171,280
<p><a href="http://ipython.scipy.org/moin/" rel="nofollow">iPython</a> (Python) and <a href="http://rush.heroku.com/" rel="nofollow">Rush</a> (Ruby) are shells that are designed for more advanced languages. There's also Hotwire, which is sort of a weird integrated shell/terminal emulator.</p>
10
2008-10-05T00:52:02Z
[ "python", "unix", "shell" ]
UNIX shell written in a reasonable language?
171,267
<p>Has anyone ever heard of a UNIX shell written in a reasonable language, like Python?</p>
10
2008-10-05T00:42:54Z
171,290
<p>Tclsh is pretty nice (assuming you like Tcl, of course).</p>
3
2008-10-05T01:05:42Z
[ "python", "unix", "shell" ]
UNIX shell written in a reasonable language?
171,267
<p>Has anyone ever heard of a UNIX shell written in a reasonable language, like Python?</p>
10
2008-10-05T00:42:54Z
171,294
<ul> <li><a href="http://www.gnu.org/software/emacs/manual/html_node/eshell/index.html" rel="nofollow">Eshell</a> is a Bash-like shell in Emacs Lisp.</li> <li>IPython can be <a href="http://ipython.org/ipython-doc/stable/interactive/shell.html" rel="nofollow">used as a system shell</a>, though the syntax is a bit weird (supporting all of Python plus basic sh constructs).</li> <li><a href="http://fishshell.com/" rel="nofollow">fish</a> 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.</li> <li><a href="https://code.google.com/p/hotwire-shell/" rel="nofollow">Hotwire</a> 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.</li> <li><a href="http://www.pardus.nl/projects/zoidberg/" rel="nofollow">Zoidberg</a> is written in Perl and uses Perl syntax. A nice-looking project, shame it seems to have stalled.</li> <li><a href="http://www.scsh.net/" rel="nofollow">Scsh</a> would be a pain to use as a login shell (an example command from the docs: <code>(run/strings (find "." -name *.c -print))</code>), but it looks like a good "Perl in Scheme."</li> </ul>
22
2008-10-05T01:08:31Z
[ "python", "unix", "shell" ]
UNIX shell written in a reasonable language?
171,267
<p>Has anyone ever heard of a UNIX shell written in a reasonable language, like Python?</p>
10
2008-10-05T00:42:54Z
171,304
<p>From all appearances, Python IS a shell. It runs with <code>#!</code> and it can run interactively. Between the <code>os</code> and <code>shutil</code> packages you have all of the features of standard Unix shells.</p> <p>Since you can do anything in Python with simple, powerful scripts, you don't really need to spend any time messing with the other shells.</p>
6
2008-10-05T01:15:26Z
[ "python", "unix", "shell" ]
UNIX shell written in a reasonable language?
171,267
<p>Has anyone ever heard of a UNIX shell written in a reasonable language, like Python?</p>
10
2008-10-05T00:42:54Z
39,234,819
<p>There is xon now:</p> <p><a href="http://xon.sh/" rel="nofollow">http://xon.sh/</a></p> <p><a href="http://xon.sh/tutorial.html#running-commands" rel="nofollow">http://xon.sh/tutorial.html#running-commands</a></p> <p>PyCon video - <a href="https://www.youtube.com/watch?v=uaje5I22kgE" rel="nofollow">https://www.youtube.com/watch?v=uaje5I22kgE</a></p>
0
2016-08-30T18:37:50Z
[ "python", "unix", "shell" ]
Sorting music
171,277
<p>So over the years, I've bought music off iTunes, Urge, and Rhapsody and all these files are lying mixed with my non-DRM'd MP3 files that I've ripped off my CDs. Now some of these files have licenses that have expired, and some of them have valid licenses.</p> <p>I want to sort my music by various DRM/license restrictions that they have on them. This will make it easier for my to delete the music that I don't have subscription to, and all know which files I can carry on which music player.</p> <p>Does anyone know if this is possible in .NET/Perl/Python i.e. are there any libraries available that will help me do this?</p>
6
2008-10-05T00:49:51Z
171,284
<p>Do all the files have different extensions? If so this might work (i wrote it all off the top of my head so its not tested):</p> <pre><code>import os music_dir = "/home/johnbloggs/music/" # note the forward slashes and the trailing slash output_dir = "/home/johnbloggs/sorted_music/" for file in os.listdir(music_dir): if file.find(".mp3") != -1: if os.path.exists(output_dir + "mp3"): os.system("cp " + music_dir + file " " + output_dir + "mp3") elif file.find(".wma") != -1: if os.path.exists(output_dir + "wma"): os.system("cp " + music_dir + file " " + output_dir + "wma") # etc </code></pre> <p>This is written with Linux in mind. If you are looking to actually read the license type from inside the file, that will be considerably more difficult</p>
0
2008-10-05T01:01:00Z
[ "c#", "python", "perl", "mp3", "music" ]
Sorting music
171,277
<p>So over the years, I've bought music off iTunes, Urge, and Rhapsody and all these files are lying mixed with my non-DRM'd MP3 files that I've ripped off my CDs. Now some of these files have licenses that have expired, and some of them have valid licenses.</p> <p>I want to sort my music by various DRM/license restrictions that they have on them. This will make it easier for my to delete the music that I don't have subscription to, and all know which files I can carry on which music player.</p> <p>Does anyone know if this is possible in .NET/Perl/Python i.e. are there any libraries available that will help me do this?</p>
6
2008-10-05T00:49:51Z
171,297
<p>Wouldn't it be great if DRM made sense like other API's? </p> <p>Sadly, you'll have to research each DRM scheme and locate a client API for that DRM scheme.</p> <p>See this <a href="http://www.linuxdevices.com/news/NS2351492178.html" rel="nofollow">article</a> for a proposal to try and cope with the various inane DRM "solutions".</p>
4
2008-10-05T01:10:41Z
[ "c#", "python", "perl", "mp3", "music" ]
Sorting music
171,277
<p>So over the years, I've bought music off iTunes, Urge, and Rhapsody and all these files are lying mixed with my non-DRM'd MP3 files that I've ripped off my CDs. Now some of these files have licenses that have expired, and some of them have valid licenses.</p> <p>I want to sort my music by various DRM/license restrictions that they have on them. This will make it easier for my to delete the music that I don't have subscription to, and all know which files I can carry on which music player.</p> <p>Does anyone know if this is possible in .NET/Perl/Python i.e. are there any libraries available that will help me do this?</p>
6
2008-10-05T00:49:51Z
171,780
<p>I have come across this problem too and wrote a python function to fix it; my advice is to cut your losses with the DRM files and just move them out of whatever program you are using for playlists etc. The typical issue is m4p's mixed in with your mp3's and m4a's; whatever your mix this will move all drm'd files into a new folder at <code>C:\drm_music</code>:</p> <pre><code>import os, shutil def move_drm_files(music_folder): all_songs = [] good_filetypes = ['mp3', 'm4a', 'ogg', 'flv', 'wma'] for root, dirs, files in os.walk(music_folder): for name in files: full_name = os.path.join(root, name) all_songs.append(full_name) os.mkdir('/drm_music') for song in all_songs: if song[-3:] not in good_filetypes: shutil.move(song, '/drm_music') </code></pre> <p>So for example you could run the above with <code>python -i move_drm.py</code> (saving the script as <code>move_drm.py</code>) and call <code>move_drm_files('/users/alienfluid/music')</code>, and all the drm'd filetypes would be moved to their own quarantined folder. If you think you can save some of those you could do this to sort the drm files by type:</p> <pre><code>def sort_drm(drm_folder, all_songs=[]): os.mkdir('/drm_collection') known_types = [] for root, dirs, files in os.walk(drm_folder): for name in files: full_name = os.path.join(root, name) all_songs.append(full_name) for item in all_songs: if item[-3:] not in known_types: known_types.append(item[-3:]) for item in known_types: os.mkdir('/drm_collection/'+item) for item in all_songs: shutil.copy2(item, '/drm_collection/'+item[-3:]) </code></pre> <p>This will create a folder at <code>C:\drm_collection</code> with subfolders named for their extension (m4p etc), and they will be filled with all instances of each type; if you run the first function, you could just save the second one in the same file and call <code>sort_drm('/drm_music')</code></p>
1
2008-10-05T10:04:56Z
[ "c#", "python", "perl", "mp3", "music" ]
Sorting music
171,277
<p>So over the years, I've bought music off iTunes, Urge, and Rhapsody and all these files are lying mixed with my non-DRM'd MP3 files that I've ripped off my CDs. Now some of these files have licenses that have expired, and some of them have valid licenses.</p> <p>I want to sort my music by various DRM/license restrictions that they have on them. This will make it easier for my to delete the music that I don't have subscription to, and all know which files I can carry on which music player.</p> <p>Does anyone know if this is possible in .NET/Perl/Python i.e. are there any libraries available that will help me do this?</p>
6
2008-10-05T00:49:51Z
171,933
<p>If you need to look at the ID3 tags in the MP3 files then there are a few modules on CPAN that may help u (for eg... <a href="http://search.cpan.org/dist/MP3-Find/" rel="nofollow">MP3::Find</a> <a href="http://search.cpan.org/dist/MP3-Tag/" rel="nofollow">MP3::Tag</a> )</p> <p>Also these articles may help....</p> <ul> <li><a href="http://www.ibm.com/developerworks/linux/library/l-cpmp31.html" rel="nofollow">Cultured Perl: Fun with MP3 and Perl - IBM</a></li> <li><a href="https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5293815.html" rel="nofollow">Reading ID3 tags with Perl's MP3::Tag module - TechRepublic</a></li> </ul> <p>I think its the AENC tag you might be looking for. <a href="http://www.id3.org" rel="nofollow">http://www.id3.org</a></p> <p>/I3az/</p>
5
2008-10-05T12:57:50Z
[ "c#", "python", "perl", "mp3", "music" ]
How would I implement a Python bit map?
171,512
<p>I wish to implement a 2d bit map class in Python. The class would have the following requirements:</p> <ol> <li><p>Allow the creating of arbitrarily sized 2d bitmaps. i.e. to create an 8 x 8 bitmap (8 bytes), something like:</p> <pre><code>bitmap = Bitmap(8,8) </code></pre></li> <li><p>provide an API to access the bits in this 2d map as boolean or even integer values, i.e.:</p> <pre><code>if bitmap[1, 2] or bitmap.get(0, 1) </code></pre></li> <li><p>Able to retrieve the data as packed Binary data. Essentially it would be each row of the bit map concatenated and returned as Binary data. It may be padded to the nearest byte or something similar.</p> <pre><code>bitmap.data() </code></pre></li> <li><p>Be able to create new maps from the binary data retrieved:</p> <pre><code>new_bitmap = Bitmap(8, 8, bitmap.data()) </code></pre></li> </ol> <p>I know Python is able to perform binary operations, but I'd like some suggestions as how best to use them to implement this class.</p>
2
2008-10-05T04:51:11Z
171,611
<p>No need to create this yourself.</p> <p>Use the very good <a href="http://www.pythonware.com/products/pil/" rel="nofollow">Python Imaging Library</a> (PIL)</p>
3
2008-10-05T07:11:25Z
[ "python", "class" ]
How would I implement a Python bit map?
171,512
<p>I wish to implement a 2d bit map class in Python. The class would have the following requirements:</p> <ol> <li><p>Allow the creating of arbitrarily sized 2d bitmaps. i.e. to create an 8 x 8 bitmap (8 bytes), something like:</p> <pre><code>bitmap = Bitmap(8,8) </code></pre></li> <li><p>provide an API to access the bits in this 2d map as boolean or even integer values, i.e.:</p> <pre><code>if bitmap[1, 2] or bitmap.get(0, 1) </code></pre></li> <li><p>Able to retrieve the data as packed Binary data. Essentially it would be each row of the bit map concatenated and returned as Binary data. It may be padded to the nearest byte or something similar.</p> <pre><code>bitmap.data() </code></pre></li> <li><p>Be able to create new maps from the binary data retrieved:</p> <pre><code>new_bitmap = Bitmap(8, 8, bitmap.data()) </code></pre></li> </ol> <p>I know Python is able to perform binary operations, but I'd like some suggestions as how best to use them to implement this class.</p>
2
2008-10-05T04:51:11Z
171,672
<p><a href="http://mentat.za.net/numpy/refguide/routines.bitwise.xhtml#bit-packing" rel="nofollow">Bit-Packing</a> numpy ( <a href="http://www.scipy.org/" rel="nofollow">SciPY</a> ) arrays does what you are looking for. The example shows 4x3 bit (Boolean) array packed into 4 8-bit bytes. <em>unpackbits</em> unpacks uint8 arrays into a Boolean output array that you can use in computations.</p> <pre><code>&gt;&gt;&gt; a = np.array([[[1,0,1], ... [0,1,0]], ... [[1,1,0], ... [0,0,1]]]) &gt;&gt;&gt; b = np.packbits(a,axis=-1) &gt;&gt;&gt; b array([[[160],[64]],[[192],[32]]], dtype=uint8) </code></pre> <p>If you need 1-bit pixel images, PIL is the place to look.</p>
4
2008-10-05T08:16:06Z
[ "python", "class" ]
Formatting a list of text into columns
171,662
<p>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 <strong>string.join</strong> 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.</p> <p>I found an <a href="http://code.activestate.com/recipes/302380/">ActiveState page</a> 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?</p> <p><hr /></p> <p><strong>Edit</strong> Here is the list that I want to use.</p> <pre><code>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"] </code></pre> <p>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.</p> <pre><code>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 </code></pre>
11
2008-10-05T08:09:52Z
171,686
<pre><code>data = [ ("1","2"),("3","4") ] print "\n".join(map("\t".join,data)) </code></pre> <p>Not as flexible as the ActiveState solution, but shorter :-)</p>
0
2008-10-05T08:22:22Z
[ "python", "string", "formatting" ]
Formatting a list of text into columns
171,662
<p>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 <strong>string.join</strong> 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.</p> <p>I found an <a href="http://code.activestate.com/recipes/302380/">ActiveState page</a> 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?</p> <p><hr /></p> <p><strong>Edit</strong> Here is the list that I want to use.</p> <pre><code>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"] </code></pre> <p>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.</p> <pre><code>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 </code></pre>
11
2008-10-05T08:09:52Z
171,707
<p>Two columns, separated by tabs, joined into lines. Look in <em>itertools</em> for iterator equivalents, to achieve a space-efficient solution.</p> <pre><code>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 ... </code></pre> <p>Oops... got caught by S.Lott (thank you).</p> <p>A more general solution, handles any number of columns and odd lists. Slightly modified from <a href="http://stackoverflow.com/questions/171662/formatting-a-list-of-text-into-columns#173823">S.lott</a>, using generators to save space.</p> <pre><code>def fmtcols(mylist, cols): lines = ("\t".join(mylist[i:i+cols]) for i in xrange(0,len(mylist),cols)) return '\n'.join(lines) </code></pre>
10
2008-10-05T08:40:22Z
[ "python", "string", "formatting" ]
Formatting a list of text into columns
171,662
<p>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 <strong>string.join</strong> 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.</p> <p>I found an <a href="http://code.activestate.com/recipes/302380/">ActiveState page</a> 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?</p> <p><hr /></p> <p><strong>Edit</strong> Here is the list that I want to use.</p> <pre><code>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"] </code></pre> <p>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.</p> <pre><code>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 </code></pre>
11
2008-10-05T08:09:52Z
173,823
<p>It's long-winded, so I'll break it into two parts.</p> <pre><code>def columns( skills_defs, cols=2 ): pairs = [ "\t".join(skills_defs[i:i+cols]) for i in range(0,len(skills_defs),cols) ] return "\n".join( pairs ) </code></pre> <p>It can, obviously, be done as a single loooong statement.</p> <p>This works for an odd number of skills, also.</p>
3
2008-10-06T10:33:04Z
[ "python", "string", "formatting" ]
Formatting a list of text into columns
171,662
<p>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 <strong>string.join</strong> 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.</p> <p>I found an <a href="http://code.activestate.com/recipes/302380/">ActiveState page</a> 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?</p> <p><hr /></p> <p><strong>Edit</strong> Here is the list that I want to use.</p> <pre><code>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"] </code></pre> <p>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.</p> <pre><code>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 </code></pre>
11
2008-10-05T08:09:52Z
173,933
<p>The <code>format_columns</code> function should do what you want:</p> <pre><code>from __future__ import generators try: import itertools except ImportError: mymap, myzip= map, zip else: mymap, myzip= itertools.imap, itertools.izip def format_columns(string_list, columns, separator=" "): "Produce equal-width columns from string_list" sublists= [] # empty_str based on item 0 of string_list try: empty_str= type(string_list[0])() except IndexError: # string_list is empty return # create a sublist for every column for column in xrange(columns): sublists.append(string_list[column::columns]) # find maximum length of a column max_sublist_len= max(mymap(len, sublists)) # make all columns same length for sublist in sublists: if len(sublist) &lt; max_sublist_len: sublist.append(empty_str) # calculate a format string for the output lines format_str= separator.join( "%%-%ds" % max(mymap(len, sublist)) for sublist in sublists) for line_items in myzip(*sublists): yield format_str % line_items if __name__ == "__main__": 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"] for line in format_columns(skills_defs, 2): print line </code></pre> <p>This assumes that you have a Python with generators available.</p>
0
2008-10-06T11:21:44Z
[ "python", "string", "formatting" ]
Formatting a list of text into columns
171,662
<p>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 <strong>string.join</strong> 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.</p> <p>I found an <a href="http://code.activestate.com/recipes/302380/">ActiveState page</a> 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?</p> <p><hr /></p> <p><strong>Edit</strong> Here is the list that I want to use.</p> <pre><code>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"] </code></pre> <p>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.</p> <pre><code>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 </code></pre>
11
2008-10-05T08:09:52Z
12,721,559
<p>This may work</p> <pre><code>if len(skills_defs)%2: skills_defs.append("") for i in range(1, len( skills_defs), 2): print('{:&lt;60}{}'.format(skills_defs[i-1], skills_defs[i])) </code></pre> <p>See: <a href="http://docs.python.org/library/string.html#format-examples" rel="nofollow"> String format examples</a></p>
2
2012-10-04T06:34:10Z
[ "python", "string", "formatting" ]
Formatting a list of text into columns
171,662
<p>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 <strong>string.join</strong> 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.</p> <p>I found an <a href="http://code.activestate.com/recipes/302380/">ActiveState page</a> 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?</p> <p><hr /></p> <p><strong>Edit</strong> Here is the list that I want to use.</p> <pre><code>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"] </code></pre> <p>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.</p> <pre><code>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 </code></pre>
11
2008-10-05T08:09:52Z
24,876,899
<p>Here is an extension of the solution provided by gimel, which allows to print equally spaced columns.</p> <pre><code>def fmtcols(mylist, cols): maxwidth = max(map(lambda x: len(x), mylist)) justifyList = map(lambda x: x.ljust(maxwidth), mylist) lines = (' '.join(justifyList[i:i+cols]) for i in xrange(0,len(justifyList),cols)) print "\n".join(lines) </code></pre> <p>which returns something like this</p> <p><code>ACM:Aircraft Mechanic BC:Body Combat</code><br> <code>BIO:Biology CBE:Combat Engineer</code><br> <code>CHM:Chemistry CMP:Computers</code><br> <code>CRM:Combat Rifeman CVE:Civil Engineer</code><br> <code>DIS:Disguise ELC:Electronics</code> ... ...`</p>
2
2014-07-22T00:12:19Z
[ "python", "string", "formatting" ]
Formatting a list of text into columns
171,662
<p>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 <strong>string.join</strong> 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.</p> <p>I found an <a href="http://code.activestate.com/recipes/302380/">ActiveState page</a> 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?</p> <p><hr /></p> <p><strong>Edit</strong> Here is the list that I want to use.</p> <pre><code>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"] </code></pre> <p>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.</p> <pre><code>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 </code></pre>
11
2008-10-05T08:09:52Z
27,027,373
<p>I think many of these solutions are conflating two separate things into one.</p> <p>You want to:</p> <ol> <li>be able to force a string to be a certain width</li> <li>print a table</li> </ol> <p>Here's a really simple take on how to do this:</p> <pre><code>import sys 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"] # The only thing "colform" does is return a modified version of "txt" that is # ensured to be exactly "width" characters long. It truncates or adds spaces # on the end as needed. def colform(txt, width): if len(txt) &gt; width: txt = txt[:width] elif len(txt) &lt; width: txt = txt + (" " * (width - len(txt))) return txt # Now that you have colform you can use it to print out columns any way you wish. # Here's one brain-dead way to print in two columns: for i in xrange(len(skills_defs)): sys.stdout.write(colform(skills_defs[i], 30)) if i % 2 == 1: sys.stdout.write('\n') </code></pre>
0
2014-11-19T21:30:54Z
[ "python", "string", "formatting" ]
Applying a common font scheme to multiple objects in wxPython
171,694
<p>Many times I will use the same font scheme for static text in a wxPython application. Currently I am making a <strong>SetFont()</strong> call for each static text object but that seems like a lot of unnecessary work. However, the wxPython demo and <em>wxPython In Action</em> book don't discuss this.</p> <p>Is there a way to easily apply the same SetFont() method to all these text objects without making separate calls each time?</p>
3
2008-10-05T08:27:57Z
171,702
<p>Maybe try subclassing the text object and in your class <code>__init__</code> method just call SetFont()? </p> <p>Or, do something like:</p> <pre><code>def f(C): x = C() x.SetFont(font) # where font is defined somewhere else return x </code></pre> <p>and then just decorate every text object you create with with it:</p> <pre><code>text = f(wx.StaticText) </code></pre> <p>(of course, if <code>StaticText</code> constructor requires some parameters, it will require changing the first lines in <code>f</code> function definition).</p>
1
2008-10-05T08:38:36Z
[ "python", "fonts", "wxpython" ]
Applying a common font scheme to multiple objects in wxPython
171,694
<p>Many times I will use the same font scheme for static text in a wxPython application. Currently I am making a <strong>SetFont()</strong> call for each static text object but that seems like a lot of unnecessary work. However, the wxPython demo and <em>wxPython In Action</em> book don't discuss this.</p> <p>Is there a way to easily apply the same SetFont() method to all these text objects without making separate calls each time?</p>
3
2008-10-05T08:27:57Z
182,923
<p>If all widgets have already been created, you can apply <code>SetFont</code> recursively, for example with the following function:</p> <pre><code>def changeFontInChildren(win, font): ''' Set font in given window and all its descendants. @type win: L{wx.Window} @type font: L{wx.Font} ''' try: win.SetFont(font) except: pass # don't require all objects to support SetFont for child in win.GetChildren(): changeFontInChildren(child, font) </code></pre> <p>An example usage that causes all text in <code>frame</code> to become default font with italic style:</p> <pre><code>newFont = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT) newFont.SetStyle(wx.FONTSTYLE_ITALIC) changeFontInChildren(frame, newFont) </code></pre>
0
2008-10-08T14:01:16Z
[ "python", "fonts", "wxpython" ]