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
list
Using for...else in Python generators
603,641
<p>I'm a big fan of Python's <a href="http://docs.python.org/reference/compound_stmts.html#the-for-statement">for...else syntax</a> - it's surprising how often it's applicable, and how effectively it can simplify code.</p> <p>However, I've not figured out a nice way to use it in a generator, for example:</p> <pre><code>def iterate(i): for value in i: yield value else: print 'i is empty' </code></pre> <p>In the above example, I'd like the <code>print</code> statement to be executed only if <code>i</code> is empty. However, as <code>else</code> only respects <code>break</code> and <code>return</code>, it is always executed, regardless of the length of <code>i</code>.</p> <p>If it's impossible to use <code>for...else</code> in this way, what's the best approach to this so that the <code>print</code> statement is only executed when nothing is yielded?</p>
7
2009-03-02T19:28:09Z
603,830
<blockquote> <blockquote> <p>If it's impossible to use for...else in this way, what's the best approach to this so that the print statement is only executed when nothing is yielded?</p> </blockquote> </blockquote> <p>Maximum i can think of:</p> <pre> <code> >>> empty = True >>> for i in [1,2]: ... empty = False ... if empty: ... print 'empty' ... >>> >>> >>> empty = True >>> for i in []: ... empty = False ... if empty: ... print 'empty' ... empty >>> </code> </pre>
0
2009-03-02T20:16:42Z
[ "python", "syntax", "for-loop", "generator", "yield" ]
Using for...else in Python generators
603,641
<p>I'm a big fan of Python's <a href="http://docs.python.org/reference/compound_stmts.html#the-for-statement">for...else syntax</a> - it's surprising how often it's applicable, and how effectively it can simplify code.</p> <p>However, I've not figured out a nice way to use it in a generator, for example:</p> <pre><code>def iterate(i): for value in i: yield value else: print 'i is empty' </code></pre> <p>In the above example, I'd like the <code>print</code> statement to be executed only if <code>i</code> is empty. However, as <code>else</code> only respects <code>break</code> and <code>return</code>, it is always executed, regardless of the length of <code>i</code>.</p> <p>If it's impossible to use <code>for...else</code> in this way, what's the best approach to this so that the <code>print</code> statement is only executed when nothing is yielded?</p>
7
2009-03-02T19:28:09Z
603,913
<p>Summing up some of the earlier answers, it could be solved like this:</p> <pre><code>def iterate(i): empty = True for value in i: yield value empty = False if empty: print "empty" </code></pre> <p>so there really is no "else" clause involved.</p>
3
2009-03-02T20:45:06Z
[ "python", "syntax", "for-loop", "generator", "yield" ]
Using for...else in Python generators
603,641
<p>I'm a big fan of Python's <a href="http://docs.python.org/reference/compound_stmts.html#the-for-statement">for...else syntax</a> - it's surprising how often it's applicable, and how effectively it can simplify code.</p> <p>However, I've not figured out a nice way to use it in a generator, for example:</p> <pre><code>def iterate(i): for value in i: yield value else: print 'i is empty' </code></pre> <p>In the above example, I'd like the <code>print</code> statement to be executed only if <code>i</code> is empty. However, as <code>else</code> only respects <code>break</code> and <code>return</code>, it is always executed, regardless of the length of <code>i</code>.</p> <p>If it's impossible to use <code>for...else</code> in this way, what's the best approach to this so that the <code>print</code> statement is only executed when nothing is yielded?</p>
7
2009-03-02T19:28:09Z
1,985,466
<p>As you note, <code>for..else</code> only detects a <code>break</code>. So it's only applicable when you look for something and then <strong>stop</strong>.</p> <p>It's not applicable to your purpose not because it's a generator, but <strong>because you want to process all elements, without stopping</strong> (because you want to yield them all, but that's not the point).</p> <p>So generator or not, you really need a boolean, as in Ber's solution.</p>
3
2009-12-31T13:43:55Z
[ "python", "syntax", "for-loop", "generator", "yield" ]
How would you draw cell borders in a wxPython FlexGridSizer?
603,831
<p>I'm new to Python, but I can't really find much decent documentation on the web, so I'm hoping somebody will know the answer or where the answer is...</p> <p>I have a wxPython FlexGridSizer bound to a panel that contains other FlexGridSizers, I'd like to display some cell borders on the main FlexGridSizer, so each section looks encapsulated but I can't find any documentation to do it.</p> <p>I tried using a panel to add to my main FlexGridView, with the panel's border on, but the panel's border doesn't always fill up the entire FlexGridView cell, so it looks choppy and uneven.</p> <p>Does anybody know how to properly simulate this?</p>
2
2009-03-02T20:16:51Z
604,264
<p>Sizers are used just to organize widgets spatially, as a matter of a fact they are 'invisible'.</p> <p>I think you're on the right track with putting a panel inside each cell and turning on it's borders. Try adding it with wx.EXPAND flag, it has a chance to help.</p> <p>Concerning documentation: wxPython is essentially a wrapper (well, with few extras) for the wxWidgets C++ library, so virtually everything you need can be found in wxwidgets documentation. I find <a href="http://wiki.wxwidgets.org/docbrowse.html" rel="nofollow">this documentation browser</a> useful. And <a href="http://wiki.wxpython.org/C%2B%2BGuideForwxPythoneers" rel="nofollow">here</a> are some notes on interpreting C++ documentation for wxPython users, but usually everything is obvious enough.</p> <p>Also for borders you might be interested in wx.StaticBox or wx.StaticBoxSizer (that etched-line box around a group of controls, often with a label)</p>
1
2009-03-02T22:17:12Z
[ "python", "wxpython", "drawing" ]
Multicast in Python
603,852
<p>How do you send and receive UDP Multicast in Python? Is there a standard library to do so? </p>
61
2009-03-02T20:24:10Z
603,864
<p>Multicast traffic is no different than regular UDP except for the IP address. Take a look at the standard <a href="http://docs.python.org/library/socket.html" rel="nofollow">socket library</a>. You may be able to find something that builds on socket and is easier to use.</p>
2
2009-03-02T20:26:52Z
[ "python", "multicast" ]
Multicast in Python
603,852
<p>How do you send and receive UDP Multicast in Python? Is there a standard library to do so? </p>
61
2009-03-02T20:24:10Z
1,151,620
<p>Multicast sender that broadcasts to a multicast group:</p> <pre><code>#!/usr/bin/env python import socket import struct def main(): MCAST_GRP = '224.1.1.1' MCAST_PORT = 5007 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32) sock.sendto('Hello World!', (MCAST_GRP, MCAST_PORT)) if __name__ == '__main__': main() </code></pre> <p>Multicast receiver that reads from a multicast group and prints hex data to the console:</p> <pre><code>#!/usr/bin/env python import socket import binascii def main(): MCAST_GRP = '224.1.1.1' MCAST_PORT = 5007 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) try: sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) except AttributeError: pass sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 32) sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_LOOP, 1) sock.bind((MCAST_GRP, MCAST_PORT)) host = socket.gethostbyname(socket.gethostname()) sock.setsockopt(socket.SOL_IP, socket.IP_MULTICAST_IF, socket.inet_aton(host)) sock.setsockopt(socket.SOL_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(MCAST_GRP) + socket.inet_aton(host)) while 1: try: data, addr = sock.recvfrom(1024) except socket.error, e: print 'Expection' hexdata = binascii.hexlify(data) print 'Data = %s' % hexdata if __name__ == '__main__': main() </code></pre>
15
2009-07-20T03:40:37Z
[ "python", "multicast" ]
Multicast in Python
603,852
<p>How do you send and receive UDP Multicast in Python? Is there a standard library to do so? </p>
61
2009-03-02T20:24:10Z
1,794,373
<p>This works for me:</p> <p>Receive</p> <pre><code>import socket import struct MCAST_GRP = '224.1.1.1' MCAST_PORT = 5007 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(('', MCAST_PORT)) # use MCAST_GRP instead of '' to listen only # to MCAST_GRP, not all groups on MCAST_PORT mreq = struct.pack("4sl", socket.inet_aton(MCAST_GRP), socket.INADDR_ANY) sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) while True: print sock.recv(10240) </code></pre> <p>Send</p> <pre><code>import socket MCAST_GRP = '224.1.1.1' MCAST_PORT = 5007 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2) sock.sendto("robot", (MCAST_GRP, MCAST_PORT)) </code></pre> <p>It is based off the examples from <a href="http://wiki.python.org/moin/UdpCommunication">http://wiki.python.org/moin/UdpCommunication</a> which didn't work.</p> <p>My system is... Linux 2.6.31-15-generic #50-Ubuntu SMP Tue Nov 10 14:54:29 UTC 2009 i686 GNU/Linux Python 2.6.4</p>
69
2009-11-25T03:03:07Z
[ "python", "multicast" ]
Multicast in Python
603,852
<p>How do you send and receive UDP Multicast in Python? Is there a standard library to do so? </p>
61
2009-03-02T20:24:10Z
3,781,328
<p>Have a look at <a href="http://coobs.eu.org/py-multicast/" rel="nofollow">py-multicast</a>. Network module can check if an interface supports multicast (on Linux at least). </p> <pre><code>import multicast from multicast import network receiver = multicast.MulticastUDPReceiver ("eth0", "238.0.0.1", 1234 ) data = receiver.read() receiver.close() config = network.ifconfig() print config['eth0'].addresses # ['10.0.0.1'] print config['eth0'].multicast #True - eth0 supports multicast print config['eth0'].up #True - eth0 is up </code></pre> <p>Perhaps problems with not seeing IGMP, were caused by an interface not supporting multicast?</p>
2
2010-09-23T18:16:13Z
[ "python", "multicast" ]
Multicast in Python
603,852
<p>How do you send and receive UDP Multicast in Python? Is there a standard library to do so? </p>
61
2009-03-02T20:24:10Z
7,675,304
<p>better use:</p> <pre><code>sock.bind((MCAST_GRP, MCAST_PORT)) </code></pre> <p>instead of:</p> <pre><code>sock.bind(('', MCAST_PORT)) </code></pre> <p>... because if you want to listen to multiple mcast groups on the same port, you'll get all messages on all listeners</p>
8
2011-10-06T13:55:47Z
[ "python", "multicast" ]
Multicast in Python
603,852
<p>How do you send and receive UDP Multicast in Python? Is there a standard library to do so? </p>
61
2009-03-02T20:24:10Z
18,129,642
<p>tolomea's answer worked for me. I hacked it into <a href="http://docs.python.org/3.2/library/socketserver.html#socketserver-udpserver-example" rel="nofollow">socketserver.UDPServer</a> too:</p> <pre><code>class ThreadedMulticastServer(socketserver.ThreadingMixIn, socketserver.UDPServer): def __init__(self, *args): super().__init__(*args) self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind((MCAST_GRP, MCAST_PORT)) mreq = struct.pack('4sl', socket.inet_aton(MCAST_GRP), socket.INADDR_ANY) self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq) </code></pre>
0
2013-08-08T15:10:04Z
[ "python", "multicast" ]
Multicast in Python
603,852
<p>How do you send and receive UDP Multicast in Python? Is there a standard library to do so? </p>
61
2009-03-02T20:24:10Z
18,298,209
<p>There is a framework to do this from <a href="http://twistedmatrix.com/trac/" rel="nofollow">http://twistedmatrix.com/trac/</a>. Here is the example <a href="https://twistedmatrix.com/documents/12.2.0/core/howto/udp.html" rel="nofollow">https://twistedmatrix.com/documents/12.2.0/core/howto/udp.html</a></p>
1
2013-08-18T10:39:05Z
[ "python", "multicast" ]
Multicast in Python
603,852
<p>How do you send and receive UDP Multicast in Python? Is there a standard library to do so? </p>
61
2009-03-02T20:24:10Z
21,332,405
<p>To make the client code (from tolomea) work on Solaris you need to pass the ttl value for the <code>IP_MULTICAST_TTL</code> socket option as an unsigned char. Otherwise you will get an error. This worked for me on Solaris 10 and 11: </p> <pre><code>import socket import struct MCAST_GRP = '224.1.1.1' MCAST_PORT = 5007 ttl = struct.pack('B', 2) sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl) sock.sendto("robot", (MCAST_GRP, MCAST_PORT)) </code></pre>
0
2014-01-24T12:12:32Z
[ "python", "multicast" ]
Multicast in Python
603,852
<p>How do you send and receive UDP Multicast in Python? Is there a standard library to do so? </p>
61
2009-03-02T20:24:10Z
29,688,659
<p>A good example which works for me:</p> <p><a href="http://svn.python.org/projects/stackless/trunk/Demo/sockets/mcast.py" rel="nofollow">http://svn.python.org/projects/stackless/trunk/Demo/sockets/mcast.py</a></p>
0
2015-04-17T01:26:04Z
[ "python", "multicast" ]
How do you get default headers in a urllib2 Request?
603,856
<p>I have a Python web client that uses urllib2. It is easy enough to add HTTP headers to my outgoing requests. I just create a dictionary of the headers I want to add, and pass it to the Request initializer.</p> <p>However, other "standard" HTTP headers get added to the request as well as the custom ones I explicitly add. When I sniff the request using Wireshark, I see headers besides the ones I add myself. My question is how do a I get access to these headers? I want to log every request (including the <em>full</em> set of HTTP headers), and can't figure out how.</p> <p>any pointers?</p> <p>in a nutshell: How do I get all the outgoing headers from an HTTP request created by urllib2?</p>
13
2009-03-02T20:24:41Z
603,916
<p>see urllib2.py:do_request (line 1044 (1067)) and urllib2.py:do_open (line 1073) (line 293) self.addheaders = [('User-agent', client_version)] (only 'User-agent' added)</p>
0
2009-03-02T20:46:02Z
[ "python", "urllib2" ]
How do you get default headers in a urllib2 Request?
603,856
<p>I have a Python web client that uses urllib2. It is easy enough to add HTTP headers to my outgoing requests. I just create a dictionary of the headers I want to add, and pass it to the Request initializer.</p> <p>However, other "standard" HTTP headers get added to the request as well as the custom ones I explicitly add. When I sniff the request using Wireshark, I see headers besides the ones I add myself. My question is how do a I get access to these headers? I want to log every request (including the <em>full</em> set of HTTP headers), and can't figure out how.</p> <p>any pointers?</p> <p>in a nutshell: How do I get all the outgoing headers from an HTTP request created by urllib2?</p>
13
2009-03-02T20:24:41Z
603,925
<p>It should send the default http headers (as specified by <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html" rel="nofollow">w3.org</a>) alongside the ones you specify. You can use a tool like <a href="http://www.wireshark.org/" rel="nofollow">WireShark</a> if you would like to see them in their entirety.</p> <p><strong>Edit:</strong></p> <p>If you would like to log them, you can use <a href="http://www.winpcap.org/" rel="nofollow">WinPcap</a> to capture packets sent by specific applications (in your case, python). You can also specify the type of packets and many other details.</p> <p>-John</p>
-1
2009-03-02T20:48:15Z
[ "python", "urllib2" ]
How do you get default headers in a urllib2 Request?
603,856
<p>I have a Python web client that uses urllib2. It is easy enough to add HTTP headers to my outgoing requests. I just create a dictionary of the headers I want to add, and pass it to the Request initializer.</p> <p>However, other "standard" HTTP headers get added to the request as well as the custom ones I explicitly add. When I sniff the request using Wireshark, I see headers besides the ones I add myself. My question is how do a I get access to these headers? I want to log every request (including the <em>full</em> set of HTTP headers), and can't figure out how.</p> <p>any pointers?</p> <p>in a nutshell: How do I get all the outgoing headers from an HTTP request created by urllib2?</p>
13
2009-03-02T20:24:41Z
603,966
<p>The urllib2 library uses OpenerDirector objects to handle the actual opening. Fortunately, the python library provides defaults so you don't have to. It is, however, these OpenerDirector objects that are adding the extra headers.</p> <p>To see what they are after the request has been sent (so that you can log it, for example):</p> <pre><code>req = urllib2.Request(url='http://google.com') response = urllib2.urlopen(req) print req.unredirected_hdrs (produces {'Host': 'google.com', 'User-agent': 'Python-urllib/2.5'} etc) </code></pre> <p>The unredirected_hdrs is where the OpenerDirectors dump their extra headers. Simply looking at <code>req.headers</code> will show only your own headers - the library leaves those unmolested for you.</p> <p>If you need to see the headers before you send the request, you'll need to subclass the OpenerDirector in order to intercept the transmission.</p> <p>Hope that helps.</p> <p>EDIT: I forgot to mention that, once the request as been sent, <code>req.header_items()</code> will give you a list of tuples of ALL the headers, with both your own and the ones added by the OpenerDirector. I should have mentioned this first since it's the most straightforward :-) Sorry.</p> <p>EDIT 2: After your question about an example for defining your own handler, here's the sample I came up with. The concern in any monkeying with the request chain is that we need to be sure that the handler is safe for multiple requests, which is why I'm uncomfortable just replacing the definition of putheader on the HTTPConnection class directly.</p> <p>Sadly, because the internals of HTTPConnection and the AbstractHTTPHandler are very internal, we have to reproduce much of the code from the python library to inject our custom behaviour. Assuming I've not goofed below and this works as well as it did in my 5 minutes of testing, please be careful to revisit this override if you update your Python version to a revision number (ie: 2.5.x to 2.5.y or 2.5 to 2.6, etc).</p> <p>I should therefore mention that I am on Python 2.5.1. If you have 2.6 or, particularly, 3.0, you may need to adjust this accordingly.</p> <p>Please let me know if this doesn't work. I'm having waaaayyyy too much fun with this question:</p> <pre><code>import urllib2 import httplib import socket class CustomHTTPConnection(httplib.HTTPConnection): def __init__(self, *args, **kwargs): httplib.HTTPConnection.__init__(self, *args, **kwargs) self.stored_headers = [] def putheader(self, header, value): self.stored_headers.append((header, value)) httplib.HTTPConnection.putheader(self, header, value) class HTTPCaptureHeaderHandler(urllib2.AbstractHTTPHandler): def http_open(self, req): return self.do_open(CustomHTTPConnection, req) http_request = urllib2.AbstractHTTPHandler.do_request_ def do_open(self, http_class, req): # All code here lifted directly from the python library host = req.get_host() if not host: raise URLError('no host given') h = http_class(host) # will parse host:port h.set_debuglevel(self._debuglevel) headers = dict(req.headers) headers.update(req.unredirected_hdrs) headers["Connection"] = "close" headers = dict( (name.title(), val) for name, val in headers.items()) try: h.request(req.get_method(), req.get_selector(), req.data, headers) r = h.getresponse() except socket.error, err: # XXX what error? raise urllib2.URLError(err) r.recv = r.read fp = socket._fileobject(r, close=True) resp = urllib2.addinfourl(fp, r.msg, req.get_full_url()) resp.code = r.status resp.msg = r.reason # This is the line we're adding req.all_sent_headers = h.stored_headers return resp my_handler = HTTPCaptureHeaderHandler() opener = urllib2.OpenerDirector() opener.add_handler(my_handler) req = urllib2.Request(url='http://www.google.com') resp = opener.open(req) print req.all_sent_headers shows: [('Accept-Encoding', 'identity'), ('Host', 'www.google.com'), ('Connection', 'close'), ('User-Agent', 'Python-urllib/2.5')] </code></pre>
5
2009-03-02T20:57:21Z
[ "python", "urllib2" ]
How do you get default headers in a urllib2 Request?
603,856
<p>I have a Python web client that uses urllib2. It is easy enough to add HTTP headers to my outgoing requests. I just create a dictionary of the headers I want to add, and pass it to the Request initializer.</p> <p>However, other "standard" HTTP headers get added to the request as well as the custom ones I explicitly add. When I sniff the request using Wireshark, I see headers besides the ones I add myself. My question is how do a I get access to these headers? I want to log every request (including the <em>full</em> set of HTTP headers), and can't figure out how.</p> <p>any pointers?</p> <p>in a nutshell: How do I get all the outgoing headers from an HTTP request created by urllib2?</p>
13
2009-03-02T20:24:41Z
603,972
<p>How about something like this:</p> <pre><code>import urllib2 import httplib old_putheader = httplib.HTTPConnection.putheader def putheader(self, header, value): print header, value old_putheader(self, header, value) httplib.HTTPConnection.putheader = putheader urllib2.urlopen('http://www.google.com') </code></pre>
2
2009-03-02T20:58:53Z
[ "python", "urllib2" ]
How do you get default headers in a urllib2 Request?
603,856
<p>I have a Python web client that uses urllib2. It is easy enough to add HTTP headers to my outgoing requests. I just create a dictionary of the headers I want to add, and pass it to the Request initializer.</p> <p>However, other "standard" HTTP headers get added to the request as well as the custom ones I explicitly add. When I sniff the request using Wireshark, I see headers besides the ones I add myself. My question is how do a I get access to these headers? I want to log every request (including the <em>full</em> set of HTTP headers), and can't figure out how.</p> <p>any pointers?</p> <p>in a nutshell: How do I get all the outgoing headers from an HTTP request created by urllib2?</p>
13
2009-03-02T20:24:41Z
4,034,430
<p>If you want to see the literal HTTP request that is sent out, and therefore see every last header exactly as it is represented on the wire, then you can tell <code>urllib2</code> to use your own version of an <code>HTTPHandler</code> that prints out (or saves, or whatever) the outgoing HTTP request.</p> <pre><code>import httplib, urllib2 class MyHTTPConnection(httplib.HTTPConnection): def send(self, s): print s # or save them, or whatever! httplib.HTTPConnection.send(self, s) class MyHTTPHandler(urllib2.HTTPHandler): def http_open(self, req): return self.do_open(MyHTTPConnection, req) opener = urllib2.build_opener(MyHTTPHandler) response = opener.open('http://www.google.com/') </code></pre> <p>The result of running this code is:</p> <pre><code>GET / HTTP/1.1 Accept-Encoding: identity Host: www.google.com Connection: close User-Agent: Python-urllib/2.6 </code></pre>
10
2010-10-27T14:36:54Z
[ "python", "urllib2" ]
How do you get default headers in a urllib2 Request?
603,856
<p>I have a Python web client that uses urllib2. It is easy enough to add HTTP headers to my outgoing requests. I just create a dictionary of the headers I want to add, and pass it to the Request initializer.</p> <p>However, other "standard" HTTP headers get added to the request as well as the custom ones I explicitly add. When I sniff the request using Wireshark, I see headers besides the ones I add myself. My question is how do a I get access to these headers? I want to log every request (including the <em>full</em> set of HTTP headers), and can't figure out how.</p> <p>any pointers?</p> <p>in a nutshell: How do I get all the outgoing headers from an HTTP request created by urllib2?</p>
13
2009-03-02T20:24:41Z
4,034,535
<p>It sounds to me like you're looking for the headers of the response object, which include <code>Connection: close</code>, etc. These headers live in the object returned by urlopen. Getting at them is easy enough: </p> <pre><code>from urllib2 import urlopen req = urlopen("http://www.google.com") print req.headers.headers </code></pre> <p><code>req.headers</code> is a instance of <a href="http://docs.python.org/library/httplib.html?highlight=httplib.httpmessage#httplib.HTTPMessage" rel="nofollow">httplib.HTTPMessage</a></p>
0
2010-10-27T14:49:24Z
[ "python", "urllib2" ]
How do you get default headers in a urllib2 Request?
603,856
<p>I have a Python web client that uses urllib2. It is easy enough to add HTTP headers to my outgoing requests. I just create a dictionary of the headers I want to add, and pass it to the Request initializer.</p> <p>However, other "standard" HTTP headers get added to the request as well as the custom ones I explicitly add. When I sniff the request using Wireshark, I see headers besides the ones I add myself. My question is how do a I get access to these headers? I want to log every request (including the <em>full</em> set of HTTP headers), and can't figure out how.</p> <p>any pointers?</p> <p>in a nutshell: How do I get all the outgoing headers from an HTTP request created by urllib2?</p>
13
2009-03-02T20:24:41Z
6,994,543
<p>A low-level solution:</p> <pre class="lang-py prettyprint-override"><code>import httplib class HTTPConnection2(httplib.HTTPConnection): def __init__(self, *args, **kwargs): httplib.HTTPConnection.__init__(self, *args, **kwargs) self._request_headers = [] self._request_header = None def putheader(self, header, value): self._request_headers.append((header, value)) httplib.HTTPConnection.putheader(self, header, value) def send(self, s): self._request_header = s httplib.HTTPConnection.send(self, s) def getresponse(self, *args, **kwargs): response = httplib.HTTPConnection.getresponse(self, *args, **kwargs) response.request_headers = self._request_headers response.request_header = self._request_header return response </code></pre> <p>Example:</p> <pre><code>conn = HTTPConnection2("www.python.org") conn.request("GET", "/index.html", headers={ "User-agent": "test", "Referer": "/", }) response = conn.getresponse() </code></pre> <p>response.status, response.reason:</p> <pre><code>1: 200 OK </code></pre> <p>response.request_headers:</p> <pre><code>[('Host', 'www.python.org'), ('Accept-Encoding', 'identity'), ('Referer', '/'), ('User-agent', 'test')] </code></pre> <p>response.request_header:</p> <pre><code>GET /index.html HTTP/1.1 Host: www.python.org Accept-Encoding: identity Referer: / User-agent: test </code></pre>
2
2011-08-09T10:09:50Z
[ "python", "urllib2" ]
How do you get default headers in a urllib2 Request?
603,856
<p>I have a Python web client that uses urllib2. It is easy enough to add HTTP headers to my outgoing requests. I just create a dictionary of the headers I want to add, and pass it to the Request initializer.</p> <p>However, other "standard" HTTP headers get added to the request as well as the custom ones I explicitly add. When I sniff the request using Wireshark, I see headers besides the ones I add myself. My question is how do a I get access to these headers? I want to log every request (including the <em>full</em> set of HTTP headers), and can't figure out how.</p> <p>any pointers?</p> <p>in a nutshell: How do I get all the outgoing headers from an HTTP request created by urllib2?</p>
13
2009-03-02T20:24:41Z
6,996,766
<p>A other solution, witch used the idea from <a href="http://stackoverflow.com/questions/603856/how-do-you-get-default-headers-in-a-urllib2-request/603966#603966">How do you get default headers in a urllib2 Request?</a> But doesn't copy code from std-lib:</p> <pre><code>class HTTPConnection2(httplib.HTTPConnection): """ Like httplib.HTTPConnection but stores the request headers. Used in HTTPConnection3(), see below. """ def __init__(self, *args, **kwargs): httplib.HTTPConnection.__init__(self, *args, **kwargs) self.request_headers = [] self.request_header = "" def putheader(self, header, value): self.request_headers.append((header, value)) httplib.HTTPConnection.putheader(self, header, value) def send(self, s): self.request_header = s httplib.HTTPConnection.send(self, s) class HTTPConnection3(object): """ Wrapper around HTTPConnection2 Used in HTTPHandler2(), see below. """ def __call__(self, *args, **kwargs): """ instance made in urllib2.HTTPHandler.do_open() """ self._conn = HTTPConnection2(*args, **kwargs) self.request_headers = self._conn.request_headers self.request_header = self._conn.request_header return self def __getattribute__(self, name): """ Redirect attribute access to the local HTTPConnection() instance. """ if name == "_conn": return object.__getattribute__(self, name) else: return getattr(self._conn, name) class HTTPHandler2(urllib2.HTTPHandler): """ A HTTPHandler which stores the request headers. Used HTTPConnection3, see above. &gt;&gt;&gt; opener = urllib2.build_opener(HTTPHandler2) &gt;&gt;&gt; opener.addheaders = [("User-agent", "Python test")] &gt;&gt;&gt; response = opener.open('http://www.python.org/') Get the request headers as a list build with HTTPConnection.putheader(): &gt;&gt;&gt; response.request_headers [('Accept-Encoding', 'identity'), ('Host', 'www.python.org'), ('Connection', 'close'), ('User-Agent', 'Python test')] &gt;&gt;&gt; response.request_header 'GET / HTTP/1.1\\r\\nAccept-Encoding: identity\\r\\nHost: www.python.org\\r\\nConnection: close\\r\\nUser-Agent: Python test\\r\\n\\r\\n' """ def http_open(self, req): conn_instance = HTTPConnection3() response = self.do_open(conn_instance, req) response.request_headers = conn_instance.request_headers response.request_header = conn_instance.request_header return response </code></pre> <p>EDIT: Update the source</p>
2
2011-08-09T13:16:27Z
[ "python", "urllib2" ]
Django set default form values
604,266
<p>I have a Model as follows</p> <pre><code>class TankJournal(models.Model): user = models.ForeignKey(User) tank = models.ForeignKey(TankProfile) ts = models.IntegerField(max_length=15) title = models.CharField(max_length=50) body = models.TextField() </code></pre> <p>I have a modelform as follows for that model</p> <pre><code>class JournalForm(ModelForm): tank = forms.IntegerField(widget=forms.HiddenInput()) class Meta: model = TankJournal exclude = ('user','ts') </code></pre> <p>I want to know how to set the default value for that tank hidden field.. Here is my function to show/save the form so far</p> <pre><code>def addJournal(request, id=0): if not request.user.is_authenticated(): return HttpResponseRedirect('/') # # checking if they own the tank # from django.contrib.auth.models import User user = User.objects.get(pk=request.session['id']) if request.method == 'POST': form = JournalForm(request.POST) if form.is_valid(): obj = form.save(commit=False) # # setting the user and ts # from time import time obj.ts = int(time()) obj.user = user obj.tank = TankProfile.objects.get(pk=form.cleaned_data['tank_id']) # # saving the test # obj.save() else: form = JournalForm() try: tank = TankProfile.objects.get(user=user, id=id) except TankProfile.DoesNotExist: return HttpResponseRedirect('/error/') form.tank = id return render_to_response('ajax/tank_addJournal.html', {'form': form}, context_instance=RequestContext(request)) </code></pre> <p>thanks!</p>
136
2009-03-02T22:18:18Z
604,325
<p>You can use <em>initial</em> which is explained <a href="http://www.djangobook.com/en/1.0/chapter07/">here</a></p> <p>You have two options either populate the value when calling form constructor:</p> <pre><code>form = JournalForm(initial={'tank': 123}) </code></pre> <p>or set the value in the form definition:</p> <pre><code>tank = forms.IntegerField(widget=forms.HiddenInput(), initial=123) </code></pre>
245
2009-03-02T22:29:46Z
[ "python", "django", "forms", "model" ]
Django set default form values
604,266
<p>I have a Model as follows</p> <pre><code>class TankJournal(models.Model): user = models.ForeignKey(User) tank = models.ForeignKey(TankProfile) ts = models.IntegerField(max_length=15) title = models.CharField(max_length=50) body = models.TextField() </code></pre> <p>I have a modelform as follows for that model</p> <pre><code>class JournalForm(ModelForm): tank = forms.IntegerField(widget=forms.HiddenInput()) class Meta: model = TankJournal exclude = ('user','ts') </code></pre> <p>I want to know how to set the default value for that tank hidden field.. Here is my function to show/save the form so far</p> <pre><code>def addJournal(request, id=0): if not request.user.is_authenticated(): return HttpResponseRedirect('/') # # checking if they own the tank # from django.contrib.auth.models import User user = User.objects.get(pk=request.session['id']) if request.method == 'POST': form = JournalForm(request.POST) if form.is_valid(): obj = form.save(commit=False) # # setting the user and ts # from time import time obj.ts = int(time()) obj.user = user obj.tank = TankProfile.objects.get(pk=form.cleaned_data['tank_id']) # # saving the test # obj.save() else: form = JournalForm() try: tank = TankProfile.objects.get(user=user, id=id) except TankProfile.DoesNotExist: return HttpResponseRedirect('/error/') form.tank = id return render_to_response('ajax/tank_addJournal.html', {'form': form}, context_instance=RequestContext(request)) </code></pre> <p>thanks!</p>
136
2009-03-02T22:18:18Z
28,484,879
<p>If you are creating modelform from POST values initial can be assigned this way:</p> <pre><code>form = SomeModelForm(request.POST or None, initial={"option": "10"}) </code></pre> <p><a href="https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#providing-initial-values" rel="nofollow">https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#providing-initial-values</a></p>
6
2015-02-12T18:18:27Z
[ "python", "django", "forms", "model" ]
Analyze audio using Fast Fourier Transform
604,453
<p>I am trying to create a graphical spectrum analyzer in python.</p> <p>I am currently reading 1024 bytes of a 16 bit dual channel 44,100 Hz sample rate audio stream and averaging the amplitude of the 2 channels together. So now I have an array of 256 signed shorts. I now want to preform a fft on that array, using a module like numpy, and use the result to create the graphical spectrum analyzer, which, to start will just be 32 bars.</p> <p>I have read the wikipedia articles on Fast Fourier Transform and Discrete Fourier Transform but I am still unclear of what the resulting array represents. This is what the array looks like after I preform an fft on my array using numpy:</p> <pre><code> [ -3.37260500e+05 +0.00000000e+00j 7.11787022e+05 +1.70667403e+04j 4.10040193e+05 +3.28653370e+05j 9.90933073e+04 +1.60555003e+05j 2.28787050e+05 +3.24141951e+05j 2.09781047e+04 +2.31063376e+05j -2.15941453e+05 +1.63773851e+05j -7.07833051e+04 +1.52467334e+05j -1.37440802e+05 +6.28107674e+04j -7.07536614e+03 +5.55634993e+03j -4.31009964e+04 -1.74891657e+05j 1.39384348e+05 +1.95956947e+04j 1.73613033e+05 +1.16883207e+05j 1.15610357e+05 -2.62619884e+04j -2.05469722e+05 +1.71343186e+05j -1.56779748e+04 +1.51258101e+05j -2.08639913e+05 +6.07372799e+04j -2.90623668e+05 -2.79550838e+05j -1.68112214e+05 +4.47877871e+04j -1.21289916e+03 +1.18397979e+05j -1.55779104e+05 +5.06852464e+04j 1.95309737e+05 +1.93876325e+04j -2.80400414e+05 +6.90079265e+04j 1.25892113e+04 -1.39293422e+05j 3.10709174e+04 -1.35248953e+05j 1.31003438e+05 +1.90799303e+05j... </code></pre> <p>I am wondering what exactly these numbers represent and how I would convert these numbers into a percentage of a height for each of the 32 bars. Also, should I be averaging the 2 channels together?</p>
83
2009-03-02T23:13:17Z
604,498
<p>what you have is a sample whose length in time is 256/44100 = 0.00580499 seconds. This means that your frequency resolution is 1 / 0.00580499 = 172 Hz. The 256 values you get out from Python correspond to the frequencies, basically, from 86 Hz to 255*172+86 Hz = 43946 Hz. The numbers you get out are complex numbers (hence the "j" at the end of every second number).</p> <p>EDITED: FIXED WRONG INFORMATION</p> <p>You need to convert the complex numbers into amplitude by calculating the sqrt(i**2 + j**2) where i and j are the real and imaginary parts, resp.</p> <p>If you want to have 32 bars, you should as far as I understand take the average of four successive amplitudes, getting 256 / 4 = 32 bars as you want.</p>
10
2009-03-02T23:29:37Z
[ "python", "audio", "signal-processing", "fft", "spectrum" ]
Analyze audio using Fast Fourier Transform
604,453
<p>I am trying to create a graphical spectrum analyzer in python.</p> <p>I am currently reading 1024 bytes of a 16 bit dual channel 44,100 Hz sample rate audio stream and averaging the amplitude of the 2 channels together. So now I have an array of 256 signed shorts. I now want to preform a fft on that array, using a module like numpy, and use the result to create the graphical spectrum analyzer, which, to start will just be 32 bars.</p> <p>I have read the wikipedia articles on Fast Fourier Transform and Discrete Fourier Transform but I am still unclear of what the resulting array represents. This is what the array looks like after I preform an fft on my array using numpy:</p> <pre><code> [ -3.37260500e+05 +0.00000000e+00j 7.11787022e+05 +1.70667403e+04j 4.10040193e+05 +3.28653370e+05j 9.90933073e+04 +1.60555003e+05j 2.28787050e+05 +3.24141951e+05j 2.09781047e+04 +2.31063376e+05j -2.15941453e+05 +1.63773851e+05j -7.07833051e+04 +1.52467334e+05j -1.37440802e+05 +6.28107674e+04j -7.07536614e+03 +5.55634993e+03j -4.31009964e+04 -1.74891657e+05j 1.39384348e+05 +1.95956947e+04j 1.73613033e+05 +1.16883207e+05j 1.15610357e+05 -2.62619884e+04j -2.05469722e+05 +1.71343186e+05j -1.56779748e+04 +1.51258101e+05j -2.08639913e+05 +6.07372799e+04j -2.90623668e+05 -2.79550838e+05j -1.68112214e+05 +4.47877871e+04j -1.21289916e+03 +1.18397979e+05j -1.55779104e+05 +5.06852464e+04j 1.95309737e+05 +1.93876325e+04j -2.80400414e+05 +6.90079265e+04j 1.25892113e+04 -1.39293422e+05j 3.10709174e+04 -1.35248953e+05j 1.31003438e+05 +1.90799303e+05j... </code></pre> <p>I am wondering what exactly these numbers represent and how I would convert these numbers into a percentage of a height for each of the 32 bars. Also, should I be averaging the 2 channels together?</p>
83
2009-03-02T23:13:17Z
604,756
<p>The array you are showing is the Fourier Transform coefficients of the audio signal. These coefficients can be used to get the frequency content of the audio. The FFT is defined for complex valued input functions, so the coefficients you get out will be imaginary numbers even though your input is all real values. In order to get the amount of power in each frequency, you need to calculate the magnitude of the FFT coefficient for each frequency. This is <strong>not</strong> just the real component of the coefficient, you need to calculate the square root of the sum of the square of its real and imaginary components. That is, if your coefficient is a + b*j, then its magnitude is sqrt(a^2 + b^2).</p> <p>Once you have calculated the magnitude of each FFT coefficient, you need to figure out which audio frequency each FFT coefficient belongs to. An N point FFT will give you the frequency content of your signal at N equally spaced frequencies, starting at 0. Because your sampling frequency is 44100 samples / sec. and the number of points in your FFT is 256, your frequency spacing is 44100 / 256 = 172 Hz (approximately)</p> <p>The first coefficient in your array will be the 0 frequency coefficient. That is basically the average power level for all frequencies. The rest of your coefficients will count up from 0 in multiples of 172 Hz until you get to 128. In an FFT, you only can measure frequencies up to half your sample points. Read these links on the <a href="http://mathworld.wolfram.com/NyquistFrequency.html">Nyquist Frequency</a> and <a href="http://en.wikipedia.org/wiki/Nyquist%E2%80%93Shannon%5Fsampling%5Ftheorem">Nyquist-Shannon Sampling Theorem</a> if you are a glutton for punishment and need to know why, but the basic result is that your lower frequencies are going to be replicated or <a href="http://en.wikipedia.org/wiki/Aliasing">aliased</a> in the higher frequency buckets. So the frequencies will start from 0, increase by 172 Hz for each coefficient up to the N/2 coefficient, then decrease by 172 Hz until the N - 1 coefficient.</p> <p>That should be enough information to get you started. If you would like a much more approachable introduction to FFTs than is given on Wikipedia, you could try <a href="http://rads.stackoverflow.com/amzn/click/0131089897">Understanding Digital Signal Processing: 2nd Ed.</a>. It was very helpful for me.</p> <p>So that is what those numbers represent. Converting to a percentage of height could be done by scaling each frequency component magnitude by the sum of all component magnitudes. Although, that would only give you a representation of the relative frequency distribution, and not the actual power for each frequency. You could try scaling by the maximum magnitude possible for a frequency component, but I'm not sure that that would display very well. The quickest way to find a workable scaling factor would be to experiment on loud and soft audio signals to find the right setting.</p> <p>Finally, you should be averaging the two channels together if you want to show the frequency content of the entire audio signal as a whole. You are mixing the stereo audio into mono audio and showing the combined frequencies. If you want two separate displays for right and left frequencies, than you need to perform the Fourier analysis on each channel separately.</p>
160
2009-03-03T01:19:43Z
[ "python", "audio", "signal-processing", "fft", "spectrum" ]
Analyze audio using Fast Fourier Transform
604,453
<p>I am trying to create a graphical spectrum analyzer in python.</p> <p>I am currently reading 1024 bytes of a 16 bit dual channel 44,100 Hz sample rate audio stream and averaging the amplitude of the 2 channels together. So now I have an array of 256 signed shorts. I now want to preform a fft on that array, using a module like numpy, and use the result to create the graphical spectrum analyzer, which, to start will just be 32 bars.</p> <p>I have read the wikipedia articles on Fast Fourier Transform and Discrete Fourier Transform but I am still unclear of what the resulting array represents. This is what the array looks like after I preform an fft on my array using numpy:</p> <pre><code> [ -3.37260500e+05 +0.00000000e+00j 7.11787022e+05 +1.70667403e+04j 4.10040193e+05 +3.28653370e+05j 9.90933073e+04 +1.60555003e+05j 2.28787050e+05 +3.24141951e+05j 2.09781047e+04 +2.31063376e+05j -2.15941453e+05 +1.63773851e+05j -7.07833051e+04 +1.52467334e+05j -1.37440802e+05 +6.28107674e+04j -7.07536614e+03 +5.55634993e+03j -4.31009964e+04 -1.74891657e+05j 1.39384348e+05 +1.95956947e+04j 1.73613033e+05 +1.16883207e+05j 1.15610357e+05 -2.62619884e+04j -2.05469722e+05 +1.71343186e+05j -1.56779748e+04 +1.51258101e+05j -2.08639913e+05 +6.07372799e+04j -2.90623668e+05 -2.79550838e+05j -1.68112214e+05 +4.47877871e+04j -1.21289916e+03 +1.18397979e+05j -1.55779104e+05 +5.06852464e+04j 1.95309737e+05 +1.93876325e+04j -2.80400414e+05 +6.90079265e+04j 1.25892113e+04 -1.39293422e+05j 3.10709174e+04 -1.35248953e+05j 1.31003438e+05 +1.90799303e+05j... </code></pre> <p>I am wondering what exactly these numbers represent and how I would convert these numbers into a percentage of a height for each of the 32 bars. Also, should I be averaging the 2 channels together?</p>
83
2009-03-02T23:13:17Z
10,462,090
<p>Although this thread is years old, I found it very heplful. I just wanted to give my input to anyone who finds this and are trying to create something similar.</p> <p>As for the division into bars this should not be done as antti suggest, by dividing the data equally based on the number of bars. The most useful would be to divide the data into octave parts, each octave being double the frequency of the previous. (ie. 100hz is one octave above 50hz, which is one octave above 25hz). </p> <p>Depending on how many bars you want, you divide the whole range into 1/X octave ranges. Based on a given center frequency of A on the bar, you get the upper and lower limits of the bar from:</p> <pre><code>upper limit = A * 2 ^ ( 1 / 2X ) lower limit = A / 2 ^ ( 1 / 2X ) </code></pre> <p>To calculate the next adjoining center frequency you use a similar calculation:</p> <pre><code>next lower = A / 2 ^ ( 1 / X ) next higher = A * 2 ^ ( 1 / X ) </code></pre> <p>You then average the data that fits into these ranges to get the amplitude for each bar.</p> <p>For example: We want to divide into 1/3 octaves ranges and we start with a center frequency of 1khz.</p> <pre><code>Upper limit = 1000 * 2 ^ ( 1 / ( 2 * 3 ) ) = 1122.5 Lower limit = 1000 / 2 ^ ( 1 / ( 2 * 3 ) ) = 890.9 </code></pre> <p>Given 44100hz and 1024 samples (43hz between each data point) we should average out values 21 through 26. ( 890.9 / 43 = 20.72 ~ 21 and 1122.5 / 43 = 26.10 ~ 26 )</p> <p>(1/3 octave bars would get you around 30 bars between ~40hz and ~20khz). As you can figure out by now, as we go higher we will average a larger range of numbers. Low bars typically only include 1 or a small number of data points. While the higher bars can be the average of hundreds of points. The reason being that 86hz is an octave aboe 43hz... while 10086hz sounds almost the same as 10043hz.</p>
23
2012-05-05T13:01:10Z
[ "python", "audio", "signal-processing", "fft", "spectrum" ]
Does Python have something like Perl 5.10's "state" variables?
604,622
<p>In Perl 5.10, I can say:</p> <pre><code>sub foo () { state $x = 1; say $x++; } foo(); foo(); foo(); </code></pre> <p>...and it will print out:</p> <pre><code>1 2 3 </code></pre> <p>Does Python have something like this?</p>
8
2009-03-03T00:17:47Z
604,633
<p>Yes, though you have to declare your global variable first before it is encountered in <code>foo</code>:</p> <pre><code>x = 0 def foo(): global x x += 1 print x foo() foo() foo() </code></pre> <p>EDIT: In response to the comment, it's true that python has no static variables scoped within a function. Note that <code>x</code> in this example is only exposed as global to the rest of the module. For example, say the code above is in <code>test.py</code>. Now suppose you write the following module:</p> <pre><code>from test import foo x = 100 foo() foo() </code></pre> <p>The output will be only <code>1</code> and <code>2</code>, not <code>101</code> and <code>102</code>.</p>
2
2009-03-03T00:23:41Z
[ "python", "perl" ]
Does Python have something like Perl 5.10's "state" variables?
604,622
<p>In Perl 5.10, I can say:</p> <pre><code>sub foo () { state $x = 1; say $x++; } foo(); foo(); foo(); </code></pre> <p>...and it will print out:</p> <pre><code>1 2 3 </code></pre> <p>Does Python have something like this?</p>
8
2009-03-03T00:17:47Z
604,645
<p>A class may be a better fit here (and is usually a better fit for anything involving "state"):</p> <pre><code>class Stateful(object): def __init__(self): self.state_var = 0 def __call__(self): self.state_var = self.state_var + 1 print self.state_var foo = Stateful() foo() foo() </code></pre>
17
2009-03-03T00:27:45Z
[ "python", "perl" ]
Does Python have something like Perl 5.10's "state" variables?
604,622
<p>In Perl 5.10, I can say:</p> <pre><code>sub foo () { state $x = 1; say $x++; } foo(); foo(); foo(); </code></pre> <p>...and it will print out:</p> <pre><code>1 2 3 </code></pre> <p>Does Python have something like this?</p>
8
2009-03-03T00:17:47Z
604,651
<p>Python has generators which do something similar:</p> <p><a href="http://stackoverflow.com/questions/231767/can-somebody-explain-me-the-python-yield-statement">http://stackoverflow.com/questions/231767/can-somebody-explain-me-the-python-yield-statement</a></p>
9
2009-03-03T00:28:47Z
[ "python", "perl" ]
Does Python have something like Perl 5.10's "state" variables?
604,622
<p>In Perl 5.10, I can say:</p> <pre><code>sub foo () { state $x = 1; say $x++; } foo(); foo(); foo(); </code></pre> <p>...and it will print out:</p> <pre><code>1 2 3 </code></pre> <p>Does Python have something like this?</p>
8
2009-03-03T00:17:47Z
604,652
<p>You could also use something like</p> <pre><code>def static_num2(): k = 0 while True: k += 1 yield k static = static_num2().next for i in range(0,10) : print static() </code></pre> <p>to avoid a global var. Lifted from <a href="http://www.daniweb.com/forums/thread33025.html" rel="nofollow">this link</a> about the same question.</p>
2
2009-03-03T00:29:13Z
[ "python", "perl" ]
Does Python have something like Perl 5.10's "state" variables?
604,622
<p>In Perl 5.10, I can say:</p> <pre><code>sub foo () { state $x = 1; say $x++; } foo(); foo(); foo(); </code></pre> <p>...and it will print out:</p> <pre><code>1 2 3 </code></pre> <p>Does Python have something like this?</p>
8
2009-03-03T00:17:47Z
604,657
<p>The closest parallel is probably to attach values to the function itself.</p> <pre><code>def foo(): foo.bar = foo.bar + 1 foo.bar = 0 foo() foo() foo() print foo.bar # prints 3 </code></pre>
12
2009-03-03T00:30:11Z
[ "python", "perl" ]
Does Python have something like Perl 5.10's "state" variables?
604,622
<p>In Perl 5.10, I can say:</p> <pre><code>sub foo () { state $x = 1; say $x++; } foo(); foo(); foo(); </code></pre> <p>...and it will print out:</p> <pre><code>1 2 3 </code></pre> <p>Does Python have something like this?</p>
8
2009-03-03T00:17:47Z
604,658
<p>Not sure if this is what you're looking for, but python has generator functions that don't return a value per se, but a generator object that generates a new value everytime</p> <pre><code>def gen(): x = 10 while True: yield x x += 1 </code></pre> <p>usage:</p> <pre><code>&gt;&gt;&gt; a = gen() &gt;&gt;&gt; a.next() 10 &gt;&gt;&gt; a.next() 11 &gt;&gt;&gt; a.next() 12 &gt;&gt;&gt; a.next() 13 &gt;&gt;&gt; </code></pre> <p>look here for more explanation on <a href="http://stackoverflow.com/questions/231767/can-somebody-explain-me-the-python-yield-statement">yield</a>:<br /> <a href="http://stackoverflow.com/questions/231767/can-somebody-explain-me-the-python-yield-statement">http://stackoverflow.com/questions/231767/can-somebody-explain-me-the-python-yield-statement</a></p>
8
2009-03-03T00:30:49Z
[ "python", "perl" ]
Does Python have something like Perl 5.10's "state" variables?
604,622
<p>In Perl 5.10, I can say:</p> <pre><code>sub foo () { state $x = 1; say $x++; } foo(); foo(); foo(); </code></pre> <p>...and it will print out:</p> <pre><code>1 2 3 </code></pre> <p>Does Python have something like this?</p>
8
2009-03-03T00:17:47Z
604,685
<pre><code>&gt;&gt;&gt; def foo(): x = 1 while True: yield x x += 1 &gt;&gt;&gt; z = iter(foo()) &gt;&gt;&gt; next(z) 1 &gt;&gt;&gt; next(z) 2 &gt;&gt;&gt; next(z) 3 </code></pre>
1
2009-03-03T00:45:05Z
[ "python", "perl" ]
Does Python have something like Perl 5.10's "state" variables?
604,622
<p>In Perl 5.10, I can say:</p> <pre><code>sub foo () { state $x = 1; say $x++; } foo(); foo(); foo(); </code></pre> <p>...and it will print out:</p> <pre><code>1 2 3 </code></pre> <p>Does Python have something like this?</p>
8
2009-03-03T00:17:47Z
604,731
<p>Not that I'm recommending this, but just for fun:</p> <pre><code>def foo(var=[1]): print var[0] var[0] += 1 </code></pre> <p>This works because of the <a href="http://effbot.org/zone/default-values.htm" rel="nofollow">way mutable default arguments</a> work in Python.</p>
2
2009-03-03T01:03:56Z
[ "python", "perl" ]
Does Python have something like Perl 5.10's "state" variables?
604,622
<p>In Perl 5.10, I can say:</p> <pre><code>sub foo () { state $x = 1; say $x++; } foo(); foo(); foo(); </code></pre> <p>...and it will print out:</p> <pre><code>1 2 3 </code></pre> <p>Does Python have something like this?</p>
8
2009-03-03T00:17:47Z
604,945
<p>Here's one way to implement a closure in python:</p> <pre><code>def outer(): a = [4] def inner(): print a[0] a[0] = a[0] + 1 return inner fn = outer() fn() # =&gt; 4 fn() # =&gt; 5 fn() # =&gt; 6 </code></pre> <p>I borrowed this example verbatim from a <a href="http://mail.python.org/pipermail/python-list/2004-July/270951.html" rel="nofollow">python mailing list post</a>.</p>
5
2009-03-03T03:04:30Z
[ "python", "perl" ]
Does Python have something like Perl 5.10's "state" variables?
604,622
<p>In Perl 5.10, I can say:</p> <pre><code>sub foo () { state $x = 1; say $x++; } foo(); foo(); foo(); </code></pre> <p>...and it will print out:</p> <pre><code>1 2 3 </code></pre> <p>Does Python have something like this?</p>
8
2009-03-03T00:17:47Z
607,236
<p>The preferable way is to use <a href="http://stackoverflow.com/questions/604622/does-python-have-something-like-perl-5-10s-state-variables/604645#604645">class</a> or <a href="http://stackoverflow.com/questions/604622/does-python-have-something-like-perl-5-10s-state-variables/604658#604658">generator</a> (<code>yield</code>).</p> <p>For the sake of completeness here's a variant w/ closure in Python 3.x:</p> <pre><code>&gt;&gt;&gt; def make_foo(): ... x = 1 ... def foo(): ... nonlocal x ... print(x) ... x += 1 ... return foo ... &gt;&gt;&gt; foo = make_foo() &gt;&gt;&gt; foo() 1 &gt;&gt;&gt; foo() 2 &gt;&gt;&gt; foo() 3 </code></pre>
2
2009-03-03T17:02:09Z
[ "python", "perl" ]
Does Python have something like Perl 5.10's "state" variables?
604,622
<p>In Perl 5.10, I can say:</p> <pre><code>sub foo () { state $x = 1; say $x++; } foo(); foo(); foo(); </code></pre> <p>...and it will print out:</p> <pre><code>1 2 3 </code></pre> <p>Does Python have something like this?</p>
8
2009-03-03T00:17:47Z
675,847
<p>Here's another dirty cheap way to do it, it's a variation on Tryiptich's answer, but using decorators</p> <pre><code>def static_var( name, value ): def dec( function ): setattr( function, name, value ) return function return dec @static_var( 'counter', 0 ) def counting_function(): counting_function.counter = counting_function.counter + 1 print counting_function.counter """ &gt;&gt;&gt; counting_function() 1 &gt;&gt;&gt; counting_function() 2 &gt;&gt;&gt; counting_function() 3 &gt;&gt;&gt; counting_function() 4 &gt;&gt;&gt; counting_function() 5 &gt;&gt;&gt; """ </code></pre>
0
2009-03-24T01:19:16Z
[ "python", "perl" ]
How would you translate this from Perl to Python?
604,721
<p>I've got a Perl function which takes a timestamp and returns either the unchanged timestamp (if it's never seen it before) or otherwise, it appends some letters to make it unique:</p> <pre><code>sub uniqify($) { my $timestamp = shift; state $last_ts = -1; state $next_letter = 'A'; if ($timestamp == $last_ts) { $timestamp .= $next_letter++; } else { $last_ts = $timestamp; $next_letter = 'A'; } return $timestamp; } </code></pre> <p>So if you call it four times, with the values 1, 1, 1, and 2, it will return 1, then 1A, then 1B, then 2.</p> <p>Note: It only ever gets called with ever-increasing timestamps, so it doesn't need to recall every one it's ever seen, just the last one.</p> <p>Now I need to translate this function to Python. I've learned that I can replace the "state" variables with globals (yuck!) or perhaps attach them to the function as attributes, but neither of those is particularly elegant.</p> <p>Also, Python doesn't have something like Perl's magic autoincrement, where if you "++" a variable whose value is "A", it becomes "B" -- or if it's "Z", it becomes "AA". So that's a curveball too.</p> <p>I'm hacking together a solution, but it's really ugly and hard to read. Translating from Perl to Python is supposed to have the opposite effect, right? :) So I'm offering this as a challenge to SO users. Can you make it an elegant Python function?</p>
11
2009-03-03T00:59:21Z
604,747
<p>Well, sorry to say, but you can't just do a direct translation from Perl to Python (including bit-for-bit Perlisms) and expect the outcome to be prettier. It won't be, it will be considerably uglier.</p> <p>If you want the prettiness of Python you will need to use Python idioms instead.</p> <p>Now for the question at hand:</p> <pre><code>from string import uppercase class Uniquifier(object): def __init__(self): self.last_timestamp = None self.last_suffix = 0 def uniquify(self, timestamp): if timestamp == self.last_timestamp: timestamp = '%s%s' % (timestamp, uppercase[self.last_suffix]) self.last_suffix += 1 else: self.last_suffix = 0 self.timestamp = timestamp return timestamp uniquifier = Uniquifier() uniquifier.uniquify(a_timestamp) </code></pre> <p>Prettier? Maybe. More readable? Probably.</p> <p><strong>Edit (re comments):</strong> Yes this fails after Z, and I am altogether unhappy with this solution. So I won't fix it, but might offer something better, like using a number instead:</p> <pre><code>timestamp = '%s%s' % (timestamp, self.last_suffix) </code></pre> <p>If it were me, I would do this:</p> <pre><code>import uuid def uniquify(timestamp): return '%s-%s' % (timestamp, uuid.uuid4()) </code></pre> <p>And just be happy.</p>
5
2009-03-03T01:11:36Z
[ "python", "perl" ]
How would you translate this from Perl to Python?
604,721
<p>I've got a Perl function which takes a timestamp and returns either the unchanged timestamp (if it's never seen it before) or otherwise, it appends some letters to make it unique:</p> <pre><code>sub uniqify($) { my $timestamp = shift; state $last_ts = -1; state $next_letter = 'A'; if ($timestamp == $last_ts) { $timestamp .= $next_letter++; } else { $last_ts = $timestamp; $next_letter = 'A'; } return $timestamp; } </code></pre> <p>So if you call it four times, with the values 1, 1, 1, and 2, it will return 1, then 1A, then 1B, then 2.</p> <p>Note: It only ever gets called with ever-increasing timestamps, so it doesn't need to recall every one it's ever seen, just the last one.</p> <p>Now I need to translate this function to Python. I've learned that I can replace the "state" variables with globals (yuck!) or perhaps attach them to the function as attributes, but neither of those is particularly elegant.</p> <p>Also, Python doesn't have something like Perl's magic autoincrement, where if you "++" a variable whose value is "A", it becomes "B" -- or if it's "Z", it becomes "AA". So that's a curveball too.</p> <p>I'm hacking together a solution, but it's really ugly and hard to read. Translating from Perl to Python is supposed to have the opposite effect, right? :) So I'm offering this as a challenge to SO users. Can you make it an elegant Python function?</p>
11
2009-03-03T00:59:21Z
604,752
<p>Quite similar to Ali A, but I'll post mine anyway:</p> <pre><code>class unique_timestamp: suffixes = " ABCDEFGHIJKLMNOPQRSTUVWXYZ" def __init__(self): self.previous_timestamps = {} pass def uniquify(self, timestamp): times_seen_before = self.previous_timestamps.get(timestamp, 0) self.previous_timestamps[timestamp] = times_seen_before + 1 if times_seen_before &gt; 0: return str(timestamp) + self.suffixes[times_seen_before] else: return str(timestamp) </code></pre> <p>Usage:</p> <pre><code>&gt;&gt;&gt; u = unique_timestamp() &gt;&gt;&gt; u.uniquify(1) '1' &gt;&gt;&gt; u.uniquify(1) '1A' &gt;&gt;&gt; u.uniquify(1) '1B' &gt;&gt;&gt; u.uniquify(2) '2' </code></pre>
1
2009-03-03T01:16:44Z
[ "python", "perl" ]
How would you translate this from Perl to Python?
604,721
<p>I've got a Perl function which takes a timestamp and returns either the unchanged timestamp (if it's never seen it before) or otherwise, it appends some letters to make it unique:</p> <pre><code>sub uniqify($) { my $timestamp = shift; state $last_ts = -1; state $next_letter = 'A'; if ($timestamp == $last_ts) { $timestamp .= $next_letter++; } else { $last_ts = $timestamp; $next_letter = 'A'; } return $timestamp; } </code></pre> <p>So if you call it four times, with the values 1, 1, 1, and 2, it will return 1, then 1A, then 1B, then 2.</p> <p>Note: It only ever gets called with ever-increasing timestamps, so it doesn't need to recall every one it's ever seen, just the last one.</p> <p>Now I need to translate this function to Python. I've learned that I can replace the "state" variables with globals (yuck!) or perhaps attach them to the function as attributes, but neither of those is particularly elegant.</p> <p>Also, Python doesn't have something like Perl's magic autoincrement, where if you "++" a variable whose value is "A", it becomes "B" -- or if it's "Z", it becomes "AA". So that's a curveball too.</p> <p>I'm hacking together a solution, but it's really ugly and hard to read. Translating from Perl to Python is supposed to have the opposite effect, right? :) So I'm offering this as a challenge to SO users. Can you make it an elegant Python function?</p>
11
2009-03-03T00:59:21Z
604,766
<p>Does the suffix have to be letters like that?</p> <pre><code>from itertools import count def unique(timestamp): if timestamp in unique.ts.keys(): return timestamp + '.' + str(unique.ts[timestamp].next()) else: unique.ts[timestamp] = count() return timestamp unique.ts = {} </code></pre> <p>You can define a different count if you want the letters back.</p> <p>This isn't the same as your perl code, though.</p> <ul> <li>It keeps a dict around so if you have lots of unique timestamps then you'll use lots of memory.</li> <li>It handles out of order calls, which the original doesn't (i.e. u(1), u(2), u(1)).</li> </ul>
1
2009-03-03T01:22:41Z
[ "python", "perl" ]
How would you translate this from Perl to Python?
604,721
<p>I've got a Perl function which takes a timestamp and returns either the unchanged timestamp (if it's never seen it before) or otherwise, it appends some letters to make it unique:</p> <pre><code>sub uniqify($) { my $timestamp = shift; state $last_ts = -1; state $next_letter = 'A'; if ($timestamp == $last_ts) { $timestamp .= $next_letter++; } else { $last_ts = $timestamp; $next_letter = 'A'; } return $timestamp; } </code></pre> <p>So if you call it four times, with the values 1, 1, 1, and 2, it will return 1, then 1A, then 1B, then 2.</p> <p>Note: It only ever gets called with ever-increasing timestamps, so it doesn't need to recall every one it's ever seen, just the last one.</p> <p>Now I need to translate this function to Python. I've learned that I can replace the "state" variables with globals (yuck!) or perhaps attach them to the function as attributes, but neither of those is particularly elegant.</p> <p>Also, Python doesn't have something like Perl's magic autoincrement, where if you "++" a variable whose value is "A", it becomes "B" -- or if it's "Z", it becomes "AA". So that's a curveball too.</p> <p>I'm hacking together a solution, but it's really ugly and hard to read. Translating from Perl to Python is supposed to have the opposite effect, right? :) So I'm offering this as a challenge to SO users. Can you make it an elegant Python function?</p>
11
2009-03-03T00:59:21Z
604,777
<p>Look at <a href="http://stackoverflow.com/questions/410485/whats-the-5-character-alphanumeric-id-in-reddit-url/410504#410504">this answer for a robust method to convert a number to an alphanumeric id</a></p> <p>The code I present doesn't go from 'Z' to 'AA', instead goes to 'BA', but I suppose that doesn't matter, it still produces a unique id</p> <pre><code>from string import uppercase as up import itertools def to_base(q, alphabet): if q &lt; 0: raise ValueError( "must supply a positive integer" ) l = len(alphabet) converted = [] while q != 0: q, r = divmod(q, l) converted.insert(0, alphabet[r]) return "".join(converted) or alphabet[0] class TimestampUniqifier( object ): def __init__(self): self.last = '' self.counter = itertools.count() def __call__( self, str ): if str == self.last: suf = self.counter.next() return str + to_base( suf, up ) else: self.last = str self.counter = itertools.count() return str timestamp_uniqify = TimestampUniqifier() </code></pre> <p>usage:</p> <pre><code>timestamp_uniqify('1') '1' timestamp_uniqify('1') '1A' timestamp_uniqify('1') '1B' timestamp_uniqify('1') '1C' timestamp_uniqify('2') '2' timestamp_uniqify('3') '3' timestamp_uniqify('3') '3A' timestamp_uniqify('3') '3B' </code></pre> <p>You can call it maaaany times and it will still produce good results:</p> <pre><code>for i in range(100): print timestamp_uniqify('4') 4 4A 4B 4C 4D 4E 4F 4G 4H 4I 4J 4K 4L 4M 4N 4O 4P 4Q 4R 4S 4T 4U 4V 4W 4X 4Y 4Z 4BA 4BB 4BC 4BD 4BE 4BF 4BG 4BH 4BI 4BJ 4BK 4BL 4BM 4BN 4BO 4BP 4BQ 4BR 4BS 4BT 4BU 4BV 4BW 4BX 4BY 4BZ 4CA 4CB 4CC 4CD 4CE 4CF 4CG 4CH 4CI 4CJ 4CK 4CL 4CM 4CN 4CO 4CP 4CQ 4CR 4CS 4CT 4CU 4CV 4CW 4CX 4CY 4CZ 4DA 4DB 4DC 4DD 4DE 4DF 4DG 4DH 4DI 4DJ 4DK 4DL 4DM 4DN 4DO 4DP 4DQ 4DR 4DS 4DT 4DU </code></pre>
7
2009-03-03T01:27:41Z
[ "python", "perl" ]
How would you translate this from Perl to Python?
604,721
<p>I've got a Perl function which takes a timestamp and returns either the unchanged timestamp (if it's never seen it before) or otherwise, it appends some letters to make it unique:</p> <pre><code>sub uniqify($) { my $timestamp = shift; state $last_ts = -1; state $next_letter = 'A'; if ($timestamp == $last_ts) { $timestamp .= $next_letter++; } else { $last_ts = $timestamp; $next_letter = 'A'; } return $timestamp; } </code></pre> <p>So if you call it four times, with the values 1, 1, 1, and 2, it will return 1, then 1A, then 1B, then 2.</p> <p>Note: It only ever gets called with ever-increasing timestamps, so it doesn't need to recall every one it's ever seen, just the last one.</p> <p>Now I need to translate this function to Python. I've learned that I can replace the "state" variables with globals (yuck!) or perhaps attach them to the function as attributes, but neither of those is particularly elegant.</p> <p>Also, Python doesn't have something like Perl's magic autoincrement, where if you "++" a variable whose value is "A", it becomes "B" -- or if it's "Z", it becomes "AA". So that's a curveball too.</p> <p>I'm hacking together a solution, but it's really ugly and hard to read. Translating from Perl to Python is supposed to have the opposite effect, right? :) So I'm offering this as a challenge to SO users. Can you make it an elegant Python function?</p>
11
2009-03-03T00:59:21Z
604,950
<p>I just tested this up to 1000 against the original perl implementation and diff returns the same results for both. The suffix code is tricky -- this is not a base 36 counter. Hasen J's solution - though it produces a unique timestamp - isn't quite the same since it goes from 'Z' to 'BA', when it should instead go to 'AA' to match the perl ++ operator.</p> <pre><code>#!/usr/bin/python class uniqify: def __init__(self): self.last_timestamp = -1 self.next_suffix = 'A' return def suffix(self): s = self.next_suffix letters = [l for l in self.next_suffix] if letters[-1] == 'Z': letters.reverse() nonz = None for i in range(len(letters)): if letters[i] != 'Z': nonz = i break if nonz is not None: letters[nonz] = chr(ord(letters[nonz]) + 1) for i in range(0, nonz): letters[i] = 'A' else: letters = ['A'] * (len(letters) + 1) letters.reverse() else: letters[-1] = chr(ord(letters[-1]) + 1) self.next_suffix = ''.join(letters) return s def reset(self): self.next_suffix = 'A' return def __call__(self, timestamp): if timestamp == self.last_timestamp: timestamp_str = '%s%s' % (timestamp, self.suffix()) else: self.last_timestamp = timestamp self.reset() timestamp_str = '%s' % timestamp return timestamp_str uniqify = uniqify() if __name__ == '__main__': for n in range(1000): print uniqify(1) for n in range(1000): print uniqify(2) </code></pre>
3
2009-03-03T03:05:50Z
[ "python", "perl" ]
How would you translate this from Perl to Python?
604,721
<p>I've got a Perl function which takes a timestamp and returns either the unchanged timestamp (if it's never seen it before) or otherwise, it appends some letters to make it unique:</p> <pre><code>sub uniqify($) { my $timestamp = shift; state $last_ts = -1; state $next_letter = 'A'; if ($timestamp == $last_ts) { $timestamp .= $next_letter++; } else { $last_ts = $timestamp; $next_letter = 'A'; } return $timestamp; } </code></pre> <p>So if you call it four times, with the values 1, 1, 1, and 2, it will return 1, then 1A, then 1B, then 2.</p> <p>Note: It only ever gets called with ever-increasing timestamps, so it doesn't need to recall every one it's ever seen, just the last one.</p> <p>Now I need to translate this function to Python. I've learned that I can replace the "state" variables with globals (yuck!) or perhaps attach them to the function as attributes, but neither of those is particularly elegant.</p> <p>Also, Python doesn't have something like Perl's magic autoincrement, where if you "++" a variable whose value is "A", it becomes "B" -- or if it's "Z", it becomes "AA". So that's a curveball too.</p> <p>I'm hacking together a solution, but it's really ugly and hard to read. Translating from Perl to Python is supposed to have the opposite effect, right? :) So I'm offering this as a challenge to SO users. Can you make it an elegant Python function?</p>
11
2009-03-03T00:59:21Z
605,011
<p>The class is generic and boring, <strong>but This is my very first recursive generator.</strong> &lt;3</p> <pre><code>def stamptag(): yield '' prefixtag = stamptag() prefix = prefixtag.next() while True: for i in range(ord('A'),ord('Z')+1): yield prefix+chr(i) prefix = prefixtag.next() tagger = stamptag() for i in range(3000): tagger.next() print tagger.next() class uniquestamp: def __init__(self): self.timestamp = -1 self.tagger = stamptag() def format(self,newstamp): if self.timestamp &lt; newstamp: self.tagger = stamptag() self.timestamp = newstamp return str(newstamp)+self.tagger.next() stamper = uniquestamp() print map(stamper.format, [1,1,1,2,2,3,4,4]) </code></pre> <p>output:</p> <pre><code>DKJ ['1', '1A', '1B', '2', '2A', '3', '4', '4A'] </code></pre>
2
2009-03-03T03:36:25Z
[ "python", "perl" ]
How would you translate this from Perl to Python?
604,721
<p>I've got a Perl function which takes a timestamp and returns either the unchanged timestamp (if it's never seen it before) or otherwise, it appends some letters to make it unique:</p> <pre><code>sub uniqify($) { my $timestamp = shift; state $last_ts = -1; state $next_letter = 'A'; if ($timestamp == $last_ts) { $timestamp .= $next_letter++; } else { $last_ts = $timestamp; $next_letter = 'A'; } return $timestamp; } </code></pre> <p>So if you call it four times, with the values 1, 1, 1, and 2, it will return 1, then 1A, then 1B, then 2.</p> <p>Note: It only ever gets called with ever-increasing timestamps, so it doesn't need to recall every one it's ever seen, just the last one.</p> <p>Now I need to translate this function to Python. I've learned that I can replace the "state" variables with globals (yuck!) or perhaps attach them to the function as attributes, but neither of those is particularly elegant.</p> <p>Also, Python doesn't have something like Perl's magic autoincrement, where if you "++" a variable whose value is "A", it becomes "B" -- or if it's "Z", it becomes "AA". So that's a curveball too.</p> <p>I'm hacking together a solution, but it's really ugly and hard to read. Translating from Perl to Python is supposed to have the opposite effect, right? :) So I'm offering this as a challenge to SO users. Can you make it an elegant Python function?</p>
11
2009-03-03T00:59:21Z
613,872
<p>This is my first time answering, and I used globals, but it seemed the simplest way to me.</p> <pre><code>from string import uppercase last_ts = None letters = None def increment(letters): if not letters: return "A" last_letter = letters[-1] if last_letter == "Z": return increment(letters[:-1]) + "A" return letters[:-1] + uppercase[uppercase.index(last_letter) + 1] def uniquify(timestamp): global last_ts, letters if timestamp == last_ts: letters = increment(letters) return timestamp + letters last_ts = timestamp letters = None return timestamp print uniquify("1") print uniquify('1') print uniquify("1") print uniquify("2") for each in range(100): print uniquify("2") 1 1A 1B 2 2A 2B 2C 2D 2E 2F 2G 2H 2I 2J 2K 2L 2M 2N 2O 2P 2Q 2R 2S 2T 2U 2V 2W 2X 2Y 2Z 2AA 2AB 2AC 2AD 2AE 2AF 2AG 2AH 2AI 2AJ 2AK 2AL 2AM 2AN 2AO 2AP 2AQ 2AR 2AS 2AT 2AU 2AV 2AW 2AX 2AY 2AZ 2BA 2BB 2BC 2BD 2BE 2BF 2BG 2BH 2BI 2BJ 2BK 2BL 2BM 2BN 2BO 2BP 2BQ 2BR 2BS 2BT 2BU 2BV 2BW 2BX 2BY 2BZ 2CA 2CB 2CC 2CD 2CE 2CF 2CG 2CH 2CI 2CJ 2CK 2CL 2CM 2CN 2CO 2CP 2CQ 2CR 2CS 2CT 2CU 2CV </code></pre>
0
2009-03-05T07:23:45Z
[ "python", "perl" ]
How would you translate this from Perl to Python?
604,721
<p>I've got a Perl function which takes a timestamp and returns either the unchanged timestamp (if it's never seen it before) or otherwise, it appends some letters to make it unique:</p> <pre><code>sub uniqify($) { my $timestamp = shift; state $last_ts = -1; state $next_letter = 'A'; if ($timestamp == $last_ts) { $timestamp .= $next_letter++; } else { $last_ts = $timestamp; $next_letter = 'A'; } return $timestamp; } </code></pre> <p>So if you call it four times, with the values 1, 1, 1, and 2, it will return 1, then 1A, then 1B, then 2.</p> <p>Note: It only ever gets called with ever-increasing timestamps, so it doesn't need to recall every one it's ever seen, just the last one.</p> <p>Now I need to translate this function to Python. I've learned that I can replace the "state" variables with globals (yuck!) or perhaps attach them to the function as attributes, but neither of those is particularly elegant.</p> <p>Also, Python doesn't have something like Perl's magic autoincrement, where if you "++" a variable whose value is "A", it becomes "B" -- or if it's "Z", it becomes "AA". So that's a curveball too.</p> <p>I'm hacking together a solution, but it's really ugly and hard to read. Translating from Perl to Python is supposed to have the opposite effect, right? :) So I'm offering this as a challenge to SO users. Can you make it an elegant Python function?</p>
11
2009-03-03T00:59:21Z
628,907
<p>Looking at the problem it seems like a good fit for a coroutine (Python 2.5 or higher). Here's some code that will roughly produce the same result:</p> <pre><code>def uniqify(): seen = {} val = (yield None) while True: if val in seen: idxa, idxb = seen[val] idxb += 1 else: idxa, idxb = (len(seen)+1, ord('a')) seen[val] = (idxa, idxb) uniq = "%s%s" % (idxa, chr(idxb)) val = (yield uniq) </code></pre> <p>And here's how you use it:</p> <pre><code>&gt;&gt;&gt; u = send.uniqify() &gt;&gt;&gt; u.next() #need this to start the generator &gt;&gt;&gt; u.send(1) '1a' &gt;&gt;&gt; u.send(1) '1b' &gt;&gt;&gt; u.send(1) '1c' &gt;&gt;&gt; u.send(2) '2a' &gt;&gt;&gt; u.send(2) '2b' &gt;&gt;&gt; u.send(1) #you can go back to previous values '1d' &gt;&gt;&gt; u.send('stringy') #you can send it anything that can be used as a dict key '3a' </code></pre>
0
2009-03-10T04:08:24Z
[ "python", "perl" ]
How do I access my webcam in Python?
604,749
<p>I would like to access my webcam from Python.</p> <p>I tried using the <a href="http://videocapture.sourceforge.net/">VideoCapture</a> extension (<a href="http://technobabbler.com/?p=22">tutorial</a>), but that didn't work very well for me, I had to work around some problems such as it's a bit slow with resolutions >320x230, and sometimes it returns <code>None</code> for no apparent reason.</p> <p>Is there a better way to access my webcam from Python?</p>
37
2009-03-03T01:11:44Z
604,798
<p>The only one I've used is VideoCapture, which you've already mentioned you don't like (although I had no problems with it; what bugs did you encounter?) </p> <p>I was unable to find any alternatives in the past or now, so you might be stuck either using VideoCapture, or finding a nice C library and writing a Python wrapper for it (which might be more work than you're willing to put into it).</p>
-2
2009-03-03T01:42:08Z
[ "python", "webcam" ]
How do I access my webcam in Python?
604,749
<p>I would like to access my webcam from Python.</p> <p>I tried using the <a href="http://videocapture.sourceforge.net/">VideoCapture</a> extension (<a href="http://technobabbler.com/?p=22">tutorial</a>), but that didn't work very well for me, I had to work around some problems such as it's a bit slow with resolutions >320x230, and sometimes it returns <code>None</code> for no apparent reason.</p> <p>Is there a better way to access my webcam from Python?</p>
37
2009-03-03T01:11:44Z
604,889
<p>gstreamer can handle webcam input. If I remeber well, there are python bindings for it!</p>
1
2009-03-03T02:33:17Z
[ "python", "webcam" ]
How do I access my webcam in Python?
604,749
<p>I would like to access my webcam from Python.</p> <p>I tried using the <a href="http://videocapture.sourceforge.net/">VideoCapture</a> extension (<a href="http://technobabbler.com/?p=22">tutorial</a>), but that didn't work very well for me, I had to work around some problems such as it's a bit slow with resolutions >320x230, and sometimes it returns <code>None</code> for no apparent reason.</p> <p>Is there a better way to access my webcam from Python?</p>
37
2009-03-03T01:11:44Z
606,154
<p>OpenCV has support for getting data from a webcam, and it comes with Python wrappers by default, you also need to install <code>numpy</code> for the OpenCV Python extension (called <code>cv2</code>) to work.<br> At the time of writing (January 2015) there is no Python 3 support yet, so you need to use Python 2.</p> <p><a href="https://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_tutorials.html">More information on using OpenCV with Python</a>.</p> <p>An example copied from <a href="http://stackoverflow.com/a/11449901/660921">Displaying webcam feed using opencv and python</a>:</p> <pre><code>import cv2 cv2.namedWindow("preview") vc = cv2.VideoCapture(0) if vc.isOpened(): # try to get the first frame rval, frame = vc.read() else: rval = False while rval: cv2.imshow("preview", frame) rval, frame = vc.read() key = cv2.waitKey(20) if key == 27: # exit on ESC break cv2.destroyWindow("preview") </code></pre>
25
2009-03-03T12:09:22Z
[ "python", "webcam" ]
How do I access my webcam in Python?
604,749
<p>I would like to access my webcam from Python.</p> <p>I tried using the <a href="http://videocapture.sourceforge.net/">VideoCapture</a> extension (<a href="http://technobabbler.com/?p=22">tutorial</a>), but that didn't work very well for me, I had to work around some problems such as it's a bit slow with resolutions >320x230, and sometimes it returns <code>None</code> for no apparent reason.</p> <p>Is there a better way to access my webcam from Python?</p>
37
2009-03-03T01:11:44Z
37,325,978
<p>This should have been a comment to @John Montgomery, but my rep does not allow me to make comments. Your answer is great, but at least on Windows, it is missing the line</p> <pre><code>vc.release() </code></pre> <p>before</p> <pre><code>cv2.destroyWindow("preview") </code></pre> <p>Without it, the camera resource is locked, and can not be captured again before the python console is killed.</p>
4
2016-05-19T14:16:11Z
[ "python", "webcam" ]
python: how to send packets in multi thread and then the thread kill itself
605,013
<p>I have a question. I'd like to send a continuous streams of byte to some host for certain amount of time (let's say 1 minute) using python. </p> <p>Here is my code so far:</p> <pre><code>#! /usr/bin/env python import socket import thread import time IP = "192.168.0.2" PADDING = "a" * 1000 #assume the MTU is slighly above 1000 DATA = PADDING + "this is sentence number = " PORT = 14444 killed = False test_time = 60 #60 seconds of testing def send_data(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((IP, PORT)) count = 1 starttime = time.clock() while elapsed &lt; test_time: sent = s.send(DATA + str(count) + "\n") if sent == 0: break # assume that if nothing is sent -&gt; connection died count = count+1 elapsed = time.clock() - starttime if killed: break s.close() print str(count) + " has been sent" print "to quit type quit" thread.start_new_thread(send_data, ()) while True: var = raw_input("Enter something: ") if var == "quit": killed = True </code></pre> <p>Few question, is there a better way to let a thread die after 60 seconds other than polling the time.clock every time? When I run this program, it sends the bytes correctly but when I typed quit the other thread won't die, even though I set the var killed = True. I wonder why is that? the scope of var Killed should reach the other thread right?</p> <p>Thanks</p>
5
2009-03-03T03:37:31Z
605,032
<p>Ensure that the "quit" is working correctly and add a small print to test that the input is working.</p> <pre><code>if var == "quit": print "Hey we got quit" </code></pre>
0
2009-03-03T03:43:47Z
[ "python", "multithreading", "sockets", "timer", "packet" ]
python: how to send packets in multi thread and then the thread kill itself
605,013
<p>I have a question. I'd like to send a continuous streams of byte to some host for certain amount of time (let's say 1 minute) using python. </p> <p>Here is my code so far:</p> <pre><code>#! /usr/bin/env python import socket import thread import time IP = "192.168.0.2" PADDING = "a" * 1000 #assume the MTU is slighly above 1000 DATA = PADDING + "this is sentence number = " PORT = 14444 killed = False test_time = 60 #60 seconds of testing def send_data(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((IP, PORT)) count = 1 starttime = time.clock() while elapsed &lt; test_time: sent = s.send(DATA + str(count) + "\n") if sent == 0: break # assume that if nothing is sent -&gt; connection died count = count+1 elapsed = time.clock() - starttime if killed: break s.close() print str(count) + " has been sent" print "to quit type quit" thread.start_new_thread(send_data, ()) while True: var = raw_input("Enter something: ") if var == "quit": killed = True </code></pre> <p>Few question, is there a better way to let a thread die after 60 seconds other than polling the time.clock every time? When I run this program, it sends the bytes correctly but when I typed quit the other thread won't die, even though I set the var killed = True. I wonder why is that? the scope of var Killed should reach the other thread right?</p> <p>Thanks</p>
5
2009-03-03T03:37:31Z
605,082
<p>The variable elapsed is not initialized. Set it to zero above the while loop.</p>
0
2009-03-03T04:11:21Z
[ "python", "multithreading", "sockets", "timer", "packet" ]
python: how to send packets in multi thread and then the thread kill itself
605,013
<p>I have a question. I'd like to send a continuous streams of byte to some host for certain amount of time (let's say 1 minute) using python. </p> <p>Here is my code so far:</p> <pre><code>#! /usr/bin/env python import socket import thread import time IP = "192.168.0.2" PADDING = "a" * 1000 #assume the MTU is slighly above 1000 DATA = PADDING + "this is sentence number = " PORT = 14444 killed = False test_time = 60 #60 seconds of testing def send_data(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((IP, PORT)) count = 1 starttime = time.clock() while elapsed &lt; test_time: sent = s.send(DATA + str(count) + "\n") if sent == 0: break # assume that if nothing is sent -&gt; connection died count = count+1 elapsed = time.clock() - starttime if killed: break s.close() print str(count) + " has been sent" print "to quit type quit" thread.start_new_thread(send_data, ()) while True: var = raw_input("Enter something: ") if var == "quit": killed = True </code></pre> <p>Few question, is there a better way to let a thread die after 60 seconds other than polling the time.clock every time? When I run this program, it sends the bytes correctly but when I typed quit the other thread won't die, even though I set the var killed = True. I wonder why is that? the scope of var Killed should reach the other thread right?</p> <p>Thanks</p>
5
2009-03-03T03:37:31Z
605,248
<p>I don't know how to do this with the "thread" module, but I can do it with the "threading" module. I think this code accomplishes what you want.</p> <p>For documentation on the threading module: <a href="http://docs.python.org/library/threading.html" rel="nofollow">http://docs.python.org/library/threading.html</a></p> <pre><code>#!/usr/bin/python import time from threading import Thread import threading import sys test_time = 10 killed = False class SillyThread( threading.Thread ): def run(self): global killed starttime = time.time() counter = 0 while (time.time() - starttime) &lt; test_time: if killed: break counter = counter + 1 time.sleep(0.1) print "I did %d loops" % counter class ManageThread( threading.Thread ): def run(self): global killed while True: var = raw_input("Enter something: ") if var == "quit": killed = True break print "Got var [%s]" % var silly = SillyThread() silly.start() ManageThread().start() Thread.join(silly) print "bye bye" sys.exit(0) </code></pre> <p>Note that I use time.time() instead of time.clock(). time.clock() gives elapsed processor time on Unix (see <a href="http://docs.python.org/library/time.html" rel="nofollow">http://docs.python.org/library/time.html</a>). I think time.clock() should work everywhere. I set my test_time to 10 seconds because I don't have the patience for a minute.</p> <p>Here's what happens if I let it run the full 10 seconds:</p> <pre><code>leif@peacock:~/tmp$ ./test.py Enter something: I did 100 loops bye bye </code></pre> <p>Here's what happens if I type 'quit':</p> <pre><code>leif@peacock:~/tmp$ ./test.py Enter something: quit Got var [quit] I did 10 loops bye bye </code></pre> <p>Hope this helps.</p>
2
2009-03-03T05:48:02Z
[ "python", "multithreading", "sockets", "timer", "packet" ]
python: how to send packets in multi thread and then the thread kill itself
605,013
<p>I have a question. I'd like to send a continuous streams of byte to some host for certain amount of time (let's say 1 minute) using python. </p> <p>Here is my code so far:</p> <pre><code>#! /usr/bin/env python import socket import thread import time IP = "192.168.0.2" PADDING = "a" * 1000 #assume the MTU is slighly above 1000 DATA = PADDING + "this is sentence number = " PORT = 14444 killed = False test_time = 60 #60 seconds of testing def send_data(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((IP, PORT)) count = 1 starttime = time.clock() while elapsed &lt; test_time: sent = s.send(DATA + str(count) + "\n") if sent == 0: break # assume that if nothing is sent -&gt; connection died count = count+1 elapsed = time.clock() - starttime if killed: break s.close() print str(count) + " has been sent" print "to quit type quit" thread.start_new_thread(send_data, ()) while True: var = raw_input("Enter something: ") if var == "quit": killed = True </code></pre> <p>Few question, is there a better way to let a thread die after 60 seconds other than polling the time.clock every time? When I run this program, it sends the bytes correctly but when I typed quit the other thread won't die, even though I set the var killed = True. I wonder why is that? the scope of var Killed should reach the other thread right?</p> <p>Thanks</p>
5
2009-03-03T03:37:31Z
605,299
<p>As mentioned above, use the <a href="http://docs.python.org/library/threading.html" rel="nofollow">threading</a> module, it is much easier to use and provides several synchronization primitives. It also provides a <a href="http://docs.python.org/library/threading.html#id7" rel="nofollow">Timer</a> class that runs after a specified amount of time.</p> <p>If you just want the program to exit, you can simply make the sending thread a daemon. You do this by calling setDaemon(True) before calling start() (2.6 might use a daemon attribute instead). Python won't exit so long as a non-daemon thread is running.</p>
1
2009-03-03T06:11:08Z
[ "python", "multithreading", "sockets", "timer", "packet" ]
python: how to send packets in multi thread and then the thread kill itself
605,013
<p>I have a question. I'd like to send a continuous streams of byte to some host for certain amount of time (let's say 1 minute) using python. </p> <p>Here is my code so far:</p> <pre><code>#! /usr/bin/env python import socket import thread import time IP = "192.168.0.2" PADDING = "a" * 1000 #assume the MTU is slighly above 1000 DATA = PADDING + "this is sentence number = " PORT = 14444 killed = False test_time = 60 #60 seconds of testing def send_data(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((IP, PORT)) count = 1 starttime = time.clock() while elapsed &lt; test_time: sent = s.send(DATA + str(count) + "\n") if sent == 0: break # assume that if nothing is sent -&gt; connection died count = count+1 elapsed = time.clock() - starttime if killed: break s.close() print str(count) + " has been sent" print "to quit type quit" thread.start_new_thread(send_data, ()) while True: var = raw_input("Enter something: ") if var == "quit": killed = True </code></pre> <p>Few question, is there a better way to let a thread die after 60 seconds other than polling the time.clock every time? When I run this program, it sends the bytes correctly but when I typed quit the other thread won't die, even though I set the var killed = True. I wonder why is that? the scope of var Killed should reach the other thread right?</p> <p>Thanks</p>
5
2009-03-03T03:37:31Z
605,865
<p>I recommned using threading module. Even more benefit is to use InterruptableThread for terminating the thread. You do not have to use flag for terminating your thread but exception will occur if you call terminate() on this thread from parent. You can handle exception or not.</p> <pre><code>import threading, ctypes class InterruptableThread(threading.Thread): @classmethod def _async_raise(cls, tid, excobj): res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(excobj)) if res == 0: raise ValueError("nonexistent thread id") elif res &gt; 1: ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, 0) raise SystemError("PyThreadState_SetAsyncExc failed") def raise_exc(self, excobj): assert self.isAlive(), "thread must be started" for tid, tobj in threading._active.items(): if tobj is self: self._async_raise(tid, excobj) return def terminate(self): self.raise_exc(SystemExit) </code></pre> <p><strong>EDIT:</strong> You can rewrite your code like this using another thread that is waiting 1 minute and then killing your other thread</p> <pre><code>def send_data: IP = ... # other vars ... s = socket.socket(.....) # no killed checking # no time checking # just do your work here ... s.close() my_thread = InterruptableThread(target=send_data) my_thread.start() def one_minute_kill(who): time.sleep(60) who.terminate() killer_thread = InterruptableThread(target=one_minute_kill, args=[my_thread]) killer.start() print "to quit type quit" while my_thread.isAlive(): if raw_input("Enter something: ") == "quit": my_thread.terminate() </code></pre>
5
2009-03-03T10:20:58Z
[ "python", "multithreading", "sockets", "timer", "packet" ]
python: how to send packets in multi thread and then the thread kill itself
605,013
<p>I have a question. I'd like to send a continuous streams of byte to some host for certain amount of time (let's say 1 minute) using python. </p> <p>Here is my code so far:</p> <pre><code>#! /usr/bin/env python import socket import thread import time IP = "192.168.0.2" PADDING = "a" * 1000 #assume the MTU is slighly above 1000 DATA = PADDING + "this is sentence number = " PORT = 14444 killed = False test_time = 60 #60 seconds of testing def send_data(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((IP, PORT)) count = 1 starttime = time.clock() while elapsed &lt; test_time: sent = s.send(DATA + str(count) + "\n") if sent == 0: break # assume that if nothing is sent -&gt; connection died count = count+1 elapsed = time.clock() - starttime if killed: break s.close() print str(count) + " has been sent" print "to quit type quit" thread.start_new_thread(send_data, ()) while True: var = raw_input("Enter something: ") if var == "quit": killed = True </code></pre> <p>Few question, is there a better way to let a thread die after 60 seconds other than polling the time.clock every time? When I run this program, it sends the bytes correctly but when I typed quit the other thread won't die, even though I set the var killed = True. I wonder why is that? the scope of var Killed should reach the other thread right?</p> <p>Thanks</p>
5
2009-03-03T03:37:31Z
609,159
<p>It's easy to test the scope of <code>killed</code>:</p> <pre><code>&gt;&gt;&gt; import thread &gt;&gt;&gt; killed = False &gt;&gt;&gt; import time &gt;&gt;&gt; def test(): ... while True: ... time.sleep(1) ... if killed: ... print 'Dead.' ... break ... &gt;&gt;&gt; thread.start_new_thread(test, ()) 25479680 &gt;&gt;&gt; time.sleep(3) &gt;&gt;&gt; killed = True &gt;&gt;&gt; Dead. </code></pre>
0
2009-03-04T03:54:32Z
[ "python", "multithreading", "sockets", "timer", "packet" ]
python: how to send packets in multi thread and then the thread kill itself
605,013
<p>I have a question. I'd like to send a continuous streams of byte to some host for certain amount of time (let's say 1 minute) using python. </p> <p>Here is my code so far:</p> <pre><code>#! /usr/bin/env python import socket import thread import time IP = "192.168.0.2" PADDING = "a" * 1000 #assume the MTU is slighly above 1000 DATA = PADDING + "this is sentence number = " PORT = 14444 killed = False test_time = 60 #60 seconds of testing def send_data(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((IP, PORT)) count = 1 starttime = time.clock() while elapsed &lt; test_time: sent = s.send(DATA + str(count) + "\n") if sent == 0: break # assume that if nothing is sent -&gt; connection died count = count+1 elapsed = time.clock() - starttime if killed: break s.close() print str(count) + " has been sent" print "to quit type quit" thread.start_new_thread(send_data, ()) while True: var = raw_input("Enter something: ") if var == "quit": killed = True </code></pre> <p>Few question, is there a better way to let a thread die after 60 seconds other than polling the time.clock every time? When I run this program, it sends the bytes correctly but when I typed quit the other thread won't die, even though I set the var killed = True. I wonder why is that? the scope of var Killed should reach the other thread right?</p> <p>Thanks</p>
5
2009-03-03T03:37:31Z
1,732,979
<p>You can do this pretty easily without threads. For example, using Twisted, you just set up a timed call and a producer:</p> <pre><code>from twisted.internet.protocol import ClientFactory, Protocol from twisted.internet import reactor class Noisy(Protocol): def __init__(self, delay, data): self.delay = delay self.data = data def stop(self): self.transport.unregisterProducer() self.transport.loseConnection() reactor.stop() def resumeProducing(self): self.transport.write(self.data) def connectionMade(self): self.transport.registerProducer(self, False) reactor.callLater(self.delay, self.stop) factory = ClientFactory() factory.protocol = lambda: Noisy(60, "hello server") reactor.connectTCP(host, port, factory) reactor.run() </code></pre> <p>This has various advantages over the threaded approach. It doesn't rely on daemon threads, so you can actually clean up the network connection (eg, to send a close message if necessary) rather than relying on the platform to destroy it. It handles all the actual low level networking code for you (your original example is doing the wrong thing in the case of socket.send returning 0; this code will handle that case properly). You also don't have to rely on ctypes or the obscure CPython API for raising an exception in another thread (so it's portable to more versions of Python and can actually interrupt a blocked send immediately, unlike some of the other suggested approaches).</p>
1
2009-11-14T02:05:32Z
[ "python", "multithreading", "sockets", "timer", "packet" ]
Python variable assigned by an outside module is accessible for printing but not for assignment in the target module
605,399
<p>I have two files, one is in the webroot, and another is a bootstrap located one folder above the web root (this is CGI programming by the way).</p> <p>The index file in the web root imports the bootstrap and assigns a variable to it, then calls a a function to initialize the application. Everything up to here works as expected.</p> <p>Now, in the bootstrap file I can print the variable, but when I try to assign a value to the variable an error is thrown. If you take away the assignment statement no errors are thrown.</p> <p>I'm really curious about how the scoping works in this situation. I can print the variable, but I can't asign to it. This is on Python 3.</p> <p><strong>index.py</strong></p> <pre><code># Import modules import sys import cgitb; # Enable error reporting cgitb.enable() #cgitb.enable(display=0, logdir="/tmp") # Add the application root to the include path sys.path.append('path') # Include the bootstrap import bootstrap bootstrap.VAR = 'testVar' bootstrap.initialize() </code></pre> <p><strong>bootstrap.py</strong></p> <pre><code>def initialize(): print('Content-type: text/html\n\n') print(VAR) VAR = 'h' print(VAR) </code></pre> <p>Thanks.</p> <p>Edit: The error message</p> <pre><code>UnboundLocalError: local variable 'VAR' referenced before assignment args = ("local variable 'VAR' referenced before assignment",) with_traceback = &lt;built-in method with_traceback of UnboundLocalError object at 0x00C6ACC0&gt; </code></pre>
1
2009-03-03T07:03:28Z
605,427
<p>try this:</p> <pre> <code> def initialize(): global VAR print('Content-type: text/html\n\n') print(VAR) VAR = 'h' print(VAR) </code> </pre> <p>Without 'global VAR' python want to use local variable VAR and give you "UnboundLocalError: local variable 'VAR' referenced before assignment" </p>
3
2009-03-03T07:23:30Z
[ "python", "scoping" ]
Python variable assigned by an outside module is accessible for printing but not for assignment in the target module
605,399
<p>I have two files, one is in the webroot, and another is a bootstrap located one folder above the web root (this is CGI programming by the way).</p> <p>The index file in the web root imports the bootstrap and assigns a variable to it, then calls a a function to initialize the application. Everything up to here works as expected.</p> <p>Now, in the bootstrap file I can print the variable, but when I try to assign a value to the variable an error is thrown. If you take away the assignment statement no errors are thrown.</p> <p>I'm really curious about how the scoping works in this situation. I can print the variable, but I can't asign to it. This is on Python 3.</p> <p><strong>index.py</strong></p> <pre><code># Import modules import sys import cgitb; # Enable error reporting cgitb.enable() #cgitb.enable(display=0, logdir="/tmp") # Add the application root to the include path sys.path.append('path') # Include the bootstrap import bootstrap bootstrap.VAR = 'testVar' bootstrap.initialize() </code></pre> <p><strong>bootstrap.py</strong></p> <pre><code>def initialize(): print('Content-type: text/html\n\n') print(VAR) VAR = 'h' print(VAR) </code></pre> <p>Thanks.</p> <p>Edit: The error message</p> <pre><code>UnboundLocalError: local variable 'VAR' referenced before assignment args = ("local variable 'VAR' referenced before assignment",) with_traceback = &lt;built-in method with_traceback of UnboundLocalError object at 0x00C6ACC0&gt; </code></pre>
1
2009-03-03T07:03:28Z
606,175
<p>Don't declare it global, pass it instead and return it if you need to have a new value, like this:</p> <pre><code>def initialize(a): print('Content-type: text/html\n\n') print a return 'h' ---- import bootstrap b = bootstrap.initialize('testVar') </code></pre>
0
2009-03-03T12:15:47Z
[ "python", "scoping" ]
Python's PubSub/observer Pattern for C++?
605,629
<p>i'm looking for a C++ replacement of the Python PubSub Library in which i don't have to connect a signal with a slot or so, but instead can register for a special Kind of messages, without knowing the object which can send it. </p>
1
2009-03-03T09:02:25Z
607,627
<p>Perhaps you misunderstand what signals and slots are. With signals and slots you don't have to know who sends signals. Your "client" class just declares slots, and an outside manager can connect signals to them.</p> <p>I recommend you to check out Qt. It's an amazing cross-platform library with much more than just GUI support. It has a convenient and efficient implementation of signals and slots which you can use.</p> <p>These days it's also licensed with LGPL (in addition to GPL and commercial), so you can use it for practically any purpose.</p> <p>Re your clarification comment, why not raise an exception for the error? The parent can notify the GUI, or alternatively the GUI can register for a signal the parent emits. This way the parent also doesn't have to know about the GUI.</p>
2
2009-03-03T18:51:31Z
[ "c++", "python", "observer-pattern", "publish-subscribe" ]
Python's PubSub/observer Pattern for C++?
605,629
<p>i'm looking for a C++ replacement of the Python PubSub Library in which i don't have to connect a signal with a slot or so, but instead can register for a special Kind of messages, without knowing the object which can send it. </p>
1
2009-03-03T09:02:25Z
614,473
<p>Can you use the boost libraries? If so then combining the function and bind libraries allows you to do the following. You may be able to do the same using the tr1 functionality if your compiler supports it.</p> <pre><code>#include &lt;iostream&gt; #include &lt;list&gt; #include &lt;boost/function.hpp&gt; #include &lt;boost/bind.hpp&gt; typedef boost::function&lt; void() &gt; EVENT_T ; template&lt;typename F&gt; class Subject { public: virtual void attach ( F o ) { obs_.push_back ( o ); } virtual void notify() { for ( typename std::list&lt;F&gt;::iterator i = obs_.begin(); i != obs_.end(); ++i ) ( *i ) (); } private: std::list&lt;F&gt; obs_; } ; class Button : public Subject&lt;EVENT_T&gt; { public: void onClick() { notify() ; }; }; class Player { public: void play() { std::cout &lt;&lt; "play" &lt;&lt; std::endl ; } void stop() { std::cout &lt;&lt; "stop" &lt;&lt; std::endl ; } }; class Display { public: void started() { std::cout &lt;&lt; "Started playing" &lt;&lt; std::endl ; } }; Button playButton ; Button stopButton ; Player thePlayer; Display theDisplay ; int main ( int argc, char **argv ) { playButton.attach ( boost::bind ( &amp;Player::play, &amp;thePlayer ) ); playButton.attach ( boost::bind ( &amp;Display::started, &amp;theDisplay ) ); stopButton.attach ( boost::bind ( &amp;Player::stop, &amp;thePlayer ) ); playButton.onClick() ; stopButton.onClick() ; return 0; } </code></pre> <p>So when you run this you get:</p> <pre><code>play Started playing stop Press any key to continue. </code></pre> <p>So.. is this the kind of thing you are looking for?</p> <p>See <a href="http://www.ddj.com/cpp/184403873" rel="nofollow">here</a> and <a href="http://www.boost.org/doc/libs/1%5F38%5F0/libs/bind/bind.html#with%5Fboost%5Ffunction" rel="nofollow">here</a> for the source of most of this code.</p> <p>EDIT: The boost::signal library might also do what you want.</p>
2
2009-03-05T11:56:27Z
[ "c++", "python", "observer-pattern", "publish-subscribe" ]
Python's PubSub/observer Pattern for C++?
605,629
<p>i'm looking for a C++ replacement of the Python PubSub Library in which i don't have to connect a signal with a slot or so, but instead can register for a special Kind of messages, without knowing the object which can send it. </p>
1
2009-03-03T09:02:25Z
619,887
<p>Why don't you just implement one? It's not a complicated pattern (well, depending what you really want). Anyway, I already implemented a quick and dirty one some time ago. It is not optimized, synchronous and single threaded. I hope you can use it to make your own.</p> <pre><code>#include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; template&lt;typename MESSAGE&gt; class Topic; class Subscriber; class TopicBase { friend class Subscriber; private: virtual void RemoveSubscriber(Subscriber* subscriber)=0; }; template&lt;typename MESSAGE&gt; class Topic : public TopicBase { friend class Subscriber; private: class Callable { public: Callable(Subscriber* subscriber, void (Subscriber::*method)(const MESSAGE&amp;)) :m_subscriber(subscriber) ,m_method(method) { } void operator()(const MESSAGE&amp; message) { (m_subscriber-&gt;*m_method)(message); } bool operator==(const Callable&amp; other) const { return m_subscriber == other.m_subscriber &amp;&amp; m_method == other.m_method; } public: Subscriber* m_subscriber; void (Subscriber::*m_method)(const MESSAGE&amp;); }; public: ~Topic() { //unregister each subscriber for(std::vector&lt;Callable&gt;::iterator i = m_subscribers.begin(); i != m_subscribers.end(); i++) { std::vector&lt;TopicBase*&gt;&amp; topics = i-&gt;m_subscriber-&gt;m_topics; for(std::vector&lt;TopicBase*&gt;::iterator ti = topics.begin();;) { ti = std::find(ti, topics.end(), this); if(ti == topics.end()) break; ti = topics.erase(ti); } } } void SendMessage(const MESSAGE&amp; message) { for(std::vector&lt;Callable&gt;::iterator i = m_subscribers.begin(); i != m_subscribers.end(); i++) { (*i)(message); } } private: void Subscribe(Subscriber* subscriber, void (Subscriber::*method)(const MESSAGE&amp;)) { m_subscribers.push_back(Callable(subscriber, method)); subscriber-&gt;m_topics.push_back(this); } void Unsubscribe(Subscriber* subscriber, void (Subscriber::*method)(const MESSAGE&amp;)) { std::vector&lt;Callable&gt;::iterator i = std::find(m_subscribers.begin(), m_subscribers.end(), Callable(subscriber, method)); if(i != m_subscribers.end()) { m_subscribers.erase(i); subscriber-&gt;m_topics.erase(std::find(subscriber-&gt;m_topics.begin(), subscriber-&gt;m_topics.end(), this)); //should always find one } } virtual void RemoveSubscriber(Subscriber* subscriber) { for(std::vector&lt;Callable&gt;::iterator i = m_subscribers.begin() ; i != m_subscribers.end(); i++) { if(i-&gt;m_subscriber == subscriber) { m_subscribers.erase(i); break; } } } private: std::vector&lt;Callable&gt; m_subscribers; }; class Subscriber { template&lt;typename T&gt; friend class Topic; public: ~Subscriber() { for(std::vector&lt;TopicBase*&gt;::iterator i = m_topics.begin(); i !=m_topics.end(); i++) { (*i)-&gt;RemoveSubscriber(this); } } protected: template&lt;typename MESSAGE, typename SUBSCRIBER&gt; void Subscribe(Topic&lt;MESSAGE&gt;&amp; topic, void (SUBSCRIBER::*method)(const MESSAGE&amp;)) { topic.Subscribe(this, static_cast&lt;void (Subscriber::*)(const MESSAGE&amp;)&gt;(method)); } template&lt;typename MESSAGE, typename SUBSCRIBER&gt; void Unsubscribe(Topic&lt;MESSAGE&gt;&amp; topic, void (SUBSCRIBER::*method)(const MESSAGE&amp;)) { topic.Unsubscribe(this, static_cast&lt;void (Subscriber::*)(const MESSAGE&amp;)&gt;(method)); } private: std::vector&lt;TopicBase*&gt; m_topics; }; // Test Topic&lt;int&gt; Topic1; class TestSubscriber1 : public Subscriber { public: TestSubscriber1() { Subscribe(Topic1, &amp;TestSubscriber1::onTopic1); } private: void onTopic1(const int&amp; message) { std::cout&lt;&lt;"TestSubscriber1::onTopic1 "&lt;&lt;message&lt;&lt;std::endl; } }; class TestSubscriber2 : public Subscriber { public: void Subscribe(Topic&lt;const char*&gt; &amp;subscriber) { Subscriber::Subscribe(subscriber, &amp;TestSubscriber2::onTopic); } void Unsubscribe(Topic&lt;const char*&gt; &amp;subscriber) { Subscriber::Unsubscribe(subscriber, &amp;TestSubscriber2::onTopic); } private: void onTopic(const char* const&amp; message) { std::cout&lt;&lt;"TestSubscriber1::onTopic1 "&lt;&lt;message&lt;&lt;std::endl; } }; int main() { Topic&lt;const char*&gt;* topic2 = new Topic&lt;const char*&gt;(); { TestSubscriber1 testSubscriber1; Topic1.SendMessage(42); Topic1.SendMessage(5); } Topic1.SendMessage(256); TestSubscriber2 testSubscriber2; testSubscriber2.Subscribe(*topic2); topic2-&gt;SendMessage("owl"); testSubscriber2.Unsubscribe(*topic2); topic2-&gt;SendMessage("owl"); testSubscriber2.Subscribe(*topic2); delete topic2; return 0; } </code></pre>
2
2009-03-06T18:20:00Z
[ "c++", "python", "observer-pattern", "publish-subscribe" ]
What's the search engine used in the new Python documentation?
605,888
<p>Is it built-in in <a href="http://sphinx.pocoo.org/">Sphinx</a>?</p>
12
2009-03-03T10:32:52Z
605,927
<p>Yes. Sphinx is not built-in, however. The search widget is part of sphinx. What context did you mean by "built-in"? </p> <p>On the page iteself: <a href="http://docs.python.org/about.html" rel="nofollow">http://docs.python.org/about.html</a></p> <p><a href="http://sphinx.pocoo.org/" rel="nofollow">http://sphinx.pocoo.org/</a></p>
-4
2009-03-03T10:50:02Z
[ "python", "python-sphinx" ]
What's the search engine used in the new Python documentation?
605,888
<p>Is it built-in in <a href="http://sphinx.pocoo.org/">Sphinx</a>?</p>
12
2009-03-03T10:32:52Z
606,039
<p>The Sphinx search engine is built in Javascript. It uses <em>JQuery</em> and a <em>(sometimes very big)</em> javascript file containing the search terms.</p>
5
2009-03-03T11:34:39Z
[ "python", "python-sphinx" ]
What's the search engine used in the new Python documentation?
605,888
<p>Is it built-in in <a href="http://sphinx.pocoo.org/">Sphinx</a>?</p>
12
2009-03-03T10:32:52Z
606,064
<p>It look like Sphinx contains own search engine for English language. See <a href="http://sphinx.pocoo.org/_static/searchtools.js">http://sphinx.pocoo.org/_static/searchtools.js</a> and searchindex.js/.json (see <a href="http://sphinx.pocoo.org/searchindex.js">Sphinx docs index</a> 36Kb, <a href="http://docs.python.org/searchindex.js">Python docs index</a> 857Kb, and <a href="http://grok.zope.org/doc/dev/searchindex.json">Grok docs</a> 37Kb). </p> <p>Index is being precomputed when docs are generated.</p> <p>When one searches, static page is being loaded and then _static/searchtools.js extract search terms from query string, normalizes (case, stemming, etc.) them and looks up in searchindex.js as it is being loaded.</p> <p>First search attempt takes rather long time, consecutive are much faster as index is cached in your browser.</p>
21
2009-03-03T11:43:27Z
[ "python", "python-sphinx" ]
Python: how to dump cookies of a mechanize.Browser instance?
606,072
<p>I am learning how to use <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a>, a Python module to automate interacting with websites.</p> <p>One feature is the automated handling of cookies. I would to want to dump cookies from a <code>mechanize.Browser</code> instance for debugging purposes, but I can't seem to figure this out myself.</p>
11
2009-03-03T11:47:21Z
606,133
<pre> <code> >>> from mechanize import Browser >>> b = Browser() >>> b._ua_handlers['_cookies'].cookiejar mechanize._clientcookie.CookieJar[] >>> b.open('http://google.com') response_seek_wrapper at 0xb7a922ccL whose wrapped object = closeable_response at 0xb7aa070cL whose fp = socket._fileobject object at 0xb7a94224 >>> >>> b._ua_handlers['_cookies'].cookiejar mechanize._clientcookie.CookieJar[Cookie(version=0, name='PREF', value='ID=57d545c229b4cf3f:TM=1236081634:LM=1236081634:S=p001WJMOr-V8Rlvi', port=None, port_specified=False, domain='.google.com', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=False, expires=1299153634, discard=False, comment=None, comment_url=None, rest={}, rfc2109=False), Cookie(version=0, name='PREF', value='ID=20534d80a5ccf2ea:TM=1236081635:LM=1236081635:S=jW3UotZ0dg8sv6mf', port=None, port_specified=False, domain='.google.com.ua', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=False, expires=1299153635, discard=False, comment=None, comment_url=None, rest={}, rfc2109=False)] >>> </code> </pre>
22
2009-03-03T12:02:03Z
[ "python", "cookies", "mechanize-python" ]
Python: how to dump cookies of a mechanize.Browser instance?
606,072
<p>I am learning how to use <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a>, a Python module to automate interacting with websites.</p> <p>One feature is the automated handling of cookies. I would to want to dump cookies from a <code>mechanize.Browser</code> instance for debugging purposes, but I can't seem to figure this out myself.</p>
11
2009-03-03T11:47:21Z
21,370,031
<p>Mykolas' answer almost gave me what I was looking for. I was looking for how to save the cookie to a file. Since this answer gives margin to dumping the cookie into a file, maybe it is going to be useful for other people coming here looking for that. To save the cookie to a file:</p> <pre><code>br._ua_handlers['_cookies'].cookiejar.save("cookie.txt", ignore_discard=True, ignore_expires=True) </code></pre>
0
2014-01-26T22:18:25Z
[ "python", "cookies", "mechanize-python" ]
Python: how to dump cookies of a mechanize.Browser instance?
606,072
<p>I am learning how to use <a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">mechanize</a>, a Python module to automate interacting with websites.</p> <p>One feature is the automated handling of cookies. I would to want to dump cookies from a <code>mechanize.Browser</code> instance for debugging purposes, but I can't seem to figure this out myself.</p>
11
2009-03-03T11:47:21Z
27,626,224
<p>Just print the CookieJar Instance</p> <pre><code># Browser br = mechanize.Browser() # Cookie Jar cj = cookielib.LWPCookieJar() br.set_cookiejar(cj) # Dump print cj </code></pre>
2
2014-12-23T18:43:59Z
[ "python", "cookies", "mechanize-python" ]
Convert bytes to a Python string
606,191
<p>I'm using this code to get standard output from an external program:</p> <pre><code>&gt;&gt;&gt; from subprocess import * &gt;&gt;&gt; command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] </code></pre> <p>The communicate() method returns an array of bytes:</p> <pre><code>&gt;&gt;&gt; command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>However, I'd like to work with the output as a normal Python string. So that I could print it like this:</p> <pre><code>&gt;&gt;&gt; print(command_stdout) -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1 -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2 </code></pre> <p>I thought that's what the <a href="http://docs.python.org/3.0/library/binascii.html?highlight=b2a#binascii.b2a_qp">binascii.b2a_qp()</a> method is for, but when I tried it, I got the same byte array again:</p> <pre><code>&gt;&gt;&gt; binascii.b2a_qp(command_stdout) b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>Does anybody know how to convert the bytes value back to string? I mean, using the "batteries" instead of doing it manually. And I'd like it to be ok with Python 3.</p>
538
2009-03-03T12:23:01Z
606,199
<p>You need to decode the bytes object to produce a string:</p> <pre><code>&gt;&gt;&gt; b"abcde" b'abcde' # utf-8 is used here because it is a very common encoding, but you # need to use the encoding your data is actually in. &gt;&gt;&gt; b"abcde".decode("utf-8") 'abcde' </code></pre>
888
2009-03-03T12:26:18Z
[ "python", "string", "python-3.x" ]
Convert bytes to a Python string
606,191
<p>I'm using this code to get standard output from an external program:</p> <pre><code>&gt;&gt;&gt; from subprocess import * &gt;&gt;&gt; command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] </code></pre> <p>The communicate() method returns an array of bytes:</p> <pre><code>&gt;&gt;&gt; command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>However, I'd like to work with the output as a normal Python string. So that I could print it like this:</p> <pre><code>&gt;&gt;&gt; print(command_stdout) -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1 -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2 </code></pre> <p>I thought that's what the <a href="http://docs.python.org/3.0/library/binascii.html?highlight=b2a#binascii.b2a_qp">binascii.b2a_qp()</a> method is for, but when I tried it, I got the same byte array again:</p> <pre><code>&gt;&gt;&gt; binascii.b2a_qp(command_stdout) b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>Does anybody know how to convert the bytes value back to string? I mean, using the "batteries" instead of doing it manually. And I'd like it to be ok with Python 3.</p>
538
2009-03-03T12:23:01Z
606,205
<p>You need to decode the byte string and turn it in to a character (unicode) string. </p> <pre><code>b'hello'.decode(encoding) </code></pre> <p>or </p> <pre><code>str(b'hello', encoding) </code></pre>
66
2009-03-03T12:28:31Z
[ "python", "string", "python-3.x" ]
Convert bytes to a Python string
606,191
<p>I'm using this code to get standard output from an external program:</p> <pre><code>&gt;&gt;&gt; from subprocess import * &gt;&gt;&gt; command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] </code></pre> <p>The communicate() method returns an array of bytes:</p> <pre><code>&gt;&gt;&gt; command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>However, I'd like to work with the output as a normal Python string. So that I could print it like this:</p> <pre><code>&gt;&gt;&gt; print(command_stdout) -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1 -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2 </code></pre> <p>I thought that's what the <a href="http://docs.python.org/3.0/library/binascii.html?highlight=b2a#binascii.b2a_qp">binascii.b2a_qp()</a> method is for, but when I tried it, I got the same byte array again:</p> <pre><code>&gt;&gt;&gt; binascii.b2a_qp(command_stdout) b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>Does anybody know how to convert the bytes value back to string? I mean, using the "batteries" instead of doing it manually. And I'd like it to be ok with Python 3.</p>
538
2009-03-03T12:23:01Z
6,738,578
<p>I think what you actually want is this:</p> <pre><code>&gt;&gt;&gt; from subprocess import * &gt;&gt;&gt; command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] &gt;&gt;&gt; command_text = command_stdout.decode(encoding='windows-1252') </code></pre> <p>Aaron's answer was correct, except that you need to know WHICH encoding to use. And I believe that Windows uses 'windows-1252'. It will only matter if you have some unusual (non-ascii) characters in your content, but then it will make a difference.</p> <p>By the way, the fact that it DOES matter is the reason that Python moved to using two different types for binary and text data: it can't convert magically between them because it doesn't know the encoding unless you tell it! The only way YOU would know is to read the Windows documentation (or read it here).</p>
23
2011-07-18T19:51:15Z
[ "python", "string", "python-3.x" ]
Convert bytes to a Python string
606,191
<p>I'm using this code to get standard output from an external program:</p> <pre><code>&gt;&gt;&gt; from subprocess import * &gt;&gt;&gt; command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] </code></pre> <p>The communicate() method returns an array of bytes:</p> <pre><code>&gt;&gt;&gt; command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>However, I'd like to work with the output as a normal Python string. So that I could print it like this:</p> <pre><code>&gt;&gt;&gt; print(command_stdout) -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1 -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2 </code></pre> <p>I thought that's what the <a href="http://docs.python.org/3.0/library/binascii.html?highlight=b2a#binascii.b2a_qp">binascii.b2a_qp()</a> method is for, but when I tried it, I got the same byte array again:</p> <pre><code>&gt;&gt;&gt; binascii.b2a_qp(command_stdout) b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>Does anybody know how to convert the bytes value back to string? I mean, using the "batteries" instead of doing it manually. And I'd like it to be ok with Python 3.</p>
538
2009-03-03T12:23:01Z
12,073,686
<p>I think this way is easy:</p> <pre><code>bytes = [112, 52, 52] "".join(map(chr, bytes)) &gt;&gt; p44 </code></pre>
61
2012-08-22T12:57:08Z
[ "python", "string", "python-3.x" ]
Convert bytes to a Python string
606,191
<p>I'm using this code to get standard output from an external program:</p> <pre><code>&gt;&gt;&gt; from subprocess import * &gt;&gt;&gt; command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] </code></pre> <p>The communicate() method returns an array of bytes:</p> <pre><code>&gt;&gt;&gt; command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>However, I'd like to work with the output as a normal Python string. So that I could print it like this:</p> <pre><code>&gt;&gt;&gt; print(command_stdout) -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1 -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2 </code></pre> <p>I thought that's what the <a href="http://docs.python.org/3.0/library/binascii.html?highlight=b2a#binascii.b2a_qp">binascii.b2a_qp()</a> method is for, but when I tried it, I got the same byte array again:</p> <pre><code>&gt;&gt;&gt; binascii.b2a_qp(command_stdout) b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>Does anybody know how to convert the bytes value back to string? I mean, using the "batteries" instead of doing it manually. And I'd like it to be ok with Python 3.</p>
538
2009-03-03T12:23:01Z
21,059,713
<p>From <a href="http://docs.python.org/3/library/sys.html" rel="nofollow">http://docs.python.org/3/library/sys.html</a>,</p> <p>To write or read binary data from/to the standard streams, use the underlying binary buffer. For example, to write bytes to stdout, use sys.stdout.buffer.write(b'abc').</p>
1
2014-01-11T07:15:18Z
[ "python", "string", "python-3.x" ]
Convert bytes to a Python string
606,191
<p>I'm using this code to get standard output from an external program:</p> <pre><code>&gt;&gt;&gt; from subprocess import * &gt;&gt;&gt; command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] </code></pre> <p>The communicate() method returns an array of bytes:</p> <pre><code>&gt;&gt;&gt; command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>However, I'd like to work with the output as a normal Python string. So that I could print it like this:</p> <pre><code>&gt;&gt;&gt; print(command_stdout) -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1 -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2 </code></pre> <p>I thought that's what the <a href="http://docs.python.org/3.0/library/binascii.html?highlight=b2a#binascii.b2a_qp">binascii.b2a_qp()</a> method is for, but when I tried it, I got the same byte array again:</p> <pre><code>&gt;&gt;&gt; binascii.b2a_qp(command_stdout) b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>Does anybody know how to convert the bytes value back to string? I mean, using the "batteries" instead of doing it manually. And I'd like it to be ok with Python 3.</p>
538
2009-03-03T12:23:01Z
21,262,396
<p>Set universal_newlines to True, i.e.</p> <pre><code>command_stdout = Popen(['ls', '-l'], stdout=PIPE, universal_newlines=True).communicate()[0] </code></pre>
14
2014-01-21T15:31:09Z
[ "python", "string", "python-3.x" ]
Convert bytes to a Python string
606,191
<p>I'm using this code to get standard output from an external program:</p> <pre><code>&gt;&gt;&gt; from subprocess import * &gt;&gt;&gt; command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] </code></pre> <p>The communicate() method returns an array of bytes:</p> <pre><code>&gt;&gt;&gt; command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>However, I'd like to work with the output as a normal Python string. So that I could print it like this:</p> <pre><code>&gt;&gt;&gt; print(command_stdout) -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1 -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2 </code></pre> <p>I thought that's what the <a href="http://docs.python.org/3.0/library/binascii.html?highlight=b2a#binascii.b2a_qp">binascii.b2a_qp()</a> method is for, but when I tried it, I got the same byte array again:</p> <pre><code>&gt;&gt;&gt; binascii.b2a_qp(command_stdout) b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>Does anybody know how to convert the bytes value back to string? I mean, using the "batteries" instead of doing it manually. And I'd like it to be ok with Python 3.</p>
538
2009-03-03T12:23:01Z
27,527,728
<p>If you don't know the encoding, then to read binary input into string in Python 3 and Python 2 compatible way, use ancient MS-DOS <a href="https://en.wikipedia.org/wiki/Code_page_437">cp437</a> encoding:</p> <pre><code>PY3K = sys.version_info &gt;= (3, 0) lines = [] for line in stream: if not PY3K: lines.append(line) else: lines.append(line.decode('cp437')) </code></pre> <p>Because encoding is unknown, expect non-English symbols to translate to characters of <code>cp437</code> (English chars are not translated, because they match in most single byte encodings and UTF-8).</p> <p>Decoding arbitrary binary input to UTF-8 is unsafe, because you may get this:</p> <pre><code>&gt;&gt;&gt; b'\x00\x01\xffsd'.decode('utf-8') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 2: invalid start byte </code></pre> <p>The same applies to <code>latin-1</code>, which was popular (default?) for Python 2. See the missing points in <a href="https://en.wikipedia.org/wiki/ISO/IEC_8859-1#Codepage_layout">Codepage Layout</a> - it is where Python chokes with infamous <code>ordinal not in range</code>.</p> <p><strong>UPDATE 20150604</strong>: There are rumors that Python 3 has <code>surrogateescape</code> error strategy for encoding stuff into binary data without data loss and crashes, but it needs conversion tests <code>[binary] -&gt; [str] -&gt; [binary]</code> to validate both performance and reliability.</p> <p><strong>P.S.</strong> I used to be a Python fanboy like you, then I took an ordinal not in range.</p>
23
2014-12-17T14:23:09Z
[ "python", "string", "python-3.x" ]
Convert bytes to a Python string
606,191
<p>I'm using this code to get standard output from an external program:</p> <pre><code>&gt;&gt;&gt; from subprocess import * &gt;&gt;&gt; command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] </code></pre> <p>The communicate() method returns an array of bytes:</p> <pre><code>&gt;&gt;&gt; command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>However, I'd like to work with the output as a normal Python string. So that I could print it like this:</p> <pre><code>&gt;&gt;&gt; print(command_stdout) -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1 -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2 </code></pre> <p>I thought that's what the <a href="http://docs.python.org/3.0/library/binascii.html?highlight=b2a#binascii.b2a_qp">binascii.b2a_qp()</a> method is for, but when I tried it, I got the same byte array again:</p> <pre><code>&gt;&gt;&gt; binascii.b2a_qp(command_stdout) b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>Does anybody know how to convert the bytes value back to string? I mean, using the "batteries" instead of doing it manually. And I'd like it to be ok with Python 3.</p>
538
2009-03-03T12:23:01Z
33,690,538
<p>While <a href="http://stackoverflow.com/a/33688948/1587329">@Aaron Maenpaa's answer</a> just works, a user <a href="http://stackoverflow.com/questions/33688837/urllib-for-python-3/33688948#comment55151210_33688948">recently asked</a></p> <blockquote> <p>Is there any more simply way? 'fhand.read().decode("ASCII")' [...] It's so long!</p> </blockquote> <p>You can use</p> <pre><code>command_stdout.decode() </code></pre> <p><code>decode()</code> has a <a href="https://docs.python.org/3/library/stdtypes.html#bytes-and-bytearray-operations">standard argument</a></p> <blockquote> <p><code>codecs.decode(obj, encoding='utf-8', errors='strict')</code></p> </blockquote>
5
2015-11-13T10:24:21Z
[ "python", "string", "python-3.x" ]
Convert bytes to a Python string
606,191
<p>I'm using this code to get standard output from an external program:</p> <pre><code>&gt;&gt;&gt; from subprocess import * &gt;&gt;&gt; command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] </code></pre> <p>The communicate() method returns an array of bytes:</p> <pre><code>&gt;&gt;&gt; command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>However, I'd like to work with the output as a normal Python string. So that I could print it like this:</p> <pre><code>&gt;&gt;&gt; print(command_stdout) -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1 -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2 </code></pre> <p>I thought that's what the <a href="http://docs.python.org/3.0/library/binascii.html?highlight=b2a#binascii.b2a_qp">binascii.b2a_qp()</a> method is for, but when I tried it, I got the same byte array again:</p> <pre><code>&gt;&gt;&gt; binascii.b2a_qp(command_stdout) b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>Does anybody know how to convert the bytes value back to string? I mean, using the "batteries" instead of doing it manually. And I'd like it to be ok with Python 3.</p>
538
2009-03-03T12:23:01Z
37,557,475
<p>I made a function to clean a list</p> <pre><code>def cleanLists(self, lista): lista = [x.strip() for x in lista] lista = [x.replace('\n', '') for x in lista] lista = [x.replace('\b', '') for x in lista] lista = [x.encode('utf8') for x in lista] lista = [x.decode('utf8') for x in lista] return lista </code></pre>
1
2016-06-01T00:03:04Z
[ "python", "string", "python-3.x" ]
Convert bytes to a Python string
606,191
<p>I'm using this code to get standard output from an external program:</p> <pre><code>&gt;&gt;&gt; from subprocess import * &gt;&gt;&gt; command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] </code></pre> <p>The communicate() method returns an array of bytes:</p> <pre><code>&gt;&gt;&gt; command_stdout b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>However, I'd like to work with the output as a normal Python string. So that I could print it like this:</p> <pre><code>&gt;&gt;&gt; print(command_stdout) -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1 -rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2 </code></pre> <p>I thought that's what the <a href="http://docs.python.org/3.0/library/binascii.html?highlight=b2a#binascii.b2a_qp">binascii.b2a_qp()</a> method is for, but when I tried it, I got the same byte array again:</p> <pre><code>&gt;&gt;&gt; binascii.b2a_qp(command_stdout) b'total 0\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file1\n-rw-rw-r-- 1 thomas thomas 0 Mar 3 07:03 file2\n' </code></pre> <p>Does anybody know how to convert the bytes value back to string? I mean, using the "batteries" instead of doing it manually. And I'd like it to be ok with Python 3.</p>
538
2009-03-03T12:23:01Z
38,102,444
<p>In Python 3 you can use directly:</p> <pre><code>b'hello'.decode() </code></pre> <p>which is equivalent to</p> <pre><code>b'hello'.decode(encoding="utf-8") </code></pre> <p>here the default encoding is "utf-8", or you can check it by:</p> <pre><code>&gt;&gt; import sys &gt;&gt; sys.getdefaultencoding() </code></pre>
4
2016-06-29T14:21:21Z
[ "python", "string", "python-3.x" ]
python regex trouble
606,221
<p>I have the following code :</p> <pre><code>what = re.match("get|post|put|head\s+(\S+) ",data,re.IGNORECASE)</code></pre> <p>and in the <strong>data</strong> variable let's say I have this line :</p> <pre>GET some-site.com HTTP/1.0 ...</pre> <p>If I stop the script in the debugger, and inspect the <strong>what</strong> variable, I can see it only matched GET. Why doesn't it match some-site.com ?</p>
1
2009-03-03T12:33:45Z
606,237
<pre> <code> >>> re.match("(get|post|put|head)\s+(\S+) ",'GET some-site.com HTTP/1.0 ...',re.IGNORECASE).groups() ('GET', 'some-site.com') >>> </code> </pre>
3
2009-03-03T12:38:52Z
[ "python", "regex" ]
python regex trouble
606,221
<p>I have the following code :</p> <pre><code>what = re.match("get|post|put|head\s+(\S+) ",data,re.IGNORECASE)</code></pre> <p>and in the <strong>data</strong> variable let's say I have this line :</p> <pre>GET some-site.com HTTP/1.0 ...</pre> <p>If I stop the script in the debugger, and inspect the <strong>what</strong> variable, I can see it only matched GET. Why doesn't it match some-site.com ?</p>
1
2009-03-03T12:33:45Z
606,276
<p>Regex language operator precedence puts <code>head\s+(\S+)</code> as the 4th alternative. The parenthesis in <em>@Mykola Kharechko</em>'s answer arrange for <code>head</code> as the 4th alternative, and <code>\s+(\S+) </code> is appended to whatever alternative matched the group.</p>
4
2009-03-03T12:52:48Z
[ "python", "regex" ]
python regex trouble
606,221
<p>I have the following code :</p> <pre><code>what = re.match("get|post|put|head\s+(\S+) ",data,re.IGNORECASE)</code></pre> <p>and in the <strong>data</strong> variable let's say I have this line :</p> <pre>GET some-site.com HTTP/1.0 ...</pre> <p>If I stop the script in the debugger, and inspect the <strong>what</strong> variable, I can see it only matched GET. Why doesn't it match some-site.com ?</p>
1
2009-03-03T12:33:45Z
606,296
<p>+1 Mykola's answer and gimel's explanation. In addition, do you really want to use regex for this? As you've found out, they are not as straightforward as they look. Here's a non-regex-based method:</p> <pre><code>def splitandpad(s, find, limit): seq= s.split(find, limit) return seq+['']*(limit-len(seq)+1) method, path, protocol= splitandpad(data, ' ', 2) if method.lower() not in ('get', 'head', 'post', 'put'): # complain, unknown method if protocol.lower() not in ('http/1.0', 'http/1.1'): # complain, unknown protocol </code></pre>
1
2009-03-03T12:59:45Z
[ "python", "regex" ]
How do I configure my sys.path variable in linux?
606,226
<p>I want to automatically add entries to python's sys.path variable when run by my user in linux. Is there something I can tweak in my home directory to get it done?</p>
2
2009-03-03T12:35:03Z
606,269
<p>The environment variable <a href="http://docs.python.org/tutorial/modules.html#the-module-search-path"><code>PYTHONPATH</code></a> sets the initial <code>sys.path</code> value.</p> <p>You can set that it your shell initialization script (e.g. <code>.bashrc</code> or <code>.cshrc</code>)</p>
6
2009-03-03T12:49:36Z
[ "python", "linux", "configuration", "path" ]
How do I install python's sphinx documentation generator in linux?
606,283
<p>And how do I run it?</p>
2
2009-03-03T12:54:00Z
606,287
<p><a href="http://sphinx.pocoo.org/">Sphinx website</a> says:</p> <pre><code>easy_install -U Sphinx </code></pre> <p>If you want that installed in system python you'd probably need elevated permissions with <code>sudo</code>:</p> <pre><code>sudo easy_install -U Sphinx </code></pre> <p>If you do not have <code>easy_install</code> yet, see <a href="http://peak.telecommunity.com/DevCenter/EasyInstall">http://peak.telecommunity.com/DevCenter/EasyInstall</a></p>
6
2009-03-03T12:56:37Z
[ "python", "python-sphinx" ]
How do I install python's sphinx documentation generator in linux?
606,283
<p>And how do I run it?</p>
2
2009-03-03T12:54:00Z
606,392
<p>How do I run it?</p> <p><a href="http://sphinx-doc.org/tutorial.html#running-the-build" rel="nofollow">http://sphinx-doc.org/tutorial.html#running-the-build</a></p> <p>Basically, the easiest way is to start with <code>sphinx-quickstart</code> command.</p>
1
2009-03-03T13:28:34Z
[ "python", "python-sphinx" ]
How do I install python's sphinx documentation generator in linux?
606,283
<p>And how do I run it?</p>
2
2009-03-03T12:54:00Z
606,616
<p><a href="http://showmedo.com/videos/video?name=2910020&amp;fromSeriesID=291" rel="nofollow">http://showmedo.com/videos/video?name=2910020&amp;fromSeriesID=291</a></p> <p>This demo shows how you can use sphinx to document your own program.</p>
1
2009-03-03T14:37:36Z
[ "python", "python-sphinx" ]
How can I debug a regular expression in python?
606,350
<p>Is there a way to debug a regular expression in Python? And I'm not referring to the process of trying and trying till they work :)</p> <p>EDIT: here is how regexes can be debugged in perl :</p> <pre><code> use re 'debug'; my $str = "GET http://some-site.com HTTP/1.1"; if($str =~/get\s+(\S+)/i) { print "MATCH:$1\n"; } </code></pre> <p>The code above produces the following output on my computer when ran :</p> <pre><code> Compiling REx "get\s+(\S+)" Final program: 1: EXACTF (3) 3: PLUS (5) 4: SPACE (0) 5: OPEN1 (7) 7: PLUS (9) 8: NSPACE (0) 9: CLOSE1 (11) 11: END (0) stclass EXACTF minlen 5 Matching REx "get\s+(\S+)" against "GET http://some-site.com HTTP/1.1" Matching stclass EXACTF against "GET http://some-site.com HTTP/1.1" (33 chars) 0 | 1:EXACTF (3) 3 | 3:PLUS(5) SPACE can match 1 times out of 2147483647... 4 | 5: OPEN1(7) 4 | 7: PLUS(9) NSPACE can match 20 times out of 2147483647... 24 | 9: CLOSE1(11) 24 | 11: END(0) Match successful! MATCH:http://some-site.com Freeing REx: "get\s+(\S+)" </code></pre>
10
2009-03-03T13:13:45Z
606,363
<p>Why don't you use some regEx tool (i usually use <a href="http://sourceforge.net/projects/regulator/" rel="nofollow">Regulator</a>) and test the regex-expression there and when you are satisfied, just copy/paste it into your code.</p>
1
2009-03-03T13:16:51Z
[ "python", "regex", "debugging" ]
How can I debug a regular expression in python?
606,350
<p>Is there a way to debug a regular expression in Python? And I'm not referring to the process of trying and trying till they work :)</p> <p>EDIT: here is how regexes can be debugged in perl :</p> <pre><code> use re 'debug'; my $str = "GET http://some-site.com HTTP/1.1"; if($str =~/get\s+(\S+)/i) { print "MATCH:$1\n"; } </code></pre> <p>The code above produces the following output on my computer when ran :</p> <pre><code> Compiling REx "get\s+(\S+)" Final program: 1: EXACTF (3) 3: PLUS (5) 4: SPACE (0) 5: OPEN1 (7) 7: PLUS (9) 8: NSPACE (0) 9: CLOSE1 (11) 11: END (0) stclass EXACTF minlen 5 Matching REx "get\s+(\S+)" against "GET http://some-site.com HTTP/1.1" Matching stclass EXACTF against "GET http://some-site.com HTTP/1.1" (33 chars) 0 | 1:EXACTF (3) 3 | 3:PLUS(5) SPACE can match 1 times out of 2147483647... 4 | 5: OPEN1(7) 4 | 7: PLUS(9) NSPACE can match 20 times out of 2147483647... 24 | 9: CLOSE1(11) 24 | 11: END(0) Match successful! MATCH:http://some-site.com Freeing REx: "get\s+(\S+)" </code></pre>
10
2009-03-03T13:13:45Z
606,366
<p>Not sure about doing such a thing directly in Python, but I could definitely suggest using a RegEx editor tool. That's likely to be your best bet anyway. Personally, I've used <a href="http://sourceforge.net/projects/regulator/" rel="nofollow">The Regulator</a> and found it to very helpful. Some others are listed in <a href="http://stackoverflow.com/questions/32282/regex-testing-tools#32365">this SO thread</a>.</p>
0
2009-03-03T13:17:56Z
[ "python", "regex", "debugging" ]
How can I debug a regular expression in python?
606,350
<p>Is there a way to debug a regular expression in Python? And I'm not referring to the process of trying and trying till they work :)</p> <p>EDIT: here is how regexes can be debugged in perl :</p> <pre><code> use re 'debug'; my $str = "GET http://some-site.com HTTP/1.1"; if($str =~/get\s+(\S+)/i) { print "MATCH:$1\n"; } </code></pre> <p>The code above produces the following output on my computer when ran :</p> <pre><code> Compiling REx "get\s+(\S+)" Final program: 1: EXACTF (3) 3: PLUS (5) 4: SPACE (0) 5: OPEN1 (7) 7: PLUS (9) 8: NSPACE (0) 9: CLOSE1 (11) 11: END (0) stclass EXACTF minlen 5 Matching REx "get\s+(\S+)" against "GET http://some-site.com HTTP/1.1" Matching stclass EXACTF against "GET http://some-site.com HTTP/1.1" (33 chars) 0 | 1:EXACTF (3) 3 | 3:PLUS(5) SPACE can match 1 times out of 2147483647... 4 | 5: OPEN1(7) 4 | 7: PLUS(9) NSPACE can match 20 times out of 2147483647... 24 | 9: CLOSE1(11) 24 | 11: END(0) Match successful! MATCH:http://some-site.com Freeing REx: "get\s+(\S+)" </code></pre>
10
2009-03-03T13:13:45Z
606,371
<pre> <code> >>> p = re.compile('.*', re.DEBUG) max_repeat 0 65535 any None >>> </code> </pre> <p><a href="http://stackoverflow.com/questions/580993/regex-operator-vs-separate-runs-for-each-sub-expression/582227#582227">http://stackoverflow.com/questions/580993/regex-operator-vs-separate-runs-for-each-sub-expression/582227#582227</a></p>
16
2009-03-03T13:21:12Z
[ "python", "regex", "debugging" ]
How can I debug a regular expression in python?
606,350
<p>Is there a way to debug a regular expression in Python? And I'm not referring to the process of trying and trying till they work :)</p> <p>EDIT: here is how regexes can be debugged in perl :</p> <pre><code> use re 'debug'; my $str = "GET http://some-site.com HTTP/1.1"; if($str =~/get\s+(\S+)/i) { print "MATCH:$1\n"; } </code></pre> <p>The code above produces the following output on my computer when ran :</p> <pre><code> Compiling REx "get\s+(\S+)" Final program: 1: EXACTF (3) 3: PLUS (5) 4: SPACE (0) 5: OPEN1 (7) 7: PLUS (9) 8: NSPACE (0) 9: CLOSE1 (11) 11: END (0) stclass EXACTF minlen 5 Matching REx "get\s+(\S+)" against "GET http://some-site.com HTTP/1.1" Matching stclass EXACTF against "GET http://some-site.com HTTP/1.1" (33 chars) 0 | 1:EXACTF (3) 3 | 3:PLUS(5) SPACE can match 1 times out of 2147483647... 4 | 5: OPEN1(7) 4 | 7: PLUS(9) NSPACE can match 20 times out of 2147483647... 24 | 9: CLOSE1(11) 24 | 11: END(0) Match successful! MATCH:http://some-site.com Freeing REx: "get\s+(\S+)" </code></pre>
10
2009-03-03T13:13:45Z
606,379
<p>Similar to the already mentioned, there is also <a href="http://www.regexbuddy.com/benefits.html" rel="nofollow">Regexbuddy</a></p>
1
2009-03-03T13:23:04Z
[ "python", "regex", "debugging" ]
How can I debug a regular expression in python?
606,350
<p>Is there a way to debug a regular expression in Python? And I'm not referring to the process of trying and trying till they work :)</p> <p>EDIT: here is how regexes can be debugged in perl :</p> <pre><code> use re 'debug'; my $str = "GET http://some-site.com HTTP/1.1"; if($str =~/get\s+(\S+)/i) { print "MATCH:$1\n"; } </code></pre> <p>The code above produces the following output on my computer when ran :</p> <pre><code> Compiling REx "get\s+(\S+)" Final program: 1: EXACTF (3) 3: PLUS (5) 4: SPACE (0) 5: OPEN1 (7) 7: PLUS (9) 8: NSPACE (0) 9: CLOSE1 (11) 11: END (0) stclass EXACTF minlen 5 Matching REx "get\s+(\S+)" against "GET http://some-site.com HTTP/1.1" Matching stclass EXACTF against "GET http://some-site.com HTTP/1.1" (33 chars) 0 | 1:EXACTF (3) 3 | 3:PLUS(5) SPACE can match 1 times out of 2147483647... 4 | 5: OPEN1(7) 4 | 7: PLUS(9) NSPACE can match 20 times out of 2147483647... 24 | 9: CLOSE1(11) 24 | 11: END(0) Match successful! MATCH:http://some-site.com Freeing REx: "get\s+(\S+)" </code></pre>
10
2009-03-03T13:13:45Z
606,477
<p>I quite often use <a href="http://regexpal.com/" rel="nofollow">RegexPal</a> for quick checks (an online regular expression prototyper). It has a lot of the common expressions listed along with a simple expression. Very handy when you don't have a dedicated tool and just need a quick way to work out a somple regex.</p>
-1
2009-03-03T14:00:22Z
[ "python", "regex", "debugging" ]
How can I debug a regular expression in python?
606,350
<p>Is there a way to debug a regular expression in Python? And I'm not referring to the process of trying and trying till they work :)</p> <p>EDIT: here is how regexes can be debugged in perl :</p> <pre><code> use re 'debug'; my $str = "GET http://some-site.com HTTP/1.1"; if($str =~/get\s+(\S+)/i) { print "MATCH:$1\n"; } </code></pre> <p>The code above produces the following output on my computer when ran :</p> <pre><code> Compiling REx "get\s+(\S+)" Final program: 1: EXACTF (3) 3: PLUS (5) 4: SPACE (0) 5: OPEN1 (7) 7: PLUS (9) 8: NSPACE (0) 9: CLOSE1 (11) 11: END (0) stclass EXACTF minlen 5 Matching REx "get\s+(\S+)" against "GET http://some-site.com HTTP/1.1" Matching stclass EXACTF against "GET http://some-site.com HTTP/1.1" (33 chars) 0 | 1:EXACTF (3) 3 | 3:PLUS(5) SPACE can match 1 times out of 2147483647... 4 | 5: OPEN1(7) 4 | 7: PLUS(9) NSPACE can match 20 times out of 2147483647... 24 | 9: CLOSE1(11) 24 | 11: END(0) Match successful! MATCH:http://some-site.com Freeing REx: "get\s+(\S+)" </code></pre>
10
2009-03-03T13:13:45Z
608,959
<p>What RegexBuddy has that the other tools don't have is a built-in <a href="http://www.regexbuddy.com/debug.html" rel="nofollow">debugger</a> that shows you the entire matching process of both successful and failed match attempts. The other tools only show the final result (which RegexBuddy can show too).</p>
1
2009-03-04T01:44:12Z
[ "python", "regex", "debugging" ]
How can I debug a regular expression in python?
606,350
<p>Is there a way to debug a regular expression in Python? And I'm not referring to the process of trying and trying till they work :)</p> <p>EDIT: here is how regexes can be debugged in perl :</p> <pre><code> use re 'debug'; my $str = "GET http://some-site.com HTTP/1.1"; if($str =~/get\s+(\S+)/i) { print "MATCH:$1\n"; } </code></pre> <p>The code above produces the following output on my computer when ran :</p> <pre><code> Compiling REx "get\s+(\S+)" Final program: 1: EXACTF (3) 3: PLUS (5) 4: SPACE (0) 5: OPEN1 (7) 7: PLUS (9) 8: NSPACE (0) 9: CLOSE1 (11) 11: END (0) stclass EXACTF minlen 5 Matching REx "get\s+(\S+)" against "GET http://some-site.com HTTP/1.1" Matching stclass EXACTF against "GET http://some-site.com HTTP/1.1" (33 chars) 0 | 1:EXACTF (3) 3 | 3:PLUS(5) SPACE can match 1 times out of 2147483647... 4 | 5: OPEN1(7) 4 | 7: PLUS(9) NSPACE can match 20 times out of 2147483647... 24 | 9: CLOSE1(11) 24 | 11: END(0) Match successful! MATCH:http://some-site.com Freeing REx: "get\s+(\S+)" </code></pre>
10
2009-03-03T13:13:45Z
27,144,035
<p><a href="https://www.debuggex.com" rel="nofollow">https://www.debuggex.com</a> is also pretty good. It's an online Python (and a couple more languages) debugger, which has a pretty neat visualization of what does and what doesn't match. A pretty good resource if you need to draft a regexp quickly.</p>
0
2014-11-26T08:08:55Z
[ "python", "regex", "debugging" ]
How to get filename of the __main__ module in Python?
606,561
<p>Suppose I have two modules:</p> <p>a.py:</p> <pre><code>import b print __name__, __file__ </code></pre> <p>b.py:</p> <pre><code>print __name__, __file__ </code></pre> <p>I run the "a.py" file. This prints:</p> <pre><code>b C:\path\to\code\b.py __main__ C:\path\to\code\a.py </code></pre> <p><strong>Question</strong>: how do I obtain the path to the <code>__main__</code> module ("a.py" in this case) from within the "b.py" library?</p>
38
2009-03-03T14:24:11Z
606,574
<p>Perhaps this will do the trick:</p> <pre><code>import sys from os import path print path.abspath(sys.modules['__main__'].__file__) </code></pre> <p>Note that, for safety, you should check whether the <code>__main__</code> module has a <code>__file__</code> attribute. If it's dynamically created, or is just being run in the interactive python console, it won't have a <code>__file__</code>:</p> <pre><code>python &gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.modules['__main__'] &lt;module '__main__' (built-in)&gt; &gt;&gt;&gt; print sys.modules['__main__'].__file__ AttributeError: 'module' object has no attribute '__file__' </code></pre> <p>A simple hasattr() check will do the trick to guard against scenario 2 if that's a possibility in your app.</p>
22
2009-03-03T14:27:58Z
[ "python", "python-module" ]
How to get filename of the __main__ module in Python?
606,561
<p>Suppose I have two modules:</p> <p>a.py:</p> <pre><code>import b print __name__, __file__ </code></pre> <p>b.py:</p> <pre><code>print __name__, __file__ </code></pre> <p>I run the "a.py" file. This prints:</p> <pre><code>b C:\path\to\code\b.py __main__ C:\path\to\code\a.py </code></pre> <p><strong>Question</strong>: how do I obtain the path to the <code>__main__</code> module ("a.py" in this case) from within the "b.py" library?</p>
38
2009-03-03T14:24:11Z
606,998
<pre><code>import __main__ print __main__.__file__ </code></pre>
49
2009-03-03T16:04:22Z
[ "python", "python-module" ]
How to get filename of the __main__ module in Python?
606,561
<p>Suppose I have two modules:</p> <p>a.py:</p> <pre><code>import b print __name__, __file__ </code></pre> <p>b.py:</p> <pre><code>print __name__, __file__ </code></pre> <p>I run the "a.py" file. This prints:</p> <pre><code>b C:\path\to\code\b.py __main__ C:\path\to\code\a.py </code></pre> <p><strong>Question</strong>: how do I obtain the path to the <code>__main__</code> module ("a.py" in this case) from within the "b.py" library?</p>
38
2009-03-03T14:24:11Z
608,036
<p>The python code below provides additional functionality, including that it works seamlessly with <a href="http://www.py2exe.org/" rel="nofollow"><code>py2exe</code></a> executables.</p> <p>I use similar code to like this to find paths relative to the running script, aka <code>__main__</code>. as an added benefit, it works cross-platform including Windows.</p> <pre><code>import imp import os import sys def main_is_frozen(): return (hasattr(sys, "frozen") or # new py2exe hasattr(sys, "importers") # old py2exe or imp.is_frozen("__main__")) # tools/freeze def get_main_dir(): if main_is_frozen(): # print 'Running from path', os.path.dirname(sys.executable) return os.path.dirname(sys.executable) return os.path.dirname(sys.argv[0]) # find path to where we are running path_to_script=get_main_dir() # OPTIONAL: # add the sibling 'lib' dir to our module search path lib_path = os.path.join(get_main_dir(), os.path.pardir, 'lib') sys.path.insert(0, lib_path) # OPTIONAL: # use info to find relative data files in 'data' subdir datafile1 = os.path.join(get_main_dir(), 'data', 'file1') </code></pre> <p>Hopefully the above example code can provide additional insight into how to determine the path to the running script...</p>
13
2009-03-03T20:29:30Z
[ "python", "python-module" ]
How to get filename of the __main__ module in Python?
606,561
<p>Suppose I have two modules:</p> <p>a.py:</p> <pre><code>import b print __name__, __file__ </code></pre> <p>b.py:</p> <pre><code>print __name__, __file__ </code></pre> <p>I run the "a.py" file. This prints:</p> <pre><code>b C:\path\to\code\b.py __main__ C:\path\to\code\a.py </code></pre> <p><strong>Question</strong>: how do I obtain the path to the <code>__main__</code> module ("a.py" in this case) from within the "b.py" library?</p>
38
2009-03-03T14:24:11Z
14,387,977
<pre><code>import sys, os def getExecPath(): try: sFile = os.path.abspath(sys.modules['__main__'].__file__) except: sFile = sys.executable return os.path.dirname(sFile) </code></pre> <p>This function will work for Python and Cython compiled programs.</p>
1
2013-01-17T20:57:33Z
[ "python", "python-module" ]
How to get filename of the __main__ module in Python?
606,561
<p>Suppose I have two modules:</p> <p>a.py:</p> <pre><code>import b print __name__, __file__ </code></pre> <p>b.py:</p> <pre><code>print __name__, __file__ </code></pre> <p>I run the "a.py" file. This prints:</p> <pre><code>b C:\path\to\code\b.py __main__ C:\path\to\code\a.py </code></pre> <p><strong>Question</strong>: how do I obtain the path to the <code>__main__</code> module ("a.py" in this case) from within the "b.py" library?</p>
38
2009-03-03T14:24:11Z
22,884,727
<p>Another method would be to use <code>sys.argv[0]</code>.</p> <pre><code>import os import sys main_file = os.path.realpath(sys.argv[0]) if sys.argv[0] else None </code></pre> <p><code>sys.argv[0]</code> will be an empty string if Python gets start with <code>-c</code> or if checked from the Python console.</p>
2
2014-04-05T18:08:36Z
[ "python", "python-module" ]
Can I use VS2005 to build extensions for a Python system built with VS2003
606,680
<p><a href="http://rdflib.net/" rel="nofollow">RDFLib</a> needs C extensions to be compiled to install on ActiveState Python 2.5; as far as I can tell, there's no binary installer anywhere obvious on the web. On attempting to install with <code>python setup.py install</code>, it produces the following message:</p> <p><code>error: Python was built with Visual Studio 2003;</code><br> <code>extensions must be built with a compiler than can generate compatible binaries.</code><br> <code>Visual Studio 2003 was not found on this system. If you have Cygwin installed,</code><br> <code>you can try compiling with MingW32, by passing "-c mingw32" to setup.py.</code></p> <p>There are <a href="http://boodebr.org/main/python/build-windows-extensions" rel="nofollow">various</a> <a href="http://isegserv.itd.rl.ac.uk/blogs/alistair/" rel="nofollow">resources</a> on the web about configuring a compiler for distutils that discuss using MinGW, although I haven't got this to work yet. As an alternative I have VS2005. </p> <p>Can anyone categorically tell me whether you can use the C compiler in VS2005 to build Python extension modules for a VS2003 compiled Python (in this case ActiveState Python 2.5). If this is possible, what configuration is needed?</p>
3
2009-03-03T14:53:15Z
606,866
<p>I can't tell you categorically, but I don't believe you can. I've only run into this problem in the inverse situation (Python built with VS2005, trying to build with VS2003). Searching the web did not turn up any way to hack around it. My eventual solution was to get VC Express, since VC2005 is when Microsoft started releasing the free editions. But that's obviously not an option for you.</p> <p>I don't use ActiveState Python, but is there a newer version you could use? The source ships with project files for VS2008, and I'm pretty sure the python.org binary builds stopped using VS2003 a while ago.</p>
2
2009-03-03T15:35:15Z
[ "python", "visual-studio-2005", "visual-studio-2003", "distutils" ]
Can I use VS2005 to build extensions for a Python system built with VS2003
606,680
<p><a href="http://rdflib.net/" rel="nofollow">RDFLib</a> needs C extensions to be compiled to install on ActiveState Python 2.5; as far as I can tell, there's no binary installer anywhere obvious on the web. On attempting to install with <code>python setup.py install</code>, it produces the following message:</p> <p><code>error: Python was built with Visual Studio 2003;</code><br> <code>extensions must be built with a compiler than can generate compatible binaries.</code><br> <code>Visual Studio 2003 was not found on this system. If you have Cygwin installed,</code><br> <code>you can try compiling with MingW32, by passing "-c mingw32" to setup.py.</code></p> <p>There are <a href="http://boodebr.org/main/python/build-windows-extensions" rel="nofollow">various</a> <a href="http://isegserv.itd.rl.ac.uk/blogs/alistair/" rel="nofollow">resources</a> on the web about configuring a compiler for distutils that discuss using MinGW, although I haven't got this to work yet. As an alternative I have VS2005. </p> <p>Can anyone categorically tell me whether you can use the C compiler in VS2005 to build Python extension modules for a VS2003 compiled Python (in this case ActiveState Python 2.5). If this is possible, what configuration is needed?</p>
3
2009-03-03T14:53:15Z
694,603
<p>The main problem is C run-time library. Python 2.4/2.5 linked against msvcr71.dll and therefore all C-extensions should be linked against this dll.</p> <p>Another option is to use gcc (mingw) instead of VS2005, you can use it to compile python extensions only. There is decent installer that allows you to configure gcc as default compiler for your Python version:</p> <p><a href="http://www.develer.com/oss/GccWinBinaries" rel="nofollow">http://www.develer.com/oss/GccWinBinaries</a></p>
3
2009-03-29T13:03:25Z
[ "python", "visual-studio-2005", "visual-studio-2003", "distutils" ]
Can I use VS2005 to build extensions for a Python system built with VS2003
606,680
<p><a href="http://rdflib.net/" rel="nofollow">RDFLib</a> needs C extensions to be compiled to install on ActiveState Python 2.5; as far as I can tell, there's no binary installer anywhere obvious on the web. On attempting to install with <code>python setup.py install</code>, it produces the following message:</p> <p><code>error: Python was built with Visual Studio 2003;</code><br> <code>extensions must be built with a compiler than can generate compatible binaries.</code><br> <code>Visual Studio 2003 was not found on this system. If you have Cygwin installed,</code><br> <code>you can try compiling with MingW32, by passing "-c mingw32" to setup.py.</code></p> <p>There are <a href="http://boodebr.org/main/python/build-windows-extensions" rel="nofollow">various</a> <a href="http://isegserv.itd.rl.ac.uk/blogs/alistair/" rel="nofollow">resources</a> on the web about configuring a compiler for distutils that discuss using MinGW, although I haven't got this to work yet. As an alternative I have VS2005. </p> <p>Can anyone categorically tell me whether you can use the C compiler in VS2005 to build Python extension modules for a VS2003 compiled Python (in this case ActiveState Python 2.5). If this is possible, what configuration is needed?</p>
3
2009-03-03T14:53:15Z
9,843,738
<p>As of today Mar 2012, I can categorically say it is possible with Python2.4.4 (only one I've tested) and Visual Studio 2005 and 2008. Just installing VS10 to check that. I don't know why it works and I have problems using distutils so I have to compile manually.</p>
0
2012-03-23T17:25:15Z
[ "python", "visual-studio-2005", "visual-studio-2003", "distutils" ]
Model and Validation Confusion - Looking for advice
606,782
<p>I'm somewhat new to Python, Django, and I'd like some advice on how to layout the code I'd like to write.</p> <p>I have the model written that allows a file to be uploaded. In the models save method I'm checking if the file has a specific extension. If it has an XML extension I'm opening the file and grabbing some information from the file to save in the database. I have this model working. I've tested it in the built-in administration. It works.</p> <p>Currently when there's an error (it's not an XML file; the file can't be opened; a specific attribute doesn't exist) I'm throwing an custom "Exception" error. What I <em>would</em> like to do is some how pass these "Exception" error messages to the view (whether that's a custom view or the built-in administration view) and have an error message displayed like if the forms library was being used. Is that possible?</p> <p>I'm starting to think I'm going to have to write the validation checks again using the forms library. If that's the case, is it possible to still use the built-in administration template, but extend the form it uses to add these custom validations?</p> <p>Anything to help my confusion would be appreciated.</p> <p><hr /></p> <p><strong>UPDATE:</strong></p> <p>Here's my model so far, for those who are asking, "nzb" is the XML file field.<br /> <a href="http://dpaste.com/hold/6101/" rel="nofollow">http://dpaste.com/hold/6101/</a></p> <blockquote> <p>The admin interface will use the Form you associate with your model; your own views can also use the form.</p> </blockquote> <p>This is exactly what I'd like to do. However, I don't know how to associate my forms with my models. When ever I've created forms in the past they've always acted as their own entity. I could never get the administration views to use them while using the ModelForm class. Can you shead any light on this?</p> <p>I've read over the link you gave me and it seams to be what I've done in the past, with no luck.</p> <blockquote> <p>Getting attributes from the file, should probably be a method.</p> </blockquote> <p>Sorry, could you please elaborate on this? A method where?</p> <p><hr /></p> <p><strong>UPDATE:</strong></p> <p>It seams I've been compleatly missing this step to link a form to the administration view. <a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin</a></p> <p>This should now allow me to do the validation in a Form. However, I'm still confused about how to actually handle the validation. S.Lott says it should be a method?</p>
0
2009-03-03T15:15:16Z
606,999
<p>The Form errors are automatically part of the administrative view.</p> <p>See <a href="http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/forms/validation/#ref-forms-validation</a></p> <p>You're happiest if you validate in a Form -- that's what Forms are for. The admin interface will use the Form you associate with your model; your own views can also use the form.</p> <p>Getting attributes from the file, should probably be a separate method of the model class. The separate method of the model class can be used by the <code>save()</code> method of the model class or invoked at other times by view functions.</p> <p><hr /></p> <p>"I could never get the administration views to use them while using the ModelForm class."</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#form" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/contrib/admin/#form</a></p> <p><a href="http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/contrib/admin/#adding-custom-validation-to-the-admin</a></p> <p><hr /></p> <p>"I'm still confused about how to actually handle the validation. S.Lott says it should be a method?"</p> <p>Validation in a form is done with a <code>clean()</code> method or a <code>clean_somefield()</code> method.</p> <p>The "Adding custom validation to the admin" link (above) shows how to add the <code>clean_name</code> method to the "MyArticleAdminForm" form. </p> <p>If you're still confused, trying actually typing the code from the Django web page and see what it does.</p>
4
2009-03-03T16:04:29Z
[ "python", "django", "validation" ]