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
listlengths
1
5
How to convert strings numbers to integers in a list?
818,949
<p>I have a list say:</p> <pre><code>['batting average', '306', 'ERA', '1710'] </code></pre> <p>How can I convert the intended numbers without touching the strings?</p> <p>Thank you for the help.</p>
9
2009-05-04T06:09:00Z
818,956
<pre><code>changed_list = [int(f) if f.isdigit() else f for f in original_list] </code></pre>
41
2009-05-04T06:11:33Z
[ "python", "string", "integer", "numbers" ]
How to convert strings numbers to integers in a list?
818,949
<p>I have a list say:</p> <pre><code>['batting average', '306', 'ERA', '1710'] </code></pre> <p>How can I convert the intended numbers without touching the strings?</p> <p>Thank you for the help.</p>
9
2009-05-04T06:09:00Z
818,975
<p>The data looks like you would know in which positions the numbers are supposed to be. In this case it's probably better to explicitly convert the data at these positions instead of just converting anything that looks like a number:</p> <pre><code>ls = ['batting average', '306', 'ERA', '1710'] ls[1] = int(ls[1]) ls[...
5
2009-05-04T06:18:20Z
[ "python", "string", "integer", "numbers" ]
How to convert strings numbers to integers in a list?
818,949
<p>I have a list say:</p> <pre><code>['batting average', '306', 'ERA', '1710'] </code></pre> <p>How can I convert the intended numbers without touching the strings?</p> <p>Thank you for the help.</p>
9
2009-05-04T06:09:00Z
819,628
<p>Try this:</p> <pre><code>def convert( someList ): for item in someList: try: yield int(item) except ValueError: yield item newList= list( convert( oldList ) ) </code></pre>
5
2009-05-04T10:40:37Z
[ "python", "string", "integer", "numbers" ]
How to convert strings numbers to integers in a list?
818,949
<p>I have a list say:</p> <pre><code>['batting average', '306', 'ERA', '1710'] </code></pre> <p>How can I convert the intended numbers without touching the strings?</p> <p>Thank you for the help.</p>
9
2009-05-04T06:09:00Z
29,850,627
<pre><code>a= ['batting average', '306', 'ERA', '1710.5'] [f if sum([c.isalpha() for c in f]) else float(f) for f in a ] </code></pre> <p>if your list contains float, string and int (as pointed about by @d.putto in the comment)</p>
0
2015-04-24T14:50:06Z
[ "python", "string", "integer", "numbers" ]
Is there a way to correctly sort unicode strings in SQLite using Python?
819,211
<p>Is there a simple way to order rows with unicode data in SQLite?</p>
1
2009-05-04T08:05:25Z
819,248
<p>There is a library called <a href="http://icu-project.org/" rel="nofollow">ICU</a> that can do proper unicode sorting for you; there's a good description in this other question:</p> <p><a href="http://stackoverflow.com/questions/611459/how-to-sort-text-in-sqlite3-with-specified-locale">http://stackoverflow.com/ques...
2
2009-05-04T08:19:04Z
[ "python", "sqlite", "unicode" ]
Is there a way to correctly sort unicode strings in SQLite using Python?
819,211
<p>Is there a simple way to order rows with unicode data in SQLite?</p>
1
2009-05-04T08:05:25Z
819,281
<p>SQLite has a BYOS (Bring Your Own Sorter) policy. See the FAQ for <a href="http://www.sqlite.org/faq.html#q18" rel="nofollow">more details</a>. They chose not to include (by default) any Unicode-aware sorting algorithm, to keep the SQLite library svelte and easy to statically link in. </p> <p>However, you can <a...
4
2009-05-04T08:34:17Z
[ "python", "sqlite", "unicode" ]
Python, who is calling my python module
819,217
<p>I have one Python module that can be called by a CGI script (passing it information from a form) or from the command line (passing it options and arguments from the command line). Is there a way to establish if the module has been called from the CGI script or from the command line ??</p>
3
2009-05-04T08:08:10Z
819,240
<p>This will do it:</p> <pre><code>import os if os.environ.has_key('REQUEST_METHOD'): # You're being run as a CGI script. else: # You're being run from the command line. </code></pre>
9
2009-05-04T08:15:38Z
[ "python", "cgi" ]
Python, who is calling my python module
819,217
<p>I have one Python module that can be called by a CGI script (passing it information from a form) or from the command line (passing it options and arguments from the command line). Is there a way to establish if the module has been called from the CGI script or from the command line ??</p>
3
2009-05-04T08:08:10Z
819,618
<p>This is a really bad design idea. Your script should be designed to work independently of how it's called. The calling programs should provide a uniform environment.</p> <p>You'll be happiest if you design your scripts to work in exactly one consistent way. Build things like this.</p> <ul> <li><p>myscript.py - ...
6
2009-05-04T10:37:06Z
[ "python", "cgi" ]
Working with a QString encoding
819,310
<p>Is there a Python library which can detect (and perhaps decode) encoding of the string?</p> <p>I found <a href="http://pypi.python.org/pypi/chardet" rel="nofollow"><code>chardet</code></a> but it gives me an error, using:</p> <pre><code>chardet.detect(self.ui.TextFrom.toPlainText()) got: = chardet.detect(self.ui.T...
1
2009-05-04T08:47:22Z
819,338
<p>I guess this is another option.</p> <p><a href="http://cthedot.de/encutils/" rel="nofollow">http://cthedot.de/encutils/</a></p> <blockquote> <p>A collection of helper functions to detect encodings of text files (like HTML, XHTML, XML, CSS, etc.) retrieved via HTTP, file or string.</p> </blockquote>
2
2009-05-04T08:55:36Z
[ "python", "encoding" ]
Working with a QString encoding
819,310
<p>Is there a Python library which can detect (and perhaps decode) encoding of the string?</p> <p>I found <a href="http://pypi.python.org/pypi/chardet" rel="nofollow"><code>chardet</code></a> but it gives me an error, using:</p> <pre><code>chardet.detect(self.ui.TextFrom.toPlainText()) got: = chardet.detect(self.ui.T...
1
2009-05-04T08:47:22Z
819,582
<p>You need to convert your <code>QString</code> to a Python string before passing it to <code>chardet</code>. Change this:</p> <pre><code>chardet.detect(self.ui.TextFrom.toPlainText()) </code></pre> <p>to this:</p> <pre><code>chardet.detect(str(self.ui.TextFrom.toPlainText())) </code></pre>
7
2009-05-04T10:18:47Z
[ "python", "encoding" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
819,371
<p>I don't know of anything in the standard library, but <a href="http://www.icir.org/robin/pysubnettree/" rel="nofollow">PySubnetTree</a> is a Python library that will do subnet matching.</p>
1
2009-05-04T09:03:32Z
[ "python", "networking", "ip-address" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
819,420
<p><a href="http://code.activestate.com/recipes/66517/">This article</a> shows you can do it with <a href="http://docs.python.org/library/socket.html"><code>socket</code></a> and <a href="http://docs.python.org/library/struct.html"><code>struct</code></a> modules without too much extra effort. I added a little to the ...
23
2009-05-04T09:21:29Z
[ "python", "networking", "ip-address" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
820,124
<p>I like to use <a href="http://pypi.python.org/pypi/netaddr">netaddr</a> for that:</p> <pre><code>from netaddr import CIDR, IP if IP("192.168.0.1") in CIDR("192.168.0.0/24"): print "Yay!" </code></pre> <p>As arno_v pointed out in the comments, new version of netaddr does it like this:</p> <pre><code>from neta...
83
2009-05-04T13:35:13Z
[ "python", "networking", "ip-address" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
1,004,527
<p>Using <a href="http://code.google.com/p/ipaddress-py/">ipaddress</a> (<a href="http://docs.python.org/3.3/library/ipaddress.html">in the stdlib since 3.3</a>, <a href="https://pypi.python.org/pypi/ipaddress">at PyPi for 2.6/2.7</a>):</p> <pre><code>&gt;&gt;&gt; import ipaddress &gt;&gt;&gt; ipaddress.ip_address('19...
51
2009-06-17T00:15:35Z
[ "python", "networking", "ip-address" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
3,188,535
<p>Thank you for your script!<br> I have work quite a long on it to make everything working... So I'm sharing it here</p> <ul> <li>Using netaddr Class is 10 times slower than using binary conversion, so if you'd like to use it on a big list of IP, you should consider not using netaddr class</li> <li><p>makeMask functi...
1
2010-07-06T17:10:58Z
[ "python", "networking", "ip-address" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
4,464,961
<p>This code is working for me on Linux x86. I haven't really given any thought to endianess issues, but I have tested it against the "ipaddr" module using over 200K IP addresses tested against 8 different network strings, and the results of ipaddr are the same as this code.</p> <pre><code>def addressInNetwork(ip, ne...
7
2010-12-16T20:16:55Z
[ "python", "networking", "ip-address" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
5,467,511
<p>Marc's code is nearly correct. A complete version of the code is -</p> <pre><code>def addressInNetwork3(ip,net): '''This function allows you to check if on IP belogs to a Network''' ipaddr = struct.unpack('=L',socket.inet_aton(ip))[0] netaddr,bits = net.split('/') netmask = struct.unpack('=L',socket...
4
2011-03-29T03:13:52Z
[ "python", "networking", "ip-address" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
7,323,817
<h1>from netaddr import all_matching_cidrs</h1> <pre><code>&gt;&gt;&gt; from netaddr import all_matching_cidrs &gt;&gt;&gt; all_matching_cidrs("212.11.70.34", ["192.168.0.0/24","212.11.64.0/19"] ) [IPNetwork('212.11.64.0/19')] </code></pre> <p>Here is the usage for this method:</p> <pre><code>&gt;&gt;&gt; help(all_m...
1
2011-09-06T17:33:34Z
[ "python", "networking", "ip-address" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
10,053,031
<pre> #This works properly without the weird byte by byte handling def addressInNetwork(ip,net): '''Is an address in a network''' # Convert addresses to host order, so shifts actually make sense ip = struct.unpack('>L',socket.inet_aton(ip))[0] netaddr,bits = net.split('/') netaddr = struct.unpack('>...
2
2012-04-07T08:36:07Z
[ "python", "networking", "ip-address" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
10,534,496
<p>I tried Dave Webb's solution but hit some problems:</p> <p>Most fundamentally - a match should be checked by ANDing the IP address with the mask, then checking the result matched the Network address exactly. Not ANDing the IP address with the Network address as was done.</p> <p>I also noticed that just ignoring th...
6
2012-05-10T12:57:30Z
[ "python", "networking", "ip-address" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
14,280,401
<p>Relating to all of the above, I think socket.inet_aton() returns bytes in network order, so the correct way to unpack them is probably</p> <pre><code>struct.unpack('!L', ... ) </code></pre>
1
2013-01-11T14:39:56Z
[ "python", "networking", "ip-address" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
18,006,400
<p>Here is a class I wrote for longest prefix matching:</p> <pre><code>#!/usr/bin/env python class Node: def __init__(self): self.left_child = None self.right_child = None self.data = "-" def setData(self, data): self.data = data def setLeft(self, pointer): self.left_child = pointer def setRight(self, po...
0
2013-08-01T23:34:27Z
[ "python", "networking", "ip-address" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
19,015,668
<p>Not in the Standard library for 2.5, but ipaddr makes this very easy. I believe it is in 3.3 under the name ipaddress. </p> <pre><code>import ipaddr a = ipaddr.IPAddress('192.168.0.1') n = ipaddr.IPNetwork('192.168.0.0/24') #This will return True n.Contains(a) </code></pre>
2
2013-09-25T21:42:39Z
[ "python", "networking", "ip-address" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
21,527,753
<p><strong>previous solution have a bug in ip &amp; net == net. Correct ip lookup is ip &amp; netmask = net</strong></p> <p>bugfixed code:</p> <pre><code>import socket import struct def makeMask(n): "return a mask of n bits as a long integer" return (2L&lt;&lt;n-1) - 1 def dottedQuadToNum(ip): "convert ...
1
2014-02-03T12:43:04Z
[ "python", "networking", "ip-address" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
23,230,273
<p>The choosen answer has a bug.</p> <p>Following is the correct code:</p> <pre><code>def addressInNetwork(ip, net_n_bits): ipaddr = struct.unpack('&lt;L', socket.inet_aton(ip))[0] net, bits = net_n_bits.split('/') netaddr = struct.unpack('&lt;L', socket.inet_aton(net))[0] netmask = ((1L &lt;&lt; int(bits...
1
2014-04-22T21:11:31Z
[ "python", "networking", "ip-address" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
29,950,808
<p>I'm not a fan of using modules when they are not needed. This job only requires simple math, so here is my simple function to do the job:</p> <pre><code>def ipToInt(ip): o = map(int, ip.split('.')) res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3] return res def isIpInSubnet(ip, ipNetwork...
5
2015-04-29T17:41:51Z
[ "python", "networking", "ip-address" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
30,676,234
<p>The accepted answer doesn't work ... which is making me angry. Mask is backwards and doesn't work with any bits that are not a simple 8 bit block (eg /24). I adapted the answer, and it works nicely.</p> <pre><code> import socket,struct def addressInNetwork(ip, net_n_bits): ipaddr = struct.unpack('!L...
1
2015-06-05T21:38:55Z
[ "python", "networking", "ip-address" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
32,127,904
<p>From various sources above, and from my own research, this is how I got subnet and address calculation working. These pieces are enough to solve the question and other related questions.</p> <pre><code>class iptools: @staticmethod def dottedQuadToNum(ip): "convert decimal dotted quad string to long...
0
2015-08-20T20:35:25Z
[ "python", "networking", "ip-address" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
33,264,320
<p>There is an API that's called SubnetTree available in python that do this job very well. This is a simple example : </p> <pre><code>import SubnetTree t = SubnetTree.SubnetTree() t.insert("10.0.1.3/32") print("10.0.1.3" in t) </code></pre> <p><a href="https://www.bro.org/sphinx/components/pysubnettree/README.html"...
1
2015-10-21T16:14:38Z
[ "python", "networking", "ip-address" ]
How can I check if an ip is in a network in python
819,355
<p>Given an ip address (say 192.168.0.1), how do I check if it's in a network (say 192.168.0.0/24) in Python?</p> <p>Are there general tools in Python for ip address manipulation? Stuff like host lookups, ip adddress to int, network address with netmask to int and so on? Hopefully in the standard Python library for 2....
55
2009-05-04T08:59:20Z
35,459,972
<pre><code>import socket,struct def addressInNetwork(ip,net): "Is an address in a network" ipaddr = struct.unpack('!L',socket.inet_aton(ip))[0] netaddr,bits = net.split('/') netaddr = struct.unpack('!L',socket.inet_aton(netaddr))[0] netmask = ((1&lt;&lt;(32-int(bits))) - 1)^0xffffffff return ipa...
0
2016-02-17T14:50:57Z
[ "python", "networking", "ip-address" ]
Best way for Parsing ANSI and UTF-16LE files using Python 2/3?
819,396
<p>I have a collection of files encoded in ANSI or UTF-16LE. I would like python to open the files using the correct encoding. The problem is that the ANSI files do not raise any sort of exception when encoded using UTF-16le and vice versa.</p> <p>Is there a straightforward way to open up the files using the correct f...
0
2009-05-04T09:12:42Z
819,432
<p>Use the <a href="http://chardet.feedparser.org/" rel="nofollow">chardet</a> library to detect the encoding.</p>
4
2009-05-04T09:26:14Z
[ "python", "encoding", "ansi", "utf-16" ]
Best way for Parsing ANSI and UTF-16LE files using Python 2/3?
819,396
<p>I have a collection of files encoded in ANSI or UTF-16LE. I would like python to open the files using the correct encoding. The problem is that the ANSI files do not raise any sort of exception when encoded using UTF-16le and vice versa.</p> <p>Is there a straightforward way to open up the files using the correct f...
0
2009-05-04T09:12:42Z
819,439
<p>You can check for the <a href="http://en.wikipedia.org/wiki/Byte-order%5Fmark" rel="nofollow" title="BOM">BOM</a> at the beginning of the file to check whether it's UTF.</p> <p>Then <a href="http://docs.python.org/library/stdtypes.html#str.decode" rel="nofollow">unicode.decode</a> accordingly (using one of the <a h...
0
2009-05-04T09:27:06Z
[ "python", "encoding", "ansi", "utf-16" ]
Best way for Parsing ANSI and UTF-16LE files using Python 2/3?
819,396
<p>I have a collection of files encoded in ANSI or UTF-16LE. I would like python to open the files using the correct encoding. The problem is that the ANSI files do not raise any sort of exception when encoded using UTF-16le and vice versa.</p> <p>Is there a straightforward way to open up the files using the correct f...
0
2009-05-04T09:12:42Z
824,579
<p>What's in the files? If it's plain text in a Latin-based alphabet, almost every other byte the UTF-16LE files will be zero. In the windows-1252 files, on the other hand, I wouldn't expect to see any zeros at all. For example, here's <code>“Hello”</code> in windows-1252:</p> <pre><code>93 48 65 6C 6C 6F 94 </...
0
2009-05-05T12:09:00Z
[ "python", "encoding", "ansi", "utf-16" ]
How do I handle exceptions when using threading and Queue?
820,111
<p>If I have a program that uses threading and Queue, how do I get exceptions to stop execution? Here is an example program, which is not possible to stop with ctrl-c (basically ripped from the python docs).</p> <pre><code>from threading import Thread from Queue import Queue from time import sleep def do_work(item): ...
8
2009-05-04T13:31:47Z
820,121
<p>The simplest way is to start all the worker threads as daemon threads, then just have your main loop be</p> <pre><code>while True: sleep(1) </code></pre> <p>Hitting Ctrl+C will throw an exception in your main thread, and all of the daemon threads will exit when the interpreter exits. This assumes you don't wa...
4
2009-05-04T13:34:45Z
[ "python", "multithreading", "exception" ]
How do I handle exceptions when using threading and Queue?
820,111
<p>If I have a program that uses threading and Queue, how do I get exceptions to stop execution? Here is an example program, which is not possible to stop with ctrl-c (basically ripped from the python docs).</p> <pre><code>from threading import Thread from Queue import Queue from time import sleep def do_work(item): ...
8
2009-05-04T13:31:47Z
820,247
<p>A (possibly) offtopic note:</p> <pre><code>(...) for item in range(1, 10000): q.put(item) (...) </code></pre> <p>You could use xrange instead of range here (unless You use python3000). You will save some cpu and memory by doing so. More on xrange can be found <a href="http://docs.python.org/library/functions.h...
1
2009-05-04T14:03:19Z
[ "python", "multithreading", "exception" ]
Render PyCairo onto PyOpenGL surface?
820,221
<p>I've recently started playing with pycairo - is it easy enough to render this to an pyopengl surface (e.g. on the side of a cube?)... my opengl is really non-existant so I'm not sure the best way to go about this.</p>
3
2009-05-04T13:57:53Z
927,479
<p>This procedure might work:</p> <ol> <li>Do your drawing in pycairo like normal.</li> <li>Export the image to a file (or get a handle to it in memory).</li> <li>Load the image into opengl texture memory.</li> <li>Draw your cube in opengl using the texture.</li> </ol> <p>Steps 1&amp;2 are in cairo, which I'm not fam...
0
2009-05-29T18:31:56Z
[ "python", "opengl", "cairo" ]
How can I make a change to a module without restarting python interpreter?
820,431
<p>I am testing code in the python interpreter and editing in a separate window. I currently need to restart python whenever I make a change to the module I am testing.</p> <p>Is there an easier way to do this?</p> <p>Thanks,</p> <p>Charlie</p>
1
2009-05-04T14:49:29Z
820,446
<p>The built-in function <a href="http://docs.python.org/library/functions.html#reload" rel="nofollow"><code>reload</code></a> is what you're looking for.</p>
10
2009-05-04T14:52:25Z
[ "python" ]
How can I make a change to a module without restarting python interpreter?
820,431
<p>I am testing code in the python interpreter and editing in a separate window. I currently need to restart python whenever I make a change to the module I am testing.</p> <p>Is there an easier way to do this?</p> <p>Thanks,</p> <p>Charlie</p>
1
2009-05-04T14:49:29Z
820,469
<p>It sounds like you want to reload the module, for which there is a <a href="http://docs.python.org/library/functions.html#reload" rel="nofollow">built-in function reload(module)</a>. That said, when I looked it up just now (to make sure I had my reference right, Google returned a <a href="http://pyunit.sourceforge....
3
2009-05-04T14:56:22Z
[ "python" ]
How can I make a change to a module without restarting python interpreter?
820,431
<p>I am testing code in the python interpreter and editing in a separate window. I currently need to restart python whenever I make a change to the module I am testing.</p> <p>Is there an easier way to do this?</p> <p>Thanks,</p> <p>Charlie</p>
1
2009-05-04T14:49:29Z
824,001
<p>Have a look at IPython <a href="http://ipython.scipy.org" rel="nofollow">http://ipython.scipy.org</a>. It has various features that make working with Python code interactively easier.</p> <p>Some <a href="http://ipython.scipy.org/screenshots/index.html" rel="nofollow">screenshots</a> and <a href="http://ipython.sci...
1
2009-05-05T09:08:35Z
[ "python" ]
rules for slugs and unicode
820,496
<p>After researching a bit how the different way people slugify titles, I've noticed that it's often missing how to deal with non english titles.</p> <p>url encoding is very restrictive. See <a href="http://www.blooberry.com/indexdot/html/topics/urlencoding.htm" rel="nofollow">http://www.blooberry.com/indexdot/html/to...
10
2009-05-04T15:04:38Z
822,848
<p>If all else fails, you could use a conversion table, but there might be a better performing solution available. What server side language are you using?</p>
1
2009-05-05T01:01:42Z
[ "python", "google-app-engine", "url", "unicode", "friendly-url" ]
rules for slugs and unicode
820,496
<p>After researching a bit how the different way people slugify titles, I've noticed that it's often missing how to deal with non english titles.</p> <p>url encoding is very restrictive. See <a href="http://www.blooberry.com/indexdot/html/topics/urlencoding.htm" rel="nofollow">http://www.blooberry.com/indexdot/html/to...
10
2009-05-04T15:04:38Z
822,917
<p>In general this is going to depend on the language you expect to get. If your primary userbase is Japanese, dropping everything but ISO-8859-1 characters is unlikely to go over well.</p> <p>That said, one option might be to use transliteration mode, if your character set conversion library supports it. For example,...
2
2009-05-05T01:27:51Z
[ "python", "google-app-engine", "url", "unicode", "friendly-url" ]
rules for slugs and unicode
820,496
<p>After researching a bit how the different way people slugify titles, I've noticed that it's often missing how to deal with non english titles.</p> <p>url encoding is very restrictive. See <a href="http://www.blooberry.com/indexdot/html/topics/urlencoding.htm" rel="nofollow">http://www.blooberry.com/indexdot/html/to...
10
2009-05-04T15:04:38Z
824,170
<p>I simply use utf-8 for URL paths. As long as the domain is non-IDN FF3, IE works fine with this. Google reads and displays them correctly. The <a href="http://www.ietf.org/rfc/rfc3987" rel="nofollow">IRI RFC</a> allows Unicode. Just make sure you parse the incoming urls correctly.</p>
4
2009-05-05T09:58:39Z
[ "python", "google-app-engine", "url", "unicode", "friendly-url" ]
rules for slugs and unicode
820,496
<p>After researching a bit how the different way people slugify titles, I've noticed that it's often missing how to deal with non english titles.</p> <p>url encoding is very restrictive. See <a href="http://www.blooberry.com/indexdot/html/topics/urlencoding.htm" rel="nofollow">http://www.blooberry.com/indexdot/html/to...
10
2009-05-04T15:04:38Z
824,829
<p>Nearly-complete transliteration table (for latin, greek and cyrillic character sets) can be found in <a href="http://trac.django-fr.org/browser/site/trunk/project/links/slughifi.py?rev=47">slughifi library</a>. It is geared towards Django, but can be easily modified to fit general needs (I use it with Werkzeug-based...
8
2009-05-05T13:21:26Z
[ "python", "google-app-engine", "url", "unicode", "friendly-url" ]
python, __slots__, and "attribute is read-only"
820,671
<p>I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows:</p> <pre><code>class MyClass( object ) : m = None # my attribute __slots__ = ( "m" ) # ensure that object has no _m etc a = MyClass() # creat...
15
2009-05-04T15:50:36Z
820,710
<p><code>__slots__</code> works with instance variables, whereas what you have there is a class variable. This is how you should be doing it:</p> <pre><code>class MyClass( object ) : __slots__ = ( "m", ) def __init__(self): self.m = None a = MyClass() a.m = "?" # No error </code></pre>
7
2009-05-04T16:02:54Z
[ "python", "exception", "descriptor", "readonlyattribute" ]
python, __slots__, and "attribute is read-only"
820,671
<p>I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows:</p> <pre><code>class MyClass( object ) : m = None # my attribute __slots__ = ( "m" ) # ensure that object has no _m etc a = MyClass() # creat...
15
2009-05-04T15:50:36Z
820,730
<p>When you declare instance variables using <code>__slots__</code>, Python creates a <a href="http://www.python.org/doc/2.5.1/ref/descriptors.html#descriptors">descriptor object</a> as a class variable with the same name. In your case, this descriptor is overwritten by the class variable <code>m</code> that you are de...
34
2009-05-04T16:07:51Z
[ "python", "exception", "descriptor", "readonlyattribute" ]
python, __slots__, and "attribute is read-only"
820,671
<p>I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows:</p> <pre><code>class MyClass( object ) : m = None # my attribute __slots__ = ( "m" ) # ensure that object has no _m etc a = MyClass() # creat...
15
2009-05-04T15:50:36Z
820,968
<p>Consider this.</p> <pre><code>class SuperSafe( object ): allowed= ( "this", "that" ) def __init__( self ): self.this= None self.that= None def __setattr__( self, attr, value ): if attr not in self.allowed: raise Exception( "No such attribute: %s" % (attr,) ) s...
4
2009-05-04T17:06:55Z
[ "python", "exception", "descriptor", "readonlyattribute" ]
python, __slots__, and "attribute is read-only"
820,671
<p>I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows:</p> <pre><code>class MyClass( object ) : m = None # my attribute __slots__ = ( "m" ) # ensure that object has no _m etc a = MyClass() # creat...
15
2009-05-04T15:50:36Z
821,773
<p>You are completely misusing <code>__slots__</code>. It prevents the creation of <code>__dict__</code> for the instances. This only makes sense if you run into memory problems with many small objects, because getting rid of <code>__dict__</code> can reduce the footprint. This is a hardcore optimization that is not ne...
13
2009-05-04T20:05:24Z
[ "python", "exception", "descriptor", "readonlyattribute" ]
python, __slots__, and "attribute is read-only"
820,671
<p>I want to create an object in python that has a few attributes and I want to protect myself from accidentally using the wrong attribute name. The code is as follows:</p> <pre><code>class MyClass( object ) : m = None # my attribute __slots__ = ( "m" ) # ensure that object has no _m etc a = MyClass() # creat...
15
2009-05-04T15:50:36Z
26,469,796
<pre><code>class MyClass( object ) : m = None # my attribute </code></pre> <p>The <code>m</code> here is the class attributes, rather than the instance attribute. You need to connect it with your instance by self in <code>__init__</code>.</p>
0
2014-10-20T15:51:31Z
[ "python", "exception", "descriptor", "readonlyattribute" ]
Why is Maya 2009 TreeView control giving a syntax error on drag?
820,697
<p>I'm using the TreeView control in Maya 2009 but I'm getting a syntax error on drag and drop. My code is as follows (simplified for brevity):</p> <pre><code> class View(event.Dispatcher): def __init__(self): self.window = cmds.window() tree_view = cmds.treeView( numberOfButtons=1, allowRepa...
1
2009-05-04T15:59:26Z
821,857
<p>See <a href="http://download.autodesk.com/us/maya/2009help/CommandsPython/treeView.html" rel="nofollow">http://download.autodesk.com/us/maya/2009help/CommandsPython/treeView.html</a>: dragAndDropCommand is a STRING -- you're passing a bound method, Maya's using its repr. I'm not sure, but I suspect that string shoul...
1
2009-05-04T20:21:38Z
[ "python", "treeview", "syntax-error", "maya" ]
Why is Maya 2009 TreeView control giving a syntax error on drag?
820,697
<p>I'm using the TreeView control in Maya 2009 but I'm getting a syntax error on drag and drop. My code is as follows (simplified for brevity):</p> <pre><code> class View(event.Dispatcher): def __init__(self): self.window = cmds.window() tree_view = cmds.treeView( numberOfButtons=1, allowRepa...
1
2009-05-04T15:59:26Z
1,704,535
<p>As of Maya 2010 the treeView widget appears to still require a string name of a mel procedure to be used for some of its callbacks, but not for others. For example, the dragCallback and dropCallback do work as expected, but the selectCommand and others don't. Many other widgets do accept a python function for thei...
0
2009-11-09T22:57:03Z
[ "python", "treeview", "syntax-error", "maya" ]
How to bestow string-ness on my class?
820,742
<p>I want a string with one additional attribute, let's say whether to print it in red or green.</p> <p>Subclassing(str) does not work, as it is immutable. I see the value, but it can be annoying.</p> <p>Can multiple inheritence help? I never used that.</p> <p>Inheriting only object and using self.value=str means I ...
6
2009-05-04T16:11:14Z
820,750
<p>Perhaps a custom class that <strong>contains</strong> a string would be a better approach. Do you really need to pass all string methods through to the underlying string? Why not expose the string via a property and allow consumers of the class to do whatever they wish to it?</p>
2
2009-05-04T16:13:22Z
[ "python", "string", "multiple-inheritance", "immutability" ]
How to bestow string-ness on my class?
820,742
<p>I want a string with one additional attribute, let's say whether to print it in red or green.</p> <p>Subclassing(str) does not work, as it is immutable. I see the value, but it can be annoying.</p> <p>Can multiple inheritence help? I never used that.</p> <p>Inheriting only object and using self.value=str means I ...
6
2009-05-04T16:11:14Z
820,767
<p>You need all of string's methods, so extend string and add your extra details. So what if string is immutable? Just make your class immutable, too. Then you're creating new objects anyway so you won't accidentally mess up thinking that it's a mutable object.</p> <p>Or, if Python has one, extend a mutable variant of...
0
2009-05-04T16:17:39Z
[ "python", "string", "multiple-inheritance", "immutability" ]
How to bestow string-ness on my class?
820,742
<p>I want a string with one additional attribute, let's say whether to print it in red or green.</p> <p>Subclassing(str) does not work, as it is immutable. I see the value, but it can be annoying.</p> <p>Can multiple inheritence help? I never used that.</p> <p>Inheriting only object and using self.value=str means I ...
6
2009-05-04T16:11:14Z
820,849
<p>str can be inherited unless you are using a very old python version, for example :</p> <pre><code>&gt;&gt;&gt; class A(str): ... def __new__(cls, color, *args, **kwargs): ... newobj = str.__new__(cls, *args, **kwargs) ... newobj.color = color ... return newobj &gt;&gt;&gt; a = A("#fff", "hor...
5
2009-05-04T16:38:51Z
[ "python", "string", "multiple-inheritance", "immutability" ]
How to bestow string-ness on my class?
820,742
<p>I want a string with one additional attribute, let's say whether to print it in red or green.</p> <p>Subclassing(str) does not work, as it is immutable. I see the value, but it can be annoying.</p> <p>Can multiple inheritence help? I never used that.</p> <p>Inheriting only object and using self.value=str means I ...
6
2009-05-04T16:11:14Z
820,852
<pre><code>import UserString class mystr(UserString.MutableString): ... </code></pre> <p>It's generally best to use immutable strings &amp; subclasses thereof, but if you need a mutable one this is the simplest way to get it.</p>
2
2009-05-04T16:39:07Z
[ "python", "string", "multiple-inheritance", "immutability" ]
How to bestow string-ness on my class?
820,742
<p>I want a string with one additional attribute, let's say whether to print it in red or green.</p> <p>Subclassing(str) does not work, as it is immutable. I see the value, but it can be annoying.</p> <p>Can multiple inheritence help? I never used that.</p> <p>Inheriting only object and using self.value=str means I ...
6
2009-05-04T16:11:14Z
11,801,438
<p>You could try using the <code>stringlike</code> module in <a href="http://pypi.python.org/pypi/stringlike" rel="nofollow">PyPI</a>. Here's <a href="http://developer.covenanteyes.com/stringlike-in-python/" rel="nofollow">an example</a>.</p>
0
2012-08-03T18:38:05Z
[ "python", "string", "multiple-inheritance", "immutability" ]
SyntaxError in finally (Django)
820,778
<p>I'm using Django, and I have the following error:</p> <blockquote> <p>Exception Type: SyntaxError Exception Value: invalid syntax (views.py, <strong>line 115</strong>)</p> </blockquote> <p>My viws.py code looks like this:</p> <pre><code>def myview(request): try: [...] except MyExceptionClass, e: [...] fi...
4
2009-05-04T16:20:23Z
820,792
<p>In Python 3, should be:</p> <pre><code>except MyExceptionClass as e: [....] </code></pre> <p>In your case, this is not the case.</p>
0
2009-05-04T16:24:39Z
[ "python", "django" ]
SyntaxError in finally (Django)
820,778
<p>I'm using Django, and I have the following error:</p> <blockquote> <p>Exception Type: SyntaxError Exception Value: invalid syntax (views.py, <strong>line 115</strong>)</p> </blockquote> <p>My viws.py code looks like this:</p> <pre><code>def myview(request): try: [...] except MyExceptionClass, e: [...] fi...
4
2009-05-04T16:20:23Z
820,799
<p>What version of python are you using? Prior to 2.5 you can't have both an except clause and a finally clause in the same try block.</p> <p>You can work around this by nesting try blocks.</p> <pre><code>def myview(request): try: try: [...] except MyExceptionClass, e: [......
13
2009-05-04T16:25:56Z
[ "python", "django" ]
SyntaxError in finally (Django)
820,778
<p>I'm using Django, and I have the following error:</p> <blockquote> <p>Exception Type: SyntaxError Exception Value: invalid syntax (views.py, <strong>line 115</strong>)</p> </blockquote> <p>My viws.py code looks like this:</p> <pre><code>def myview(request): try: [...] except MyExceptionClass, e: [...] fi...
4
2009-05-04T16:20:23Z
820,813
<p>Nadia is right, so if you're stuck with Python 2.4 or earlier, use <em>two</em> try blocks:</p> <pre><code>try: try: [...] except MyExceptionClass, e: [...] finally: render_to_response(...) </code></pre>
2
2009-05-04T16:31:20Z
[ "python", "django" ]
Where can I find some "hello world"-simple Beautiful Soup examples?
821,173
<p>I'd like to do a very simple replacement using Beautiful Soup. Let's say I want to visit all A tags in a page and append "?foo" to their href. Can someone post or link to an example of how to do something simple like that?</p>
7
2009-05-04T17:53:51Z
821,238
<pre><code>from BeautifulSoup import BeautifulSoup soup = BeautifulSoup(''' &lt;html&gt; &lt;head&gt;&lt;title&gt;Testing&lt;/title&gt;&lt;/head&gt; &lt;body&gt; &lt;a href="http://foo.com/"&gt;foo&lt;/a&gt; &lt;a href="http://bar.com/bar"&gt;Bar&lt;/a&gt; &lt;/body&gt; &lt;/html&gt;''') for link i...
14
2009-05-04T18:09:56Z
[ "python", "beautifulsoup" ]
Where can I find some "hello world"-simple Beautiful Soup examples?
821,173
<p>I'd like to do a very simple replacement using Beautiful Soup. Let's say I want to visit all A tags in a page and append "?foo" to their href. Can someone post or link to an example of how to do something simple like that?</p>
7
2009-05-04T17:53:51Z
2,264,956
<p>my example:</p> <pre><code>HEADERS = {"User-Agent" : "Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5", "Accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", "Accept-Language" : "ru,en-us;q=0.7,en;q=0.3", "Accept-Charset" : "windows-...
1
2010-02-15T09:35:59Z
[ "python", "beautifulsoup" ]
SQL TOP 1 analog for lists in Python
821,416
<p>Here is an example of my input csv file:</p> <pre><code>... 0.7,0.5,0.35,14.4,0.521838919218 0.7,0.5,0.35,14.4,0.521893472678 0.7,0.5,0.35,14.4,0.521948026139 0.7,0.5,0.35,14.4,0.522002579599 ... </code></pre> <p>I need to select the top row where the last float > random number. My current implementation is ver...
1
2009-05-04T18:59:51Z
821,464
<p>The fastest approach is to use bisect (assuming the float list is ordered). You can do it like this:</p> <pre><code>import bisect float_list = [line[-1] for line in foo] index = bisect.bisect(float_list, random.random()) if index &lt; len(float_list) result = foo[index] else: result = None # None exists </...
3
2009-05-04T19:07:34Z
[ "python", "tsql" ]
SQL TOP 1 analog for lists in Python
821,416
<p>Here is an example of my input csv file:</p> <pre><code>... 0.7,0.5,0.35,14.4,0.521838919218 0.7,0.5,0.35,14.4,0.521893472678 0.7,0.5,0.35,14.4,0.521948026139 0.7,0.5,0.35,14.4,0.522002579599 ... </code></pre> <p>I need to select the top row where the last float > random number. My current implementation is ver...
1
2009-05-04T18:59:51Z
821,529
<p>You might actually be able to use the appropriate SQL command if you <a href="http://www.sqlite.org/cvstrac/wiki?p=ImportingFiles" rel="nofollow">import the CSV file into SQLite</a>. Python has a <a href="http://docs.python.org/library/sqlite3.html" rel="nofollow">built-in sqlite library</a> you can use to query th...
1
2009-05-04T19:19:46Z
[ "python", "tsql" ]
what python feature is illustrated in this code?
821,855
<p>I read Storm ORM's tutorial at <a href="https://storm.canonical.com/Tutorial" rel="nofollow">https://storm.canonical.com/Tutorial</a>, and I stumbled upon the following piece of code :</p> <pre><code> store.find(Person, Person.name == u"Mary Margaret").set(name=u"Mary Maggie") </code></pre> <p>I'm not sure that th...
5
2009-05-04T20:21:03Z
821,900
<p>since I'm a Java programmer... I'm guessing... it is operator overloading? Person.name == is an operator overloaded that instead do comparison... it produces a SQL query</p> <p>my 0.02$</p>
0
2009-05-04T20:28:12Z
[ "python", "language-features" ]
what python feature is illustrated in this code?
821,855
<p>I read Storm ORM's tutorial at <a href="https://storm.canonical.com/Tutorial" rel="nofollow">https://storm.canonical.com/Tutorial</a>, and I stumbled upon the following piece of code :</p> <pre><code> store.find(Person, Person.name == u"Mary Margaret").set(name=u"Mary Maggie") </code></pre> <p>I'm not sure that th...
5
2009-05-04T20:21:03Z
821,912
<p>It does not look like a python lambda to me. I did not read the code for Storm but Miles is probably right in that it uses a lazy evaluation schema.</p> <p>To learn more about python lambda functions read the excellent <a href="http://www.diveintopython.org/power%5Fof%5Fintrospection/lambda%5Ffunctions.html" rel="n...
1
2009-05-04T20:31:02Z
[ "python", "language-features" ]
what python feature is illustrated in this code?
821,855
<p>I read Storm ORM's tutorial at <a href="https://storm.canonical.com/Tutorial" rel="nofollow">https://storm.canonical.com/Tutorial</a>, and I stumbled upon the following piece of code :</p> <pre><code> store.find(Person, Person.name == u"Mary Margaret").set(name=u"Mary Maggie") </code></pre> <p>I'm not sure that th...
5
2009-05-04T20:21:03Z
821,926
<p><code>Person.name</code> has a overloaded <code>__eq__</code> method that returns not a boolean value but an object that stores both sides of the expression; that object can be examined by the <code>find()</code> method to obtain the attribute and value that it will use for filtering. I would describe this as a typ...
22
2009-05-04T20:33:48Z
[ "python", "language-features" ]
what python feature is illustrated in this code?
821,855
<p>I read Storm ORM's tutorial at <a href="https://storm.canonical.com/Tutorial" rel="nofollow">https://storm.canonical.com/Tutorial</a>, and I stumbled upon the following piece of code :</p> <pre><code> store.find(Person, Person.name == u"Mary Margaret").set(name=u"Mary Maggie") </code></pre> <p>I'm not sure that th...
5
2009-05-04T20:21:03Z
821,941
<p>The magic is in the Person.name property, which results in a type that overloads <code>__eq__</code> (&amp;c) to return non-bools. Storm's sources are online for you to browse (and CAUTIOUSLY imitate;-) at <a href="http://bazaar.launchpad.net/~storm/storm/trunk/files/head%3A/storm/" rel="nofollow">http://bazaar.lau...
8
2009-05-04T20:36:00Z
[ "python", "language-features" ]
what python feature is illustrated in this code?
821,855
<p>I read Storm ORM's tutorial at <a href="https://storm.canonical.com/Tutorial" rel="nofollow">https://storm.canonical.com/Tutorial</a>, and I stumbled upon the following piece of code :</p> <pre><code> store.find(Person, Person.name == u"Mary Margaret").set(name=u"Mary Maggie") </code></pre> <p>I'm not sure that th...
5
2009-05-04T20:21:03Z
822,115
<p><code>Person.name</code> is an instance of some type with a custom <code>__eq__</code> method. While <code>__eq__</code> normally returns a boolean(ish) value, it can actually return whatever you want, including a lambda. See <a href="http://docs.python.org/reference/datamodel.html#special-method-names" rel="nofollo...
9
2009-05-04T21:19:20Z
[ "python", "language-features" ]
Python sockets buffering
822,001
<p>Let's say I want to read a line from a socket, using the standard <code>socket</code> module:</p> <pre><code>def read_line(s): ret = '' while True: c = s.recv(1) if c == '\n' or c == '': break else: ret += c return ret </code></pre> <p>What exactly hap...
13
2009-05-04T20:50:59Z
822,057
<p>The <code>recv()</code> call is handled directly by calling the C library function.</p> <p>It will block waiting for the socket to have data. In reality it will just let the <code>recv()</code> system call block.</p> <p><code>file.readline()</code> is an efficient buffered implementation. It is not threadsafe, be...
18
2009-05-04T21:05:08Z
[ "python", "sockets", "buffering" ]
Python sockets buffering
822,001
<p>Let's say I want to read a line from a socket, using the standard <code>socket</code> module:</p> <pre><code>def read_line(s): ret = '' while True: c = s.recv(1) if c == '\n' or c == '': break else: ret += c return ret </code></pre> <p>What exactly hap...
13
2009-05-04T20:50:59Z
822,788
<p>If you are concerned with performance and control the socket completely (you are not passing it into a library for example) then try implementing your own buffering in Python -- Python string.find and string.split and such can be amazingly fast.</p> <pre><code>def linesplit(socket): buffer = socket.recv(4096) ...
20
2009-05-05T00:38:27Z
[ "python", "sockets", "buffering" ]
Python sockets buffering
822,001
<p>Let's say I want to read a line from a socket, using the standard <code>socket</code> module:</p> <pre><code>def read_line(s): ret = '' while True: c = s.recv(1) if c == '\n' or c == '': break else: ret += c return ret </code></pre> <p>What exactly hap...
13
2009-05-04T20:50:59Z
11,348,929
<pre><code>def buffered_readlines(pull_next_chunk, buf_size=4096): """ pull_next_chunk is callable that should accept one positional argument max_len, i.e. socket.recv or file().read and returns string of up to max_len long or empty one when nothing left to read. &gt;&gt;&gt; for line in buffered_readlines(s...
6
2012-07-05T16:49:27Z
[ "python", "sockets", "buffering" ]
How to separate content from a file that is a container for binary and other forms of content
822,161
<p>I am trying to parse some .txt files. These files serve as containers for a variable number of 'children' files that are set off or identified within the container with SGML tags. With python I can easily separate the children files. However I am having trouble writing the binary content back out as a binary file...
2
2009-05-04T21:32:00Z
822,192
<p>You definitely need to be reading in binary mode if the content includes JPEG images.</p> <p>As well, Python includes an SGML parser, <a href="http://docs.python.org/library/sgmllib.html" rel="nofollow">http://docs.python.org/library/sgmllib.html</a> .</p> <p>There is no example there, but all you need to do is se...
2
2009-05-04T21:39:13Z
[ "python", "text", "encoding", "file", "binary" ]
How to separate content from a file that is a container for binary and other forms of content
822,161
<p>I am trying to parse some .txt files. These files serve as containers for a variable number of 'children' files that are set off or identified within the container with SGML tags. With python I can easily separate the children files. However I am having trouble writing the binary content back out as a binary file...
2
2009-05-04T21:32:00Z
822,398
<p>You need to <code>open(filename,'rb')</code> to open the file in binary mode. Be aware that this will cause python to give You confusing, two-byte line endings on some operating systems.</p>
0
2009-05-04T22:27:41Z
[ "python", "text", "encoding", "file", "binary" ]
How to separate content from a file that is a container for binary and other forms of content
822,161
<p>I am trying to parse some .txt files. These files serve as containers for a variable number of 'children' files that are set off or identified within the container with SGML tags. With python I can easily separate the children files. However I am having trouble writing the binary content back out as a binary file...
2
2009-05-04T21:32:00Z
826,277
<p>What you're looking at isn't "binary", it's <strong><a href="http://en.wikipedia.org/wiki/Uuencode" rel="nofollow">uuencoded</a></strong>. Python's standard library includes the module <a href="http://docs.python.org/library/uu.html#module-uu" rel="nofollow">uu</a>, to handle uuencoded data.</p> <p>The module <a hr...
3
2009-05-05T18:27:56Z
[ "python", "text", "encoding", "file", "binary" ]
Emacs Pabbrev and Python
822,195
<p>Normally when you hit tab on an empty line in emacs python mode it will cycle through the available tab indentations. When I hit tab when the point is at the deepest indent level I get the pabbrev buffer containing the last best match options. Does anyone else have this problem, is there an easy way around it with...
3
2009-05-04T21:39:58Z
822,273
<p>No elisp? Sure:</p> <pre><code>M-x pabbrev-mode </code></pre> <p>should toggle it off. But, if you don't mind cutting/pasting elisp, you can turn off pabbrev mode in python buffers:</p> <pre><code>(add-hook 'python-mode (lambda () (pabbrev-mode -1))) </code></pre>
0
2009-05-04T21:54:38Z
[ "python", "emacs", "pabbrev" ]
Emacs Pabbrev and Python
822,195
<p>Normally when you hit tab on an empty line in emacs python mode it will cycle through the available tab indentations. When I hit tab when the point is at the deepest indent level I get the pabbrev buffer containing the last best match options. Does anyone else have this problem, is there an easy way around it with...
3
2009-05-04T21:39:58Z
823,395
<p>In light of the clarified requirements, you need something along the lines of this. I'm pretty sure you can't get away w/out writing some elisp. What's nice (IMO) is that this should work for all modes, not just python mode.</p> <pre><code>(defadvice pabbrev-expand-maybe (around pabbrev-expand-maybe-when-not-afte...
3
2009-05-05T04:48:39Z
[ "python", "emacs", "pabbrev" ]
Emacs Pabbrev and Python
822,195
<p>Normally when you hit tab on an empty line in emacs python mode it will cycle through the available tab indentations. When I hit tab when the point is at the deepest indent level I get the pabbrev buffer containing the last best match options. Does anyone else have this problem, is there an easy way around it with...
3
2009-05-04T21:39:58Z
14,367,349
<p>How is this for a late response? </p> <p>This should work out of the box now, thanks to a patch from Trey. Binding tab in the way that pabbrev.el is somewhat naughty, but what are you to do if you want rapid expansion. </p>
1
2013-01-16T20:35:42Z
[ "python", "emacs", "pabbrev" ]
I need a regex for the href attribute for an mp3 file url in python
822,260
<p>Based on a previous stack overflow question and contribution by cgoldberg, I came up with this regex using the python re module:</p> <pre><code>import re urls = re.finditer('http://(.*?).mp3', htmlcode) </code></pre> <p>The variable urls is an iterable object and I can use a loop to access each mp3 file url indivi...
2
2009-05-04T21:52:19Z
822,341
<p>First, yeah, you should probably be using an HTML parser. Here's some sample code using the HTMLParser module that comes with Python:</p> <pre><code>from HTMLParser import HTMLParser class ImgSrcHTMLParser(HTMLParser): def __init__(self): HTMLParser.__init__(self) self.srcs = [] def handle_starttag(se...
2
2009-05-04T22:12:26Z
[ "python", "regex" ]
I need a regex for the href attribute for an mp3 file url in python
822,260
<p>Based on a previous stack overflow question and contribution by cgoldberg, I came up with this regex using the python re module:</p> <pre><code>import re urls = re.finditer('http://(.*?).mp3', htmlcode) </code></pre> <p>The variable urls is an iterable object and I can use a loop to access each mp3 file url indivi...
2
2009-05-04T21:52:19Z
822,416
<p>As always I suggest using a html parser like <a href="http://codespeak.net/lxml/lxmlhtml.html" rel="nofollow">lxml.html</a> instead of regular expressions to extract informations from html files:</p> <pre><code>import lxml.html tree = lxml.html.fromstring(htmlcode) for link in tree.findall(".//a"): url = link....
2
2009-05-04T22:31:59Z
[ "python", "regex" ]
I need a regex for the href attribute for an mp3 file url in python
822,260
<p>Based on a previous stack overflow question and contribution by cgoldberg, I came up with this regex using the python re module:</p> <pre><code>import re urls = re.finditer('http://(.*?).mp3', htmlcode) </code></pre> <p>The variable urls is an iterable object and I can use a loop to access each mp3 file url indivi...
2
2009-05-04T21:52:19Z
822,523
<p>As pointed out by the other answers, using regular expressions to parse HTML = bad, bad idea.</p> <p>With that in mind, I will add in code of my favorite parser: <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">BeautifulSoup</a>:</p> <pre><code>from BeautifulSoup import BeautifulSoup soup =...
3
2009-05-04T22:56:19Z
[ "python", "regex" ]
How do I iterate over the HTML attributes of a Beautiful Soup element?
822,571
<p>How do I iterate over the HTML attributes of a Beautiful Soup element?</p> <p>Like, given:</p> <pre><code>&lt;foo bar="asdf" blah="123"&gt;xyz&lt;/foo&gt; </code></pre> <p>I want "bar" and "blah".</p>
17
2009-05-04T23:14:02Z
822,601
<pre><code>from BeautifulSoup import BeautifulSoup page = BeautifulSoup('&lt;foo bar="asdf" blah="123"&gt;xyz&lt;/foo&gt;') for attr, value in page.find('foo').attrs: print attr, "=", value # Prints: # bar = asdf # blah = 123 </code></pre>
28
2009-05-04T23:24:13Z
[ "python", "beautifulsoup" ]
logging in mod_python/apache
822,875
<p>What is the standard way to make python's logging module work with apache/modpython?</p> <p>I want to call mylog.warn('whatever') and have that result in a call to req.log_error() where req is the modpython request.</p> <p>Is there an easy way to set this up?</p>
2
2009-05-05T01:08:11Z
823,126
<p>I've never done it, but it seems that writing a subclass of <a href="http://docs.python.org/library/logging.html#handlers" rel="nofollow"><code>logging.Handler</code></a> shouldn't be that hard. Something like this should do the trick. I can't say that I have actually tried this since I don't have mod_python install...
2
2009-05-05T03:02:26Z
[ "python", "apache", "logging", "mod-python" ]
logging in mod_python/apache
822,875
<p>What is the standard way to make python's logging module work with apache/modpython?</p> <p>I want to call mylog.warn('whatever') and have that result in a call to req.log_error() where req is the modpython request.</p> <p>Is there an easy way to set this up?</p>
2
2009-05-05T01:08:11Z
824,236
<p>We use the following. It's documented completely <a href="http://docs.python.org/library/logging.html#module-logging" rel="nofollow">here</a>.</p> <ol> <li><p>We use <a href="http://docs.python.org/library/logging.html#logging.fileConfig" rel="nofollow">logging.fileConfig</a> with a logging.ini file.</p></li> <li>...
0
2009-05-05T10:18:14Z
[ "python", "apache", "logging", "mod-python" ]
Elegant, pythonic solution for forcing all keys and values to lower case in nested dictionaries of Unicode strings?
823,030
<p>I'm curious how the Python Ninjas around here would do the following, elegantly and pythonically:</p> <p>I've got a data structure that's a dict from unicode strings to dicts from unicode strings to unicode string lists. So:</p> <pre><code>&gt;&gt;&gt; type(myDict) &lt;type 'dict'&gt; &gt;&gt;&gt; type(myDict[u'my...
3
2009-05-05T02:25:32Z
823,057
<p>The following works for your example input:</p> <pre><code>&gt;&gt;&gt; myDict = {'myKey': {'myKey2': [u'Abc']}} &gt;&gt;&gt; newDict = dict([ (k1.lower(), dict([ (k2.lower(), [x.lower() for x in myDict[k1][k2]]) for k2 in myDict[k1].keys() ])) for k1 in myDict.keys() ...
1
2009-05-05T02:31:44Z
[ "python" ]
Elegant, pythonic solution for forcing all keys and values to lower case in nested dictionaries of Unicode strings?
823,030
<p>I'm curious how the Python Ninjas around here would do the following, elegantly and pythonically:</p> <p>I've got a data structure that's a dict from unicode strings to dicts from unicode strings to unicode string lists. So:</p> <pre><code>&gt;&gt;&gt; type(myDict) &lt;type 'dict'&gt; &gt;&gt;&gt; type(myDict[u'my...
3
2009-05-05T02:25:32Z
823,072
<p>A recursive variant:</p> <pre><code>def make_lowercase(obj): if hasattr(obj,'iteritems'): # dictionary ret = {} for k,v in obj.iteritems(): ret[make_lowercase(k)] = make_lowercase(v) return ret elif isinstance(obj,basestring): # string return obj.l...
3
2009-05-05T02:37:34Z
[ "python" ]
Elegant, pythonic solution for forcing all keys and values to lower case in nested dictionaries of Unicode strings?
823,030
<p>I'm curious how the Python Ninjas around here would do the following, elegantly and pythonically:</p> <p>I've got a data structure that's a dict from unicode strings to dicts from unicode strings to unicode string lists. So:</p> <pre><code>&gt;&gt;&gt; type(myDict) &lt;type 'dict'&gt; &gt;&gt;&gt; type(myDict[u'my...
3
2009-05-05T02:25:32Z
823,077
<p>Really simple way, though I'm not sure you'd call it Pythonic:</p> <pre><code>newDict = eval(repr(myDict).lower()) </code></pre> <p>Saner way:</p> <pre><code>newDict = dict((k1.lower(), dict((k2.lower(), [s.lower() for s in v2]) for k2, v2 in v1.iteritems())) f...
18
2009-05-05T02:39:37Z
[ "python" ]
Elegant, pythonic solution for forcing all keys and values to lower case in nested dictionaries of Unicode strings?
823,030
<p>I'm curious how the Python Ninjas around here would do the following, elegantly and pythonically:</p> <p>I've got a data structure that's a dict from unicode strings to dicts from unicode strings to unicode string lists. So:</p> <pre><code>&gt;&gt;&gt; type(myDict) &lt;type 'dict'&gt; &gt;&gt;&gt; type(myDict[u'my...
3
2009-05-05T02:25:32Z
823,079
<p>If you don't mind modifying your input:</p> <pre><code>def make_lower(x): try: return x.lower() # x is a string except AttributeError: # assume x is a dict of the appropriate form for key in x.keys(): x[key.lower()] = make_lower(x[key]) if key != key.lower(...
0
2009-05-05T02:40:48Z
[ "python" ]
What's the best way to record the type of every variable assignment in a Python program?
823,103
<p>Python is so dynamic that it's not always clear what's going on in a large program, and looking at a tiny bit of source code does not always help. To make matters worse, editors tend to have poor support for navigating to the definitions of tokens or import statements in a Python file.</p> <p>One way to compensate...
3
2009-05-05T02:52:08Z
823,111
<p>I don't think you can help making it slow, but it should be possible to detect the address of each variable when you encounter a STORE_FAST STORE_NAME STORE_* opcode.</p> <p>Whether or not this has been done before, I do not know.</p> <p>If you need debugging, look at <a href="http://docs.python.org/library/pdb.ht...
3
2009-05-05T02:56:25Z
[ "python", "profiling" ]
What's the best way to record the type of every variable assignment in a Python program?
823,103
<p>Python is so dynamic that it's not always clear what's going on in a large program, and looking at a tiny bit of source code does not always help. To make matters worse, editors tend to have poor support for navigating to the definitions of tokens or import statements in a Python file.</p> <p>One way to compensate...
3
2009-05-05T02:52:08Z
823,117
<p>What if you monkey-patched <code>object</code>'s class or another prototypical object?</p> <p>This might not be the easiest if you're not using new-style classes.</p>
1
2009-05-05T02:57:22Z
[ "python", "profiling" ]
What's the best way to record the type of every variable assignment in a Python program?
823,103
<p>Python is so dynamic that it's not always clear what's going on in a large program, and looking at a tiny bit of source code does not always help. To make matters worse, editors tend to have poor support for navigating to the definitions of tokens or import statements in a Python file.</p> <p>One way to compensate...
3
2009-05-05T02:52:08Z
823,179
<p>You might want to check out <a href="http://pychecker.sourceforge.net/" rel="nofollow">PyChecker</a>'s code - it does (i think) what you are looking to do.</p>
1
2009-05-05T03:23:50Z
[ "python", "profiling" ]
What's the best way to record the type of every variable assignment in a Python program?
823,103
<p>Python is so dynamic that it's not always clear what's going on in a large program, and looking at a tiny bit of source code does not always help. To make matters worse, editors tend to have poor support for navigating to the definitions of tokens or import statements in a Python file.</p> <p>One way to compensate...
3
2009-05-05T02:52:08Z
2,449,127
<p><a href="http://pythoscope.org" rel="nofollow">Pythoscope</a> does something very similar to what you describe and it uses a combination of static information in a form of AST and dynamic information through <code>sys.settrace</code>.</p> <p>BTW, if you have problems refactoring your project, give Pythoscope a try....
1
2010-03-15T17:30:32Z
[ "python", "profiling" ]
Why is this recursive statement wrong?
823,141
<p>This is a bank simulation that takes into account 20 different serving lines with a single queue, customers arrive following an exponential rate and they are served during a time that follows a normal probability distribution with mean 40 and standard deviation 20. </p> <p>Things were working just fine till I decid...
0
2009-05-05T03:08:00Z
823,149
<p>I think you want </p> <pre><code>return getnormal(self) </code></pre> <p>instead of</p> <pre><code>getnormal(self) </code></pre> <p>If the function exits without hitting a return statement, then it returns the special value None, which is a NoneType object - that's why Python complains about a 'NoneType.' The ab...
8
2009-05-05T03:12:39Z
[ "python", "recursion", "simpy" ]
Why is this recursive statement wrong?
823,141
<p>This is a bank simulation that takes into account 20 different serving lines with a single queue, customers arrive following an exponential rate and they are served during a time that follows a normal probability distribution with mean 40 and standard deviation 20. </p> <p>Things were working just fine till I decid...
0
2009-05-05T03:08:00Z
823,150
<p>You need to have:</p> <pre><code>return getNormal(self) </code></pre> <p>instead of</p> <pre><code>getNormal(self) </code></pre> <p>Really though, there's no need for recursion:</p> <pre><code>def getNormal(self): normal = 0 while normal &lt; 1: normal = normalvariate(40,20) return normal <...
1
2009-05-05T03:13:04Z
[ "python", "recursion", "simpy" ]
Why is this recursive statement wrong?
823,141
<p>This is a bank simulation that takes into account 20 different serving lines with a single queue, customers arrive following an exponential rate and they are served during a time that follows a normal probability distribution with mean 40 and standard deviation 20. </p> <p>Things were working just fine till I decid...
0
2009-05-05T03:08:00Z
823,160
<p>I am not entirely sure, but I think you need to change your method to the following:</p> <pre><code>def getNormal(self): normal = normalvariate(40,20) if (normal&gt;=1): return normal else: return getNormal(self) </code></pre>
1
2009-05-05T03:17:38Z
[ "python", "recursion", "simpy" ]
Yaml merge in Python
823,196
<p>So I'm toying around with the idea of making myself (and anyone who cares to use it of course) a little boilerplate library in Python for Pygame. I would like a system where settings for the application are provided with a yaml file. </p> <p>So I was thinking it would be useful if the library provided a default yam...
11
2009-05-05T03:31:41Z
823,240
<p>You could use <a href="http://pyyaml.org/">PyYAML</a> for parsing the files, and then the following function to merge two trees:</p> <pre><code>def merge(user, default): if isinstance(user,dict) and isinstance(default,dict): for k,v in default.iteritems(): if k not in user: u...
17
2009-05-05T03:46:17Z
[ "python", "configuration", "yaml" ]
What does += mean in Python?
823,561
<p>I see code like this for example in Python:</p> <pre><code> if cnt &gt; 0 and len(aStr) &gt; 1: while cnt &gt; 0: aStr = aStr[1:]+aStr[0] cnt += 1 </code></pre> <p>What does the <code>+=</code> mean?</p>
9
2009-05-05T06:10:26Z
823,567
<pre><code>a += b </code></pre> <p>is <em>in this case</em> the same as</p> <pre><code>a = a + b </code></pre> <p>In this case cnt += 1 means that cnt is increased by one.</p> <p>Note that the code you pasted will loop indefinitely if cnt > 0 and len(aStr) > 1.</p> <p><strong>Edit</strong>: quote <a href="http://s...
22
2009-05-05T06:11:25Z
[ "python", "syntax" ]
What does += mean in Python?
823,561
<p>I see code like this for example in Python:</p> <pre><code> if cnt &gt; 0 and len(aStr) &gt; 1: while cnt &gt; 0: aStr = aStr[1:]+aStr[0] cnt += 1 </code></pre> <p>What does the <code>+=</code> mean?</p>
9
2009-05-05T06:10:26Z
823,576
<p>it means "append "THIS" to the current value"</p> <p>example:</p> <p>a = "hello"; a += " world";</p> <p>printing a now will output: "hello world"</p>
-3
2009-05-05T06:14:40Z
[ "python", "syntax" ]
What does += mean in Python?
823,561
<p>I see code like this for example in Python:</p> <pre><code> if cnt &gt; 0 and len(aStr) &gt; 1: while cnt &gt; 0: aStr = aStr[1:]+aStr[0] cnt += 1 </code></pre> <p>What does the <code>+=</code> mean?</p>
9
2009-05-05T06:10:26Z
823,580
<p>FYI: it looks like you might have an infinite loop in your example...</p> <pre><code>if cnt &gt; 0 and len(aStr) &gt; 1: while cnt &gt; 0: aStr = aStr[1:]+aStr[0] cnt += 1 </code></pre> <ul> <li>a condition of entering the loop is that <code>cnt</code> is greater than 0</li> <...
1
2009-05-05T06:15:34Z
[ "python", "syntax" ]
What does += mean in Python?
823,561
<p>I see code like this for example in Python:</p> <pre><code> if cnt &gt; 0 and len(aStr) &gt; 1: while cnt &gt; 0: aStr = aStr[1:]+aStr[0] cnt += 1 </code></pre> <p>What does the <code>+=</code> mean?</p>
9
2009-05-05T06:10:26Z
823,583
<p>Google 'python += operator' leads you to <a href="http://docs.python.org/library/operator.html" rel="nofollow">http://docs.python.org/library/operator.html</a></p> <p>Search for += once the page loads up for a more detailed answer.</p>
7
2009-05-05T06:16:56Z
[ "python", "syntax" ]
What does += mean in Python?
823,561
<p>I see code like this for example in Python:</p> <pre><code> if cnt &gt; 0 and len(aStr) &gt; 1: while cnt &gt; 0: aStr = aStr[1:]+aStr[0] cnt += 1 </code></pre> <p>What does the <code>+=</code> mean?</p>
9
2009-05-05T06:10:26Z
823,878
<p><code>a += b</code> is essentially the same as <code>a = a + b</code>, except that:</p> <ul> <li><code>+</code> always returns a newly allocated object, but <code>+=</code> should (but doesn't have to) modify the object in-place if it's mutable (e.g. <code>list</code> or <code>dict</code>, but <code>int</code> and ...
63
2009-05-05T08:28:49Z
[ "python", "syntax" ]
What does += mean in Python?
823,561
<p>I see code like this for example in Python:</p> <pre><code> if cnt &gt; 0 and len(aStr) &gt; 1: while cnt &gt; 0: aStr = aStr[1:]+aStr[0] cnt += 1 </code></pre> <p>What does the <code>+=</code> mean?</p>
9
2009-05-05T06:10:26Z
825,505
<p><code>+=</code> is the <a href="http://docs.python.org/library/operator.html#operator.iadd" rel="nofollow">in-place addition operator</a>.</p> <p>It's the same as doing <code>cnt = cnt + 1</code>. For example:</p> <pre><code>&gt;&gt;&gt; cnt = 0 &gt;&gt;&gt; cnt += 2 &gt;&gt;&gt; print cnt 2 &gt;&gt;&gt; cnt += 42...
0
2009-05-05T15:43:55Z
[ "python", "syntax" ]