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><co...
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 =...
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><co...
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><co...
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> (becaus...
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 ...
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 essent...
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_T...
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 '' ...
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 = r...
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, *arg...
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 = ...
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 explicitl...
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 explicitl...
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...
-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 explicitl...
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, f...
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 explicitl...
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') </co...
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 explicitl...
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>...
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 explicitl...
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.he...
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 explicitl...
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 ...
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 explicitl...
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): ...
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 ...
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>...
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 ...
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.django...
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 ...
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 ...
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 ...
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...
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 ...
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 wou...
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....
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() </...
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="nofo...
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() ...
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/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>yiel...
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(): coun...
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_...
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...
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_...
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) ...
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_...
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 ...
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_...
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, ...
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_...
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...
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_...
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 = p...
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_...
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(lett...
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_...
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 ...
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...
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...
-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...
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...
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> ...
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...
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 resourc...
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 = ...
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 = ...
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 = ...
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>...
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 = ...
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 a...
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 = ...
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, ctype...
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 = ...
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, ()) 25...
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 = ...
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 =...
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...
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...
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 ...
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 ...
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 &l...
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...
-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.o...
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 pu...
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 >...
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 pu...
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['_co...
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 pu...
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 ...
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 ...
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 ...
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 t...
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 ...
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 ...
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 ...
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 ...
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: lin...
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 ...
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")'...
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 ...
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...
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 ...
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><...
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</s...
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</s...
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</s...
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) ...
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...
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...
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...
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...
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...
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-run...
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...
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...
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.<...
-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...
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...
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>Ques...
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 r...
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>Ques...
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>Ques...
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, ...
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>Ques...
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>Ques...
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...
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 sta...
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...
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 ...
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...
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 ...
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...
4
2009-03-03T16:04:29Z
[ "python", "django", "validation" ]