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 |
|---|---|---|---|---|---|---|---|---|---|
Performance Advantages to Iterators?
| 628,903
|
<p>What (if any) performance advantages are offered by using iterators. It seems like the 'Right Way' to solve many problems, but does it create faster/more memory-conscious code? I'm thinking specifically in Python, but don't restrict answers to just that. </p>
| 14
|
2009-03-10T04:05:59Z
| 628,978
|
<p>An iterator is simply an object that provides methods to allow traversing through a collection. You could traverse all of the elements of an array or all the nodes of a tree with the same interface. Trees and arrays are very different data structures and require different methods to traverse .. but with an iterator you can loop through all elements in the same way.</p>
<p>For one type of collection, there may also be different ways to traverse it and a single collection could have multiple iterators .. You could have a depth-first iterator or a breadth-first iterator traversing a tree structure and returning the nodes in different orders.
Iterators are not intended for performance ... but typically for providing a consistent interface for traversing structures.</p>
| 1
|
2009-03-10T05:00:04Z
|
[
"python",
"performance",
"iterator"
] |
Performance Advantages to Iterators?
| 628,903
|
<p>What (if any) performance advantages are offered by using iterators. It seems like the 'Right Way' to solve many problems, but does it create faster/more memory-conscious code? I'm thinking specifically in Python, but don't restrict answers to just that. </p>
| 14
|
2009-03-10T04:05:59Z
| 628,979
|
<p>The primary benefit of iterators is not one of performance. In my experience the most performant solution is creating an algorithm which embeds your data structure of choice. The benefit of iterators is that they allow you to decouple data and algorithm and, therefore, generalize and reuse both. If this can also be done without (or with little) performance degradation then it's a net gain.</p>
<p>My favorite example of iterator usage can be found in the C++ <a href="http://www.sgi.com/tech/stl/" rel="nofollow">Standard Template Library</a>. It manages to demonstrate the power and beauty of the abstraction by cleanly separating container and algorithm without sacrificing performance. Understanding this design had a profound effect on the way I think about code.</p>
| 4
|
2009-03-10T05:00:05Z
|
[
"python",
"performance",
"iterator"
] |
Performance Advantages to Iterators?
| 628,903
|
<p>What (if any) performance advantages are offered by using iterators. It seems like the 'Right Way' to solve many problems, but does it create faster/more memory-conscious code? I'm thinking specifically in Python, but don't restrict answers to just that. </p>
| 14
|
2009-03-10T04:05:59Z
| 629,169
|
<p>For Python, generators will be faster and have better memory efficiency. Just think of an example of <code>range(1000)</code> <strong>vs</strong> <code>xrange(1000)</code> (This has been changed in 3.0, range is now an generator). With Range you pre-build your list but XRange just has a generator object and yields the next item when needed instead.</p>
<p>The performance difference isn't great on small things, but as soon as you start cranking them out getting larger and larger sets of information you'll notice it quite quickly. Also, not just having to generate and then step through, you will be consuming extra memory for your pre-built item where-as with the generator expression only 1 item at a time gets made.</p>
| 13
|
2009-03-10T07:07:24Z
|
[
"python",
"performance",
"iterator"
] |
Performance Advantages to Iterators?
| 628,903
|
<p>What (if any) performance advantages are offered by using iterators. It seems like the 'Right Way' to solve many problems, but does it create faster/more memory-conscious code? I'm thinking specifically in Python, but don't restrict answers to just that. </p>
| 14
|
2009-03-10T04:05:59Z
| 631,619
|
<p>There's actually a very good mail on the python mailing list about this: <a href="http://markmail.org/message/t2a6tp33n5lddzvy">Iterators vs Lists</a>. It's a bit dated (from 2003), but as far as I know, it's still valid.</p>
<p>Here's the summary:</p>
<blockquote>
<p>For small datasets, iterator and list based approaches have similar
performance.
For larger datasets, iterators save both time and space.</p>
</blockquote>
<p>What I would draw from it is this: iterators are to be preferred over loading data into a list if possible. But unless you have a big dataset, don't contort your code to make something that should fit in a list to work with an iterator.</p>
| 15
|
2009-03-10T18:16:59Z
|
[
"python",
"performance",
"iterator"
] |
Performance Advantages to Iterators?
| 628,903
|
<p>What (if any) performance advantages are offered by using iterators. It seems like the 'Right Way' to solve many problems, but does it create faster/more memory-conscious code? I'm thinking specifically in Python, but don't restrict answers to just that. </p>
| 14
|
2009-03-10T04:05:59Z
| 631,909
|
<p>To backup the <a href="http://stackoverflow.com/questions/628903/performance-advantages-to-iterators/629169#629169">@Christian Witts's answer</a>: </p>
<h3><code>range</code> vs. <code>xrange</code> performance</h3>
<pre><code>python25 -mtimeit "for i in xrange(1000): pass"
10000 loops, best of 3: 56.3 usec per loop
python25 -mtimeit "for i in range(1000): pass"
10000 loops, best of 3: 80.9 usec per loop
python26 -mtimeit "for i in xrange(1000): pass"
10000 loops, best of 3: 48.8 usec per loop
python26 -mtimeit "for i in range(1000): pass"
10000 loops, best of 3: 68.6 usec per loop
</code></pre>
<p>btw, neither <code>range()</code> nor <code>xrange()</code> are iterators:</p>
<pre><code>>>> hasattr(range(1), 'next')
False
>>> hasattr(xrange(1), 'next')
False
>>> iter(xrange(1))
<rangeiterator object at 0x0097A500>
>>> iter(range(1))
<listiterator object at 0x00A7BFD0>
>>> iter([])
<listiterator object at 0x00A7BE30>
>>> iter(i for i in (1,))
<generator object at 0x00A7F940>
>>> (i for i in (1,))
<generator object at 0x00A7FDC8>
</code></pre>
| 3
|
2009-03-10T19:31:53Z
|
[
"python",
"performance",
"iterator"
] |
Performance Advantages to Iterators?
| 628,903
|
<p>What (if any) performance advantages are offered by using iterators. It seems like the 'Right Way' to solve many problems, but does it create faster/more memory-conscious code? I'm thinking specifically in Python, but don't restrict answers to just that. </p>
| 14
|
2009-03-10T04:05:59Z
| 734,050
|
<p>My inference from many answers above is "Use list to code. If necessary, re-factor using iterators" The difference is not apparent unless you have a large dataset.</p>
<p>Another thing to note is that, even when using lists often, the dataset we are operating upon is progressively smaller and smaller. </p>
| 2
|
2009-04-09T12:45:50Z
|
[
"python",
"performance",
"iterator"
] |
Privilege Escalation in Web Environment for File Access
| 628,956
|
<p>I have a situation where I would like to elevate the permissions I have in a web environment so that I can access a serial device. </p>
<p>The specific case is where I have a web interface for configuring a modem that comes up on <code>/dev/ttyUSB[0-9]</code>. </p>
<p>Zero or more modems will be plugged in by an end user. I am writing some software that is capable of discerning which is a USB Wireless Modem by reading <code>/sys/devices</code> and talking to the modem using some AT commands.</p>
<p>I would like to be able to open the device and do something like:</p>
<pre><code>ser = serial.Serial(tty, baudrate=115200, timeout=10)
ser.write('AT+CGSN\r\n')
imei = ser.readline()
</code></pre>
<p>The problem is that <code>pyserial</code> does this: <code>self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK)</code> to open the serial port, where portstr is <code>/dev/ttyUSB0</code>, but it does it as the <code>nobody</code> user, which is unprivileged.</p>
<p>Serial ports on this system are owned by root:uucp and are set as 0660 (i.e. <code>rw-rw----</code>).</p>
<p>What is the best way for a user such as <code>nobody</code> who should have as few permissions as possible to open a file in dev?</p>
<p>Ideas I will consider:</p>
<ul>
<li>Doing things in a subprocess using <code>sudo</code>.</li>
<li>Changing permissions of the files in <code>/dev/</code> (instructions on how to do this properly using udev are appreciated!)</li>
<li>Using another API or piece of software I have not considered.</li>
</ul>
| 1
|
2009-03-10T04:42:25Z
| 629,034
|
<p>The sudo idea could be possible. IIRC, you can set specific commands to be sudo-able, but without requiring a password.</p>
<p>The other option is to put <code>nobody</code> in a group that has access to the device you want, or to start Apache as the group that does have access.</p>
<p>If you're using fastcgi (or equiv), I think you can have it run scripts as the owning user (some shared hosts do this).</p>
<p>To change permissions of files in <code>/dev</code>, just chmod them.</p>
| -1
|
2009-03-10T05:34:16Z
|
[
"python",
"linux",
"permissions",
"serial-port",
"cgi"
] |
Privilege Escalation in Web Environment for File Access
| 628,956
|
<p>I have a situation where I would like to elevate the permissions I have in a web environment so that I can access a serial device. </p>
<p>The specific case is where I have a web interface for configuring a modem that comes up on <code>/dev/ttyUSB[0-9]</code>. </p>
<p>Zero or more modems will be plugged in by an end user. I am writing some software that is capable of discerning which is a USB Wireless Modem by reading <code>/sys/devices</code> and talking to the modem using some AT commands.</p>
<p>I would like to be able to open the device and do something like:</p>
<pre><code>ser = serial.Serial(tty, baudrate=115200, timeout=10)
ser.write('AT+CGSN\r\n')
imei = ser.readline()
</code></pre>
<p>The problem is that <code>pyserial</code> does this: <code>self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK)</code> to open the serial port, where portstr is <code>/dev/ttyUSB0</code>, but it does it as the <code>nobody</code> user, which is unprivileged.</p>
<p>Serial ports on this system are owned by root:uucp and are set as 0660 (i.e. <code>rw-rw----</code>).</p>
<p>What is the best way for a user such as <code>nobody</code> who should have as few permissions as possible to open a file in dev?</p>
<p>Ideas I will consider:</p>
<ul>
<li>Doing things in a subprocess using <code>sudo</code>.</li>
<li>Changing permissions of the files in <code>/dev/</code> (instructions on how to do this properly using udev are appreciated!)</li>
<li>Using another API or piece of software I have not considered.</li>
</ul>
| 1
|
2009-03-10T04:42:25Z
| 629,256
|
<p>In this case, I would write a daemon run by a system user that accepted socket connections and relayed them to the appropriate device, then use sockets within the web application to talk to the daemon. This also helps keep the web app from blocking when opening a device that isn't quite ready to deal with users, settle locks a little more sanely than you could with CGI, etc.</p>
<p>However, if you wish to give the application the ability to talk to the devices directly, give them the same permissions that null has.</p>
| 2
|
2009-03-10T07:48:12Z
|
[
"python",
"linux",
"permissions",
"serial-port",
"cgi"
] |
Privilege Escalation in Web Environment for File Access
| 628,956
|
<p>I have a situation where I would like to elevate the permissions I have in a web environment so that I can access a serial device. </p>
<p>The specific case is where I have a web interface for configuring a modem that comes up on <code>/dev/ttyUSB[0-9]</code>. </p>
<p>Zero or more modems will be plugged in by an end user. I am writing some software that is capable of discerning which is a USB Wireless Modem by reading <code>/sys/devices</code> and talking to the modem using some AT commands.</p>
<p>I would like to be able to open the device and do something like:</p>
<pre><code>ser = serial.Serial(tty, baudrate=115200, timeout=10)
ser.write('AT+CGSN\r\n')
imei = ser.readline()
</code></pre>
<p>The problem is that <code>pyserial</code> does this: <code>self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK)</code> to open the serial port, where portstr is <code>/dev/ttyUSB0</code>, but it does it as the <code>nobody</code> user, which is unprivileged.</p>
<p>Serial ports on this system are owned by root:uucp and are set as 0660 (i.e. <code>rw-rw----</code>).</p>
<p>What is the best way for a user such as <code>nobody</code> who should have as few permissions as possible to open a file in dev?</p>
<p>Ideas I will consider:</p>
<ul>
<li>Doing things in a subprocess using <code>sudo</code>.</li>
<li>Changing permissions of the files in <code>/dev/</code> (instructions on how to do this properly using udev are appreciated!)</li>
<li>Using another API or piece of software I have not considered.</li>
</ul>
| 1
|
2009-03-10T04:42:25Z
| 629,493
|
<p>"What is the best way for a user such as nobody who should have as few permissions as possible to open a file in dev?"</p>
<p>Actually, you're better off using mod_wsgi in daemon mode for your web application. The mod_wsgi user can be any username (and group) you provide. </p>
<p>You can run as a user with appropriately defined privileges.</p>
<p>See <a href="http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIDaemonProcess" rel="nofollow">http://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIDaemonProcess</a></p>
| 1
|
2009-03-10T09:54:11Z
|
[
"python",
"linux",
"permissions",
"serial-port",
"cgi"
] |
Privilege Escalation in Web Environment for File Access
| 628,956
|
<p>I have a situation where I would like to elevate the permissions I have in a web environment so that I can access a serial device. </p>
<p>The specific case is where I have a web interface for configuring a modem that comes up on <code>/dev/ttyUSB[0-9]</code>. </p>
<p>Zero or more modems will be plugged in by an end user. I am writing some software that is capable of discerning which is a USB Wireless Modem by reading <code>/sys/devices</code> and talking to the modem using some AT commands.</p>
<p>I would like to be able to open the device and do something like:</p>
<pre><code>ser = serial.Serial(tty, baudrate=115200, timeout=10)
ser.write('AT+CGSN\r\n')
imei = ser.readline()
</code></pre>
<p>The problem is that <code>pyserial</code> does this: <code>self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK)</code> to open the serial port, where portstr is <code>/dev/ttyUSB0</code>, but it does it as the <code>nobody</code> user, which is unprivileged.</p>
<p>Serial ports on this system are owned by root:uucp and are set as 0660 (i.e. <code>rw-rw----</code>).</p>
<p>What is the best way for a user such as <code>nobody</code> who should have as few permissions as possible to open a file in dev?</p>
<p>Ideas I will consider:</p>
<ul>
<li>Doing things in a subprocess using <code>sudo</code>.</li>
<li>Changing permissions of the files in <code>/dev/</code> (instructions on how to do this properly using udev are appreciated!)</li>
<li>Using another API or piece of software I have not considered.</li>
</ul>
| 1
|
2009-03-10T04:42:25Z
| 629,569
|
<p>There's another way of doing this: Unix/Linux allows sending file descriptors via Unix sockets. There's even a Perl module for that: <a href="http://search.cpan.org/~sampo/Socket-PassAccessRights-0.03/PassAccessRights.pm" rel="nofollow">PassAccessRights.pm</a>. Didn't find similar module for Python but it could be easily implemented.</p>
| 2
|
2009-03-10T10:18:07Z
|
[
"python",
"linux",
"permissions",
"serial-port",
"cgi"
] |
Privilege Escalation in Web Environment for File Access
| 628,956
|
<p>I have a situation where I would like to elevate the permissions I have in a web environment so that I can access a serial device. </p>
<p>The specific case is where I have a web interface for configuring a modem that comes up on <code>/dev/ttyUSB[0-9]</code>. </p>
<p>Zero or more modems will be plugged in by an end user. I am writing some software that is capable of discerning which is a USB Wireless Modem by reading <code>/sys/devices</code> and talking to the modem using some AT commands.</p>
<p>I would like to be able to open the device and do something like:</p>
<pre><code>ser = serial.Serial(tty, baudrate=115200, timeout=10)
ser.write('AT+CGSN\r\n')
imei = ser.readline()
</code></pre>
<p>The problem is that <code>pyserial</code> does this: <code>self.fd = os.open(self.portstr, os.O_RDWR|os.O_NOCTTY|os.O_NONBLOCK)</code> to open the serial port, where portstr is <code>/dev/ttyUSB0</code>, but it does it as the <code>nobody</code> user, which is unprivileged.</p>
<p>Serial ports on this system are owned by root:uucp and are set as 0660 (i.e. <code>rw-rw----</code>).</p>
<p>What is the best way for a user such as <code>nobody</code> who should have as few permissions as possible to open a file in dev?</p>
<p>Ideas I will consider:</p>
<ul>
<li>Doing things in a subprocess using <code>sudo</code>.</li>
<li>Changing permissions of the files in <code>/dev/</code> (instructions on how to do this properly using udev are appreciated!)</li>
<li>Using another API or piece of software I have not considered.</li>
</ul>
| 1
|
2009-03-10T04:42:25Z
| 636,564
|
<p>Configure a <em>udev</em> rule to <em>chgrp</em> the new device to <em>nobody</em>, if it is acceptable that every access via the web interface be permitted the same access to the device. Here's what I put in my <em>eee-bpw</em> package in file <em>/etc/udev/rules.d/99-bpw.rules</em>.</p>
<pre><code># Sierra Wireless AirCard 880 U
BUS=="usb", KERNEL=="ttyUSB2*", ACTION=="add", \
PRODUCT=="1199/6855/0", DEVNAME=="/dev/tts/USB2", \
OWNER="root", GROUP="dialout", \
SYMLINK+="bpw", RUN="/usr/sbin/bpw"
</code></pre>
<p>Substitute <em>nobody</em> for <em>dialout</em>. This particular rule assumes the device name to be <em>/dev/ttyUSB2</em>, but you can extend the rule considerably, see the <em>udev</em> documentation.</p>
| 1
|
2009-03-11T22:02:29Z
|
[
"python",
"linux",
"permissions",
"serial-port",
"cgi"
] |
How do I send a HTTP POST value to a (PHP) page using Python?
| 629,518
|
<p>I have a PHP page that has 1 textbox and when I press on the submit button. My SQL is going to store this product name into my database. My question is; is it possible to send/post the product name using Python script that asks for 1 value and then use my PHP page to send it to my database? Thanks! </p>
| 1
|
2009-03-10T10:02:22Z
| 629,534
|
<p>Check out the urllib and urllib2 modules. </p>
<p><a href="http://docs.python.org/library/urllib2.html" rel="nofollow">http://docs.python.org/library/urllib2.html</a></p>
<p><a href="http://docs.python.org/library/urllib.html" rel="nofollow">http://docs.python.org/library/urllib.html</a></p>
<p>Simply create a Request object with the needed data. Then read the response from your PHP service. </p>
<p><a href="http://docs.python.org/library/urllib2.html#urllib2.Request" rel="nofollow">http://docs.python.org/library/urllib2.html#urllib2.Request</a></p>
| 5
|
2009-03-10T10:05:27Z
|
[
"php",
"python",
"post"
] |
How do I send a HTTP POST value to a (PHP) page using Python?
| 629,518
|
<p>I have a PHP page that has 1 textbox and when I press on the submit button. My SQL is going to store this product name into my database. My question is; is it possible to send/post the product name using Python script that asks for 1 value and then use my PHP page to send it to my database? Thanks! </p>
| 1
|
2009-03-10T10:02:22Z
| 629,538
|
<p>Yes. <a href="http://docs.python.org/library/urllib2.html" rel="nofollow">urllib2</a> is a nice Python way to form/send HTTP requests.</p>
| 2
|
2009-03-10T10:06:08Z
|
[
"php",
"python",
"post"
] |
How do I send a HTTP POST value to a (PHP) page using Python?
| 629,518
|
<p>I have a PHP page that has 1 textbox and when I press on the submit button. My SQL is going to store this product name into my database. My question is; is it possible to send/post the product name using Python script that asks for 1 value and then use my PHP page to send it to my database? Thanks! </p>
| 1
|
2009-03-10T10:02:22Z
| 630,100
|
<p>When testing, or automating websites using python, I enjoy using twill. Twill is a tool that automatically handles cookies and can read HTML forms and submit them.</p>
<p>For instance, if you had a form on a webpage you could conceivably use the following code:</p>
<pre><code>from twill import commands
commands.go('http://example.com/create_product')
commands.formvalue('formname', 'product', 'new value')
commands.submit()
</code></pre>
<p>This would load the form, fill in the value, and submit it.</p>
| 3
|
2009-03-10T13:15:45Z
|
[
"php",
"python",
"post"
] |
How do I send a HTTP POST value to a (PHP) page using Python?
| 629,518
|
<p>I have a PHP page that has 1 textbox and when I press on the submit button. My SQL is going to store this product name into my database. My question is; is it possible to send/post the product name using Python script that asks for 1 value and then use my PHP page to send it to my database? Thanks! </p>
| 1
|
2009-03-10T10:02:22Z
| 632,312
|
<p>I find <a href="http://www.voidspace.org.uk/python/articles/urllib2.shtml" rel="nofollow">http://www.voidspace.org.uk/python/articles/urllib2.shtml</a> to be a good source of information about urllib2, which is probably the best tool for the job.</p>
<pre><code>import urllib
import urllib2
url = 'http://www.someserver.com/cgi-bin/register.cgi'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {'name' : 'Michael Foord',
'location' : 'Northampton',
'language' : 'Python' }
headers = { 'User-Agent' : user_agent }
data = urllib.urlencode(values)
req = urllib2.Request(url, data, headers)
response = urllib2.urlopen(req)
the_page = response.read()
</code></pre>
<p>The encoding is actually done using urllib, and this supports HTTP POST. There is also a way to use GET, where you have to pass the data into urlencode.</p>
<p>Don't forget to call read() though, otherwise the request won't be completed.</p>
| 3
|
2009-03-10T21:16:00Z
|
[
"php",
"python",
"post"
] |
How do I send a HTTP POST value to a (PHP) page using Python?
| 629,518
|
<p>I have a PHP page that has 1 textbox and when I press on the submit button. My SQL is going to store this product name into my database. My question is; is it possible to send/post the product name using Python script that asks for 1 value and then use my PHP page to send it to my database? Thanks! </p>
| 1
|
2009-03-10T10:02:22Z
| 634,178
|
<p>Just an addendum to <a href="http://stackoverflow.com/questions/629518/how-do-i-send-a-http-post-value-to-a-php-page-using-python/632312#632312">@antileet</a>'s procedure, it works similarly if you're trying to do a HTTP POST request with a web-service-like payload, except you just omit the urlencode step; i.e.</p>
<pre><code>import urllib, urllib2
payload = """
<?xml version='1.0'?>
<web_service_request>
<short_order>Spam</short_order>
<short_order>Eggs</short_order>
</web_service_request>
""".strip()
query_string_values = {'test': 1}
uri = 'http://example.com'
# You can still encode values in the query string, even though
# it's a POST request. Nice to have this when your payload is
# a chunk of text.
if query_string_values:
uri = ''.join([uri, '/?', urllib.urlencode(query_string_values)])
req = urllib2.Request(uri, data=payload)
assert req.get_method() == 'POST'
response = urllib2.urlopen(req)
print 'Response:', response.read()
</code></pre>
| 0
|
2009-03-11T11:40:35Z
|
[
"php",
"python",
"post"
] |
How do I send a HTTP POST value to a (PHP) page using Python?
| 629,518
|
<p>I have a PHP page that has 1 textbox and when I press on the submit button. My SQL is going to store this product name into my database. My question is; is it possible to send/post the product name using Python script that asks for 1 value and then use my PHP page to send it to my database? Thanks! </p>
| 1
|
2009-03-10T10:02:22Z
| 34,576,169
|
<p>Personally i prefer to use <strong>Requests</strong>. As its summary, this is a <em>HTTP library for Python, built for human beings</em>.</p>
<p>To quickly solve problems, rather than study deeply in HTTP, <strong>Requests</strong> will be a better choice. (Yeah, i mean compared to <em>urllib</em> or <em>socket</em>)</p>
<p>For example,
A python file which send a POST request with userdata:</p>
<pre><code>import requests
userdata = {"firstname": "Smith", "lastname": "Ayasaki", "password": "123456"}
resp = requests.post('http://example.com/test.php', data = userdata)
</code></pre>
<p>And the following text.php treating this request:</p>
<pre><code>$firstname = htmlspecialchars($_POST["firstname"]);
$lastname = htmlspecialchars($_POST["lastname"]);
$password = htmlspecialchars($_POST["password"]);
echo "FIRSTNAME: $firstname LASTNAME: $lastname PW: $password";
</code></pre>
<p>Finally, the response text (resp.content in python) will be like:</p>
<blockquote>
<p>FIRSTNAME: Smith LASTNAME: Ayasaki PW: 123456</p>
</blockquote>
<ul>
<li>A simple Quickstart: <a href="http://docs.python-requests.org/en/latest/user/quickstart/" rel="nofollow">http://docs.python-requests.org/en/latest/user/quickstart/</a></li>
<li>Another answer recommending <strong>Requests</strong>: <a href="https://stackoverflow.com/questions/4214231/sending-data-using-post-in-python-to-php/29492097#29492097">Sending data using POST in Python to PHP</a></li>
</ul>
| 0
|
2016-01-03T11:46:53Z
|
[
"php",
"python",
"post"
] |
How to query as GROUP BY in django?
| 629,551
|
<p>I query a model, </p>
<pre><code>Members.objects.all()
</code></pre>
<p>and it returns say</p>
<pre><code>Eric, Salesman, X-Shop
Freddie, Manager, X2-Shop
Teddy, Salesman, X2-Shop
Sean, Manager, X2-Shop
</code></pre>
<p>What i want is, to know the best Django way to fire
a group_by query to my db, as like,</p>
<pre><code>Members.objects.all().group_by('designation')
</code></pre>
<p>Which doesn't work of course.
I know we can do some tricks on "django/db/models/query.py",
but i am just curious to know how to do it without patching.</p>
| 161
|
2009-03-10T10:10:30Z
| 629,584
|
<p>You need to do custom SQL as exemplified in this snippet:</p>
<p><a href="http://www.djangosnippets.org/snippets/236/" rel="nofollow">Custom SQL via subquery</a></p>
<p>Or in a custom manager as shown in the online Django docs:</p>
<p><a href="http://docs.djangoproject.com/en/dev/topics/db/managers/#adding-extra-manager-methods" rel="nofollow">Adding extra Manager methods</a></p>
| 4
|
2009-03-10T10:24:57Z
|
[
"python",
"django"
] |
How to query as GROUP BY in django?
| 629,551
|
<p>I query a model, </p>
<pre><code>Members.objects.all()
</code></pre>
<p>and it returns say</p>
<pre><code>Eric, Salesman, X-Shop
Freddie, Manager, X2-Shop
Teddy, Salesman, X2-Shop
Sean, Manager, X2-Shop
</code></pre>
<p>What i want is, to know the best Django way to fire
a group_by query to my db, as like,</p>
<pre><code>Members.objects.all().group_by('designation')
</code></pre>
<p>Which doesn't work of course.
I know we can do some tricks on "django/db/models/query.py",
but i am just curious to know how to do it without patching.</p>
| 161
|
2009-03-10T10:10:30Z
| 629,600
|
<p>An easy solution, but not in a proper way is to use RAW-SQL:</p>
<p><a href="http://docs.djangoproject.com/en/dev/topics/db/sql/#topics-db-sql">http://docs.djangoproject.com/en/dev/topics/db/sql/#topics-db-sql</a></p>
<p>Another solution is to use the group_by property:</p>
<pre><code>query = Members.objects.all().query
query.group_by = ['designation']
results = QuerySet(query=query, model=Members)
</code></pre>
<p>You can now iterate over the results variable to retrieve your results. Note that group_by is not documented and may be changed in future version of Django.</p>
<p>And... why do you want to use group_by? If you don't use aggregation, you can use order_by to achieve an alike result.</p>
| 25
|
2009-03-10T10:30:44Z
|
[
"python",
"django"
] |
How to query as GROUP BY in django?
| 629,551
|
<p>I query a model, </p>
<pre><code>Members.objects.all()
</code></pre>
<p>and it returns say</p>
<pre><code>Eric, Salesman, X-Shop
Freddie, Manager, X2-Shop
Teddy, Salesman, X2-Shop
Sean, Manager, X2-Shop
</code></pre>
<p>What i want is, to know the best Django way to fire
a group_by query to my db, as like,</p>
<pre><code>Members.objects.all().group_by('designation')
</code></pre>
<p>Which doesn't work of course.
I know we can do some tricks on "django/db/models/query.py",
but i am just curious to know how to do it without patching.</p>
| 161
|
2009-03-10T10:10:30Z
| 629,691
|
<p>If you mean to do aggregation and are using Django 1.1 (currently in alpha 1), you can use the new <a href="http://docs.djangoproject.com/en/dev/topics/db/aggregation/#topics-db-aggregation">aggregation features of the ORM</a>:</p>
<pre><code>from django.db.models import Count
Members.objects.values('designation').annotate(dcount=Count('designation'))
</code></pre>
<p>This results in a query similar to</p>
<pre><code>SELECT designation, COUNT(designation) AS dcount
FROM members GROUP BY designation
</code></pre>
<p>and the output would be of the form</p>
<pre><code>[{'designation': 'Salesman', 'dcount': 2},
{'designation': 'Manager', 'dcount': 2}]
</code></pre>
| 246
|
2009-03-10T11:08:28Z
|
[
"python",
"django"
] |
How to query as GROUP BY in django?
| 629,551
|
<p>I query a model, </p>
<pre><code>Members.objects.all()
</code></pre>
<p>and it returns say</p>
<pre><code>Eric, Salesman, X-Shop
Freddie, Manager, X2-Shop
Teddy, Salesman, X2-Shop
Sean, Manager, X2-Shop
</code></pre>
<p>What i want is, to know the best Django way to fire
a group_by query to my db, as like,</p>
<pre><code>Members.objects.all().group_by('designation')
</code></pre>
<p>Which doesn't work of course.
I know we can do some tricks on "django/db/models/query.py",
but i am just curious to know how to do it without patching.</p>
| 161
|
2009-03-10T10:10:30Z
| 26,843,739
|
<p>If I'm not mistaking you can use, <em>whatever-query-set</em>.group_by=['<em>field</em>'] </p>
| 0
|
2014-11-10T12:22:15Z
|
[
"python",
"django"
] |
How to query as GROUP BY in django?
| 629,551
|
<p>I query a model, </p>
<pre><code>Members.objects.all()
</code></pre>
<p>and it returns say</p>
<pre><code>Eric, Salesman, X-Shop
Freddie, Manager, X2-Shop
Teddy, Salesman, X2-Shop
Sean, Manager, X2-Shop
</code></pre>
<p>What i want is, to know the best Django way to fire
a group_by query to my db, as like,</p>
<pre><code>Members.objects.all().group_by('designation')
</code></pre>
<p>Which doesn't work of course.
I know we can do some tricks on "django/db/models/query.py",
but i am just curious to know how to do it without patching.</p>
| 161
|
2009-03-10T10:10:30Z
| 33,678,300
|
<p><strong>Django does not support free group by queries</strong>. I learned it in the very bad way. ORM is not designed to support stuff like what you want to do, without using custom SQL. You are limited to:</p>
<ul>
<li>RAW sql (i.e. MyModel.objects.raw())</li>
<li><code>cr.execute</code> sentences (and a hand-made parsing of the result).</li>
<li><code>.annotate()</code> (the group by sentences are performed in the child model for .annotate(), in examples like aggregating lines_count=Count('lines'))).</li>
</ul>
<p>Over a queryset <code>qs</code> you can call <code>qs.query.group_by = ['field1', 'field2', ...]</code> but it is risky if you don't know what query are you editing and have no guarantee that it will work and not break internals of the QuerySet object. Besides, it is an internal (undocumented) API you should not access directly without risking the code not being anymore compatible with future Django versions.</p>
| 0
|
2015-11-12T18:06:20Z
|
[
"python",
"django"
] |
How to query as GROUP BY in django?
| 629,551
|
<p>I query a model, </p>
<pre><code>Members.objects.all()
</code></pre>
<p>and it returns say</p>
<pre><code>Eric, Salesman, X-Shop
Freddie, Manager, X2-Shop
Teddy, Salesman, X2-Shop
Sean, Manager, X2-Shop
</code></pre>
<p>What i want is, to know the best Django way to fire
a group_by query to my db, as like,</p>
<pre><code>Members.objects.all().group_by('designation')
</code></pre>
<p>Which doesn't work of course.
I know we can do some tricks on "django/db/models/query.py",
but i am just curious to know how to do it without patching.</p>
| 161
|
2009-03-10T10:10:30Z
| 39,537,917
|
<p>You can get the equivalent of a group by using Django's <code>order_by</code> query and python's built-in <a href="https://docs.python.org/2/library/itertools.html#itertools.groupby" rel="nofollow"><code>itertools.groupby</code></a> function.</p>
<pre><code>import itertools
members_queryset = Members.objects.order_by('designation')
grouped_members_iterator = itertools.groupby(members_queryset, lambda member: member.designation)
grouped_members = { designation: list(members_iterator) for designation, members_iterator in members_grouped_by_designation_iterator }
</code></pre>
<p>As you can see, <code>groupby</code> can be tricky to work with. The iterable passed into <code>groupby</code> must already be ordered. It also returns an iterable of <code>key, iterable)</code> instead of, for example, a <code>dict</code>. This is nice for flexibility and performance - you never have to store things in memory that you don't need, can skip keys you don't need, and can iterate through the group without realizing them in memory as well.</p>
<p>In the example above, we use a <a href="https://docs.python.org/2/tutorial/datastructures.html#dictionaries" rel="nofollow">dictionary comprehension</a> to iterate through the group by, and cast the iterable of members for that designation to a <code>list</code> to get a fully realized grouping in memory.</p>
<p>Remember that the Django queries will be realized in memory when passed to <code>itertools.group_by</code>. To minimize memory try using Django's <a href="https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.iterator" rel="nofollow"><code>QuerySet.iterator</code></a> method. This can be a drop in replacement, though behavior varies by database and should definitely be researched before using:</p>
<pre><code>members_queryset_iterator = Members.objects.order_by('designation').iterator()
</code></pre>
| 1
|
2016-09-16T18:25:19Z
|
[
"python",
"django"
] |
How to query as GROUP BY in django?
| 629,551
|
<p>I query a model, </p>
<pre><code>Members.objects.all()
</code></pre>
<p>and it returns say</p>
<pre><code>Eric, Salesman, X-Shop
Freddie, Manager, X2-Shop
Teddy, Salesman, X2-Shop
Sean, Manager, X2-Shop
</code></pre>
<p>What i want is, to know the best Django way to fire
a group_by query to my db, as like,</p>
<pre><code>Members.objects.all().group_by('designation')
</code></pre>
<p>Which doesn't work of course.
I know we can do some tricks on "django/db/models/query.py",
but i am just curious to know how to do it without patching.</p>
| 161
|
2009-03-10T10:10:30Z
| 39,774,497
|
<p>There is module that allows you to group Django models and still work with a QuerySet in the result: <a href="https://github.com/kako-nawao/django-group-by" rel="nofollow">https://github.com/kako-nawao/django-group-by</a></p>
<p>For example:</p>
<pre><code>from django_group_by import GroupByMixin
class BookQuerySet(QuerySet, GroupByMixin):
pass
class Book(Model):
title = TextField(...)
author = ForeignKey(User, ...)
shop = ForeignKey(Shop, ...)
price = DecimalField(...)
</code></pre>
<hr>
<pre><code>class GroupedBookListView(PaginationMixin, ListView):
template_name = 'book/books.html'
model = Book
paginate_by = 100
def get_queryset(self):
return Book.objects.group_by('title', 'author').annotate(
shop_count=Count('shop'), price_avg=Avg('price')).order_by(
'name', 'author').distinct()
def get_context_data(self, **kwargs):
return super().get_context_data(total_count=self.get_queryset().count(), **kwargs)
</code></pre>
<p>'book/books.html'</p>
<pre><code><ul>
{% for book in object_list %}
<li>
<h2>{{ book.title }}</td>
<p>{{ book.author.last_name }}, {{ book.author.first_name }}</p>
<p>{{ book.shop_count }}</p>
<p>{{ book.price_avg }}</p>
</li>
{% endfor %}
</ul>
</code></pre>
<p>The difference to the <code>annotate</code>/<code>aggregate</code> basic Django queries is the use of the attributes of a related field, e.g. <code>book.author.last_name</code>.</p>
<p>If you need the PKs of the instances that have been grouped together, add the following annotation:</p>
<pre><code>.annotate(pks=ArrayAgg('id'))
</code></pre>
<p>NOTE: <code>ArrayAgg</code> is a Postgres specific function, available from Django 1.9 onwards: <a href="https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/aggregates/#arrayagg" rel="nofollow">https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/aggregates/#arrayagg</a> </p>
| 0
|
2016-09-29T15:33:31Z
|
[
"python",
"django"
] |
Deploying Google Analytics With Django
| 629,696
|
<p>We're about to deploy a new Django website, and we want to use Google Analytics to keep track of traffic on the site. However, we don't want all of the hits on development instances to contribute to the Google Analytics statistics.</p>
<p>There are a few ways we could deal with this:</p>
<ul>
<li>have a configuration option in settings.py which the base template uses to decide whether or not to include the appropriate <code><script></code> elements,</li>
<li>maintain a branch which we pull into before deploying to the production server, which we ensure includes the <code><script></code> elements,</li>
<li>do something with Google Analytics to block hits to 127.0.0.1 or localhost, or</li>
<li>something else.</li>
</ul>
<p>The first option seems the most sensible, but I'm not sure if it is. For example, would we have to start passing a <code>google_analytics</code> variable into all of our views?</p>
<p>What are your thoughts?</p>
| 23
|
2009-03-10T11:09:57Z
| 629,715
|
<p>First, create a way to have your development and production servers pull settings from different files, say dev.py and prod.py. There are lots of ways to do this.</p>
<p>Then, create a setting, <code>GOOGLE_ANALYTICS_KEY</code>. In dev.py set it to the empty string. In prod.py, set it to your key, something like "UA-124465-1". Create a <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/#writing-your-own-context-processors">context processor</a> to add this setting to all your template contexts, either as <code>GOOGLE_ANALYTICS_KEY</code>, or just go ahead and add your settings module. Then, in your template, use it to conditionally include your analytics code:</p>
<pre><code>{% if settings.GOOGLE_ANALYTICS_KEY %}
<script> blah blah {{settings.GOOGLE_ANALYTICS_KEY}} blah blah </script>
{% endif %}
</code></pre>
| 34
|
2009-03-10T11:17:08Z
|
[
"python",
"django",
"deployment",
"google-analytics"
] |
Deploying Google Analytics With Django
| 629,696
|
<p>We're about to deploy a new Django website, and we want to use Google Analytics to keep track of traffic on the site. However, we don't want all of the hits on development instances to contribute to the Google Analytics statistics.</p>
<p>There are a few ways we could deal with this:</p>
<ul>
<li>have a configuration option in settings.py which the base template uses to decide whether or not to include the appropriate <code><script></code> elements,</li>
<li>maintain a branch which we pull into before deploying to the production server, which we ensure includes the <code><script></code> elements,</li>
<li>do something with Google Analytics to block hits to 127.0.0.1 or localhost, or</li>
<li>something else.</li>
</ul>
<p>The first option seems the most sensible, but I'm not sure if it is. For example, would we have to start passing a <code>google_analytics</code> variable into all of our views?</p>
<p>What are your thoughts?</p>
| 23
|
2009-03-10T11:09:57Z
| 629,720
|
<p>You have template context processors that can be used to pass values to all templates without updating all your views.</p>
<p><a href="http://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/settings/#template-context-processors</a></p>
| 0
|
2009-03-10T11:18:58Z
|
[
"python",
"django",
"deployment",
"google-analytics"
] |
Deploying Google Analytics With Django
| 629,696
|
<p>We're about to deploy a new Django website, and we want to use Google Analytics to keep track of traffic on the site. However, we don't want all of the hits on development instances to contribute to the Google Analytics statistics.</p>
<p>There are a few ways we could deal with this:</p>
<ul>
<li>have a configuration option in settings.py which the base template uses to decide whether or not to include the appropriate <code><script></code> elements,</li>
<li>maintain a branch which we pull into before deploying to the production server, which we ensure includes the <code><script></code> elements,</li>
<li>do something with Google Analytics to block hits to 127.0.0.1 or localhost, or</li>
<li>something else.</li>
</ul>
<p>The first option seems the most sensible, but I'm not sure if it is. For example, would we have to start passing a <code>google_analytics</code> variable into all of our views?</p>
<p>What are your thoughts?</p>
| 23
|
2009-03-10T11:09:57Z
| 629,888
|
<p>I mostly agree with Ned, although I have a single setting called IS_LIVE_SITE which toggles analytics code, adverts and a few other things. This way I can keep all the keys in subversion (as it is a pain to look them up) and still toggle them on or off easily.</p>
| 2
|
2009-03-10T12:19:36Z
|
[
"python",
"django",
"deployment",
"google-analytics"
] |
Deploying Google Analytics With Django
| 629,696
|
<p>We're about to deploy a new Django website, and we want to use Google Analytics to keep track of traffic on the site. However, we don't want all of the hits on development instances to contribute to the Google Analytics statistics.</p>
<p>There are a few ways we could deal with this:</p>
<ul>
<li>have a configuration option in settings.py which the base template uses to decide whether or not to include the appropriate <code><script></code> elements,</li>
<li>maintain a branch which we pull into before deploying to the production server, which we ensure includes the <code><script></code> elements,</li>
<li>do something with Google Analytics to block hits to 127.0.0.1 or localhost, or</li>
<li>something else.</li>
</ul>
<p>The first option seems the most sensible, but I'm not sure if it is. For example, would we have to start passing a <code>google_analytics</code> variable into all of our views?</p>
<p>What are your thoughts?</p>
| 23
|
2009-03-10T11:09:57Z
| 633,029
|
<p>Instead of including the script tag directly in your html, just change the analytics javascript so it only runs if the href does not contain your prod site's name. This will work without any extra configuration.</p>
| 1
|
2009-03-11T01:48:06Z
|
[
"python",
"django",
"deployment",
"google-analytics"
] |
Deploying Google Analytics With Django
| 629,696
|
<p>We're about to deploy a new Django website, and we want to use Google Analytics to keep track of traffic on the site. However, we don't want all of the hits on development instances to contribute to the Google Analytics statistics.</p>
<p>There are a few ways we could deal with this:</p>
<ul>
<li>have a configuration option in settings.py which the base template uses to decide whether or not to include the appropriate <code><script></code> elements,</li>
<li>maintain a branch which we pull into before deploying to the production server, which we ensure includes the <code><script></code> elements,</li>
<li>do something with Google Analytics to block hits to 127.0.0.1 or localhost, or</li>
<li>something else.</li>
</ul>
<p>The first option seems the most sensible, but I'm not sure if it is. For example, would we have to start passing a <code>google_analytics</code> variable into all of our views?</p>
<p>What are your thoughts?</p>
| 23
|
2009-03-10T11:09:57Z
| 1,433,970
|
<p>My solution takes a similar approach to Ned's preferred answer, but separates the analytics code into its own template. I prefer this, so I can just copy the template from project to project.</p>
<p>Here's a snippet from my context_processor file:</p>
<pre><code>from django.conf import settings
from django.template.loader import render_to_string
def analytics(request):
"""
Returns analytics code.
"""
if not settings.DEBUG:
return { 'analytics_code': render_to_string("analytics/analytics.html", { 'google_analytics_key: settings.GOOGLE_ANALYTICS_KEY }) }
else:
return { 'analytics_code': "" }
</code></pre>
<p>Of course you'll need to tell Django to include this in your context. In in your settings.py file, include:</p>
<pre><code>TEMPLATE_CONTEXT_PROCESSORS = (
...
"context_processors.analytics",
)
</code></pre>
<p>I have it set up to include the analytics code only when DEBUG is set to False, but you may prefer to key it off something else, perhaps a new setting altogether. I think DEBUG is a good default since it supposes you don't want to track any hits while debugging/developing.</p>
<p>Create a setting with your Google Analytics Key:</p>
<pre><code>GOOGLE_ANALYTICS_KEY = "UA-1234567-8"
</code></pre>
<p>Create a template called: "analytics/analytics.html" that includes something like this:</p>
<pre><code><script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("{{ google_analytics_key }}");
pageTracker._trackPageview();
} catch(err) {}</script>
</code></pre>
<p>Finally, just before the closing tag in your base.html template, add this:</p>
<pre><code>{{ analytics_code }}
</code></pre>
<p>Now your analytics code will be included only when DEBUG=False. Otherwise, nothing will be included.</p>
| 5
|
2009-09-16T16:12:53Z
|
[
"python",
"django",
"deployment",
"google-analytics"
] |
Deploying Google Analytics With Django
| 629,696
|
<p>We're about to deploy a new Django website, and we want to use Google Analytics to keep track of traffic on the site. However, we don't want all of the hits on development instances to contribute to the Google Analytics statistics.</p>
<p>There are a few ways we could deal with this:</p>
<ul>
<li>have a configuration option in settings.py which the base template uses to decide whether or not to include the appropriate <code><script></code> elements,</li>
<li>maintain a branch which we pull into before deploying to the production server, which we ensure includes the <code><script></code> elements,</li>
<li>do something with Google Analytics to block hits to 127.0.0.1 or localhost, or</li>
<li>something else.</li>
</ul>
<p>The first option seems the most sensible, but I'm not sure if it is. For example, would we have to start passing a <code>google_analytics</code> variable into all of our views?</p>
<p>What are your thoughts?</p>
| 23
|
2009-03-10T11:09:57Z
| 1,559,982
|
<p>A little late to the party, but there's a reusable Django app called <a href="http://github.com/montylounge/django-google-analytics">django-google-analytics</a>. The easiest way to use it is:</p>
<ol>
<li>Add the <code>google_analytics</code> application to your <code>INSTALLED_APPS</code> section of your <code>settings.py</code>.</li>
<li>In your base template, usually a <code>base.html</code>, insert this tag at the very top: <code>{% load analytics %}</code></li>
<li>In the same template, insert the following code right before the closing body tag: <code>{% analytics "UA-xxxxxx-x" %}</code> the <code>UA-xxxxxx-x</code> is a unique Google Analytics code for your domain.</li>
</ol>
| 10
|
2009-10-13T12:45:30Z
|
[
"python",
"django",
"deployment",
"google-analytics"
] |
Deploying Google Analytics With Django
| 629,696
|
<p>We're about to deploy a new Django website, and we want to use Google Analytics to keep track of traffic on the site. However, we don't want all of the hits on development instances to contribute to the Google Analytics statistics.</p>
<p>There are a few ways we could deal with this:</p>
<ul>
<li>have a configuration option in settings.py which the base template uses to decide whether or not to include the appropriate <code><script></code> elements,</li>
<li>maintain a branch which we pull into before deploying to the production server, which we ensure includes the <code><script></code> elements,</li>
<li>do something with Google Analytics to block hits to 127.0.0.1 or localhost, or</li>
<li>something else.</li>
</ul>
<p>The first option seems the most sensible, but I'm not sure if it is. For example, would we have to start passing a <code>google_analytics</code> variable into all of our views?</p>
<p>What are your thoughts?</p>
| 23
|
2009-03-10T11:09:57Z
| 11,400,347
|
<p>All of these other solutions may work, but they are all overkill now because you can easily set up a filter in Google Analytics to filter out all traffic that is not coming from your production website or websites. See <a href="http://support.google.com/analytics/bin/answer.py?hl=en&answer=1034823" rel="nofollow">Create/Manage Profile</a> Filters in the GA Help. A solution with no code just makes everybody's life easier.</p>
<p><strong>Note</strong>: there are two caveats</p>
<ol>
<li>this doesn't work with realtime filtering, because no filters are applied to realtime (as of July 2012--check their documents)</li>
<li>you have to be an admin with the Google Analytics account to set this up</li>
</ol>
| 4
|
2012-07-09T17:49:45Z
|
[
"python",
"django",
"deployment",
"google-analytics"
] |
Deploying Google Analytics With Django
| 629,696
|
<p>We're about to deploy a new Django website, and we want to use Google Analytics to keep track of traffic on the site. However, we don't want all of the hits on development instances to contribute to the Google Analytics statistics.</p>
<p>There are a few ways we could deal with this:</p>
<ul>
<li>have a configuration option in settings.py which the base template uses to decide whether or not to include the appropriate <code><script></code> elements,</li>
<li>maintain a branch which we pull into before deploying to the production server, which we ensure includes the <code><script></code> elements,</li>
<li>do something with Google Analytics to block hits to 127.0.0.1 or localhost, or</li>
<li>something else.</li>
</ul>
<p>The first option seems the most sensible, but I'm not sure if it is. For example, would we have to start passing a <code>google_analytics</code> variable into all of our views?</p>
<p>What are your thoughts?</p>
| 23
|
2009-03-10T11:09:57Z
| 16,115,699
|
<p>Here's the dead simple way that I solved it:</p>
<p>Create an app in your project called 'utils' if you haven't already. See <a href="http://ygamretuta.me/2011/03/08/django-creating-a-custom-template-context-processor/" rel="nofollow">these directions</a>.</p>
<p>However, follow this approach to include all global context processers in addition to the project settings. It's seems to be a better practice. Here are the <a href="http://blog.madpython.com/2010/04/07/django-context-processors-best-practice/" rel="nofollow">instructions</a>.</p>
<p>So, after you create your 'utils' app, create a a file called context_processors.py in /utils that looks like this:</p>
<pre><code>from django.conf import settings
def googleanalytics(request):
return {
'google_tracking_id' : settings.GOOGLE_TRACKING_ID,
}
</code></pre>
<p>In you settings.py file, add this:</p>
<pre><code>import django.conf.global_settings as DEFAULT_SETTINGS
TEMPLATE_CONTEXT_PROCESSORS = DEFAULT_SETTINGS.TEMPLATE_CONTEXT_PROCESSORS + (
'utils.context_processors.googleanalytics',
</code></pre>
<p>)</p>
<p>Hope this helps!</p>
| 0
|
2013-04-20T01:51:04Z
|
[
"python",
"django",
"deployment",
"google-analytics"
] |
Deploying Google Analytics With Django
| 629,696
|
<p>We're about to deploy a new Django website, and we want to use Google Analytics to keep track of traffic on the site. However, we don't want all of the hits on development instances to contribute to the Google Analytics statistics.</p>
<p>There are a few ways we could deal with this:</p>
<ul>
<li>have a configuration option in settings.py which the base template uses to decide whether or not to include the appropriate <code><script></code> elements,</li>
<li>maintain a branch which we pull into before deploying to the production server, which we ensure includes the <code><script></code> elements,</li>
<li>do something with Google Analytics to block hits to 127.0.0.1 or localhost, or</li>
<li>something else.</li>
</ul>
<p>The first option seems the most sensible, but I'm not sure if it is. For example, would we have to start passing a <code>google_analytics</code> variable into all of our views?</p>
<p>What are your thoughts?</p>
| 23
|
2009-03-10T11:09:57Z
| 20,730,513
|
<p>Another simple way.
In <code>settings.py</code>ï¼Check <code>debug</code> is <code>True</code>, then add:</p>
<pre><code>INTERNAL_IPS = (
'127.0.0.1',
'localhost',
)
</code></pre>
<p>Then you can use things in your template like this:</p>
<pre><code>{% if not debug %}
<script> blah blah </script>
{% endif %}
</code></pre>
<p>If want to change to production, set <code>debug</code> to <code>False</code>.</p>
<p>Ref:
<a href="http://www.djangobook.com/en/2.0/chapter09.html" rel="nofollow">http://www.djangobook.com/en/2.0/chapter09.html</a></p>
| 2
|
2013-12-22T14:36:12Z
|
[
"python",
"django",
"deployment",
"google-analytics"
] |
Why avoid CGI for Python with LAMP hosting?
| 629,919
|
<p>I have been using PHP for years. Lately I've come across numerous forum posts stating that <strong>PHP is outdated</strong>, that modern programming languages are easier, more secure, etc. etc.</p>
<p>So, I decided to <strong>start learning Python</strong>. Since I'm used to using PHP, I just started building pages by uploading an .htaccess file with:</p>
<pre><code>addtype text/html py
addhandler cgi-script .py
</code></pre>
<p>Then, my sample pages look like:</p>
<pre>
#!/usr/bin/python
print "content-type: text/html\n\n"
print "html tags, more stuff, etc."
</pre>
<p>This works fine. But, I came across a comment in a post that said that <strong>CGI isn't the best way to use Python</strong>. Of course, it didn't mention what <em>is</em> the best way.</p>
<p><strong>Why is it that using CGI is not the best way to use Python? What is the alternative?</strong></p>
<p>Is there some <strong>totally other way</strong> to set up a simple Python site? Is there some completely different paradigm I should be looking at outside of .htaccess and .py files?</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/43709/pros-and-cons-of-different-approaches-to-web-programming-in-python">Pros and Cons of different approaches to web programming in Python</a></li>
<li><a href="http://stackoverflow.com/questions/68986/whats-a-good-lightweight-python-mvc-framework">Whatâs a good lightweight Python MVC framework?</a> (esp., <a href="http://stackoverflow.com/questions/68986/whats-a-good-lightweight-python-mvc-framework/83263#83263">@Kevin Dangoor's answer</a>)</li>
<li><a href="http://stackoverflow.com/questions/596729/how-do-i-use-python-for-web-development-without-relying-on-a-framework">How do I use python for web development without relying on a framework?</a></li>
<li><a href="http://stackoverflow.com/questions/490210/python-web-framework-not-app-framework-or-cms-framework">Python Web Framework - Not App Framework or CMS Framework</a></li>
<li><a href="http://stackoverflow.com/questions/581038/python-web-programming">Python web programming</a></li>
</ul>
| 22
|
2009-03-10T12:32:06Z
| 629,929
|
<p><a href="http://code.djangoproject.com/wiki/django%5Fapache%5Fand%5Fmod%5Fwsgi" rel="nofollow"><strong>mod_wsgi</strong></a> is the proper alternative. It is preferable over CGI in almost all aspects.</p>
| 3
|
2009-03-10T12:35:41Z
|
[
"php",
"python",
".htaccess",
"cgi"
] |
Why avoid CGI for Python with LAMP hosting?
| 629,919
|
<p>I have been using PHP for years. Lately I've come across numerous forum posts stating that <strong>PHP is outdated</strong>, that modern programming languages are easier, more secure, etc. etc.</p>
<p>So, I decided to <strong>start learning Python</strong>. Since I'm used to using PHP, I just started building pages by uploading an .htaccess file with:</p>
<pre><code>addtype text/html py
addhandler cgi-script .py
</code></pre>
<p>Then, my sample pages look like:</p>
<pre>
#!/usr/bin/python
print "content-type: text/html\n\n"
print "html tags, more stuff, etc."
</pre>
<p>This works fine. But, I came across a comment in a post that said that <strong>CGI isn't the best way to use Python</strong>. Of course, it didn't mention what <em>is</em> the best way.</p>
<p><strong>Why is it that using CGI is not the best way to use Python? What is the alternative?</strong></p>
<p>Is there some <strong>totally other way</strong> to set up a simple Python site? Is there some completely different paradigm I should be looking at outside of .htaccess and .py files?</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/43709/pros-and-cons-of-different-approaches-to-web-programming-in-python">Pros and Cons of different approaches to web programming in Python</a></li>
<li><a href="http://stackoverflow.com/questions/68986/whats-a-good-lightweight-python-mvc-framework">Whatâs a good lightweight Python MVC framework?</a> (esp., <a href="http://stackoverflow.com/questions/68986/whats-a-good-lightweight-python-mvc-framework/83263#83263">@Kevin Dangoor's answer</a>)</li>
<li><a href="http://stackoverflow.com/questions/596729/how-do-i-use-python-for-web-development-without-relying-on-a-framework">How do I use python for web development without relying on a framework?</a></li>
<li><a href="http://stackoverflow.com/questions/490210/python-web-framework-not-app-framework-or-cms-framework">Python Web Framework - Not App Framework or CMS Framework</a></li>
<li><a href="http://stackoverflow.com/questions/581038/python-web-programming">Python web programming</a></li>
</ul>
| 22
|
2009-03-10T12:32:06Z
| 629,930
|
<p>Classic CGI isn't the best way to use anything at all. With classic CGI server has to <strong>spawn a new process for every request</strong>.</p>
<p>As for Python, you have few alternatives:</p>
<ul>
<li><a href="http://code.google.com/p/modwsgi/" rel="nofollow"><code>mod_wsgi</code></a></li>
<li><a href="http://modpython.org/" rel="nofollow"><code>mod_python</code></a></li>
<li><a href="http://pypi.python.org/pypi/python-fastcgi" rel="nofollow">fastcgi</a></li>
<li>standalone Python web server (<a href="http://docs.python.org/library/simplehttpserver.html" rel="nofollow">built-in</a>, <a href="http://www.cherrypy.org/" rel="nofollow">CherryPy</a>, <a href="http://trac.edgewall.org/wiki/TracStandalone" rel="nofollow">Tracd</a> )</li>
<li>standalone Python web server on non-standard port and <a href="http://httpd.apache.org/docs/2.2/mod/mod%5Fproxy.html" rel="nofollow"><code>mod_proxy</code></a> in Apache</li>
</ul>
| 9
|
2009-03-10T12:35:50Z
|
[
"php",
"python",
".htaccess",
"cgi"
] |
Why avoid CGI for Python with LAMP hosting?
| 629,919
|
<p>I have been using PHP for years. Lately I've come across numerous forum posts stating that <strong>PHP is outdated</strong>, that modern programming languages are easier, more secure, etc. etc.</p>
<p>So, I decided to <strong>start learning Python</strong>. Since I'm used to using PHP, I just started building pages by uploading an .htaccess file with:</p>
<pre><code>addtype text/html py
addhandler cgi-script .py
</code></pre>
<p>Then, my sample pages look like:</p>
<pre>
#!/usr/bin/python
print "content-type: text/html\n\n"
print "html tags, more stuff, etc."
</pre>
<p>This works fine. But, I came across a comment in a post that said that <strong>CGI isn't the best way to use Python</strong>. Of course, it didn't mention what <em>is</em> the best way.</p>
<p><strong>Why is it that using CGI is not the best way to use Python? What is the alternative?</strong></p>
<p>Is there some <strong>totally other way</strong> to set up a simple Python site? Is there some completely different paradigm I should be looking at outside of .htaccess and .py files?</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/43709/pros-and-cons-of-different-approaches-to-web-programming-in-python">Pros and Cons of different approaches to web programming in Python</a></li>
<li><a href="http://stackoverflow.com/questions/68986/whats-a-good-lightweight-python-mvc-framework">Whatâs a good lightweight Python MVC framework?</a> (esp., <a href="http://stackoverflow.com/questions/68986/whats-a-good-lightweight-python-mvc-framework/83263#83263">@Kevin Dangoor's answer</a>)</li>
<li><a href="http://stackoverflow.com/questions/596729/how-do-i-use-python-for-web-development-without-relying-on-a-framework">How do I use python for web development without relying on a framework?</a></li>
<li><a href="http://stackoverflow.com/questions/490210/python-web-framework-not-app-framework-or-cms-framework">Python Web Framework - Not App Framework or CMS Framework</a></li>
<li><a href="http://stackoverflow.com/questions/581038/python-web-programming">Python web programming</a></li>
</ul>
| 22
|
2009-03-10T12:32:06Z
| 629,940
|
<p>Really it's just an efficiency thing - CGI spawns an entire new process for every request, which is quite heavyweight for what it does.</p>
<p>PHP can be run through CGI as well, but mod_php embeds the interpreter within apache.
There's a <a href="http://www.modpython.org/" rel="nofollow">mod_python</a> which does the same job, and <a href="http://code.google.com/p/modwsgi/" rel="nofollow">mod_wsgi</a> as Yuval says.</p>
| 3
|
2009-03-10T12:38:39Z
|
[
"php",
"python",
".htaccess",
"cgi"
] |
Why avoid CGI for Python with LAMP hosting?
| 629,919
|
<p>I have been using PHP for years. Lately I've come across numerous forum posts stating that <strong>PHP is outdated</strong>, that modern programming languages are easier, more secure, etc. etc.</p>
<p>So, I decided to <strong>start learning Python</strong>. Since I'm used to using PHP, I just started building pages by uploading an .htaccess file with:</p>
<pre><code>addtype text/html py
addhandler cgi-script .py
</code></pre>
<p>Then, my sample pages look like:</p>
<pre>
#!/usr/bin/python
print "content-type: text/html\n\n"
print "html tags, more stuff, etc."
</pre>
<p>This works fine. But, I came across a comment in a post that said that <strong>CGI isn't the best way to use Python</strong>. Of course, it didn't mention what <em>is</em> the best way.</p>
<p><strong>Why is it that using CGI is not the best way to use Python? What is the alternative?</strong></p>
<p>Is there some <strong>totally other way</strong> to set up a simple Python site? Is there some completely different paradigm I should be looking at outside of .htaccess and .py files?</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/43709/pros-and-cons-of-different-approaches-to-web-programming-in-python">Pros and Cons of different approaches to web programming in Python</a></li>
<li><a href="http://stackoverflow.com/questions/68986/whats-a-good-lightweight-python-mvc-framework">Whatâs a good lightweight Python MVC framework?</a> (esp., <a href="http://stackoverflow.com/questions/68986/whats-a-good-lightweight-python-mvc-framework/83263#83263">@Kevin Dangoor's answer</a>)</li>
<li><a href="http://stackoverflow.com/questions/596729/how-do-i-use-python-for-web-development-without-relying-on-a-framework">How do I use python for web development without relying on a framework?</a></li>
<li><a href="http://stackoverflow.com/questions/490210/python-web-framework-not-app-framework-or-cms-framework">Python Web Framework - Not App Framework or CMS Framework</a></li>
<li><a href="http://stackoverflow.com/questions/581038/python-web-programming">Python web programming</a></li>
</ul>
| 22
|
2009-03-10T12:32:06Z
| 629,960
|
<p>Aside from the suggestions others make, you should really consider using a framework of some kind. You can and should be using <a href="http://www.fastcgi.com/" rel="nofollow">FastCGI</a>, mod_python, or mod_wsgi, but they weren't really intended for you to write code directly against. Might I suggest one of the following?</p>
<ul>
<li><a href="http://www.djangoproject.com" rel="nofollow">django</a> (my favorite for practical applications)</li>
<li><a href="http://pylonshq.com/" rel="nofollow">pylons</a></li>
<li><a href="http://www.cherrypy.org/" rel="nofollow">cherrypy</a> (my favorite for not-so-practical applications)</li>
<li><a href="http://webpy.org/" rel="nofollow">web.py</a></li>
</ul>
| 1
|
2009-03-10T12:42:36Z
|
[
"php",
"python",
".htaccess",
"cgi"
] |
Why avoid CGI for Python with LAMP hosting?
| 629,919
|
<p>I have been using PHP for years. Lately I've come across numerous forum posts stating that <strong>PHP is outdated</strong>, that modern programming languages are easier, more secure, etc. etc.</p>
<p>So, I decided to <strong>start learning Python</strong>. Since I'm used to using PHP, I just started building pages by uploading an .htaccess file with:</p>
<pre><code>addtype text/html py
addhandler cgi-script .py
</code></pre>
<p>Then, my sample pages look like:</p>
<pre>
#!/usr/bin/python
print "content-type: text/html\n\n"
print "html tags, more stuff, etc."
</pre>
<p>This works fine. But, I came across a comment in a post that said that <strong>CGI isn't the best way to use Python</strong>. Of course, it didn't mention what <em>is</em> the best way.</p>
<p><strong>Why is it that using CGI is not the best way to use Python? What is the alternative?</strong></p>
<p>Is there some <strong>totally other way</strong> to set up a simple Python site? Is there some completely different paradigm I should be looking at outside of .htaccess and .py files?</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/43709/pros-and-cons-of-different-approaches-to-web-programming-in-python">Pros and Cons of different approaches to web programming in Python</a></li>
<li><a href="http://stackoverflow.com/questions/68986/whats-a-good-lightweight-python-mvc-framework">Whatâs a good lightweight Python MVC framework?</a> (esp., <a href="http://stackoverflow.com/questions/68986/whats-a-good-lightweight-python-mvc-framework/83263#83263">@Kevin Dangoor's answer</a>)</li>
<li><a href="http://stackoverflow.com/questions/596729/how-do-i-use-python-for-web-development-without-relying-on-a-framework">How do I use python for web development without relying on a framework?</a></li>
<li><a href="http://stackoverflow.com/questions/490210/python-web-framework-not-app-framework-or-cms-framework">Python Web Framework - Not App Framework or CMS Framework</a></li>
<li><a href="http://stackoverflow.com/questions/581038/python-web-programming">Python web programming</a></li>
</ul>
| 22
|
2009-03-10T12:32:06Z
| 630,001
|
<p>There is a page in the Python documentation that describes the <a href="http://docs.python.org/howto/webservers.html" rel="nofollow">advantages and disadvantages of the various possibilities</a>.</p>
<p><strong>mod_python</strong></p>
<blockquote>
<p>(â¦) These are the reasons why mod_python should be avoided when writing new programs.</p>
</blockquote>
<p><strong>WSGI</strong></p>
<blockquote>
<p>The <em>Web Server Gateway Interface</em> or
WSGI for short is currently the best
possible way to Python web
programming. While it is great for
programmers writing frameworks, the
normal person does not need to get in
direct contact with it.</p>
</blockquote>
<p><strong>FastCGI and stuff</strong></p>
<blockquote>
<p>These days, FastCGI is never used directly.</p>
</blockquote>
| 2
|
2009-03-10T12:52:07Z
|
[
"php",
"python",
".htaccess",
"cgi"
] |
Why avoid CGI for Python with LAMP hosting?
| 629,919
|
<p>I have been using PHP for years. Lately I've come across numerous forum posts stating that <strong>PHP is outdated</strong>, that modern programming languages are easier, more secure, etc. etc.</p>
<p>So, I decided to <strong>start learning Python</strong>. Since I'm used to using PHP, I just started building pages by uploading an .htaccess file with:</p>
<pre><code>addtype text/html py
addhandler cgi-script .py
</code></pre>
<p>Then, my sample pages look like:</p>
<pre>
#!/usr/bin/python
print "content-type: text/html\n\n"
print "html tags, more stuff, etc."
</pre>
<p>This works fine. But, I came across a comment in a post that said that <strong>CGI isn't the best way to use Python</strong>. Of course, it didn't mention what <em>is</em> the best way.</p>
<p><strong>Why is it that using CGI is not the best way to use Python? What is the alternative?</strong></p>
<p>Is there some <strong>totally other way</strong> to set up a simple Python site? Is there some completely different paradigm I should be looking at outside of .htaccess and .py files?</p>
<h3>Related</h3>
<ul>
<li><a href="http://stackoverflow.com/questions/43709/pros-and-cons-of-different-approaches-to-web-programming-in-python">Pros and Cons of different approaches to web programming in Python</a></li>
<li><a href="http://stackoverflow.com/questions/68986/whats-a-good-lightweight-python-mvc-framework">Whatâs a good lightweight Python MVC framework?</a> (esp., <a href="http://stackoverflow.com/questions/68986/whats-a-good-lightweight-python-mvc-framework/83263#83263">@Kevin Dangoor's answer</a>)</li>
<li><a href="http://stackoverflow.com/questions/596729/how-do-i-use-python-for-web-development-without-relying-on-a-framework">How do I use python for web development without relying on a framework?</a></li>
<li><a href="http://stackoverflow.com/questions/490210/python-web-framework-not-app-framework-or-cms-framework">Python Web Framework - Not App Framework or CMS Framework</a></li>
<li><a href="http://stackoverflow.com/questions/581038/python-web-programming">Python web programming</a></li>
</ul>
| 22
|
2009-03-10T12:32:06Z
| 630,462
|
<blockquote>
<p>Why is it that using CGI is not the best way to use Python?</p>
</blockquote>
<p>I will stick up for CGI a little. It's good for development environments.</p>
<p>It's simple to wire up and you don't have to worry about module reloading problems. Naturally performance is terrible, but for dev you don't care.</p>
<p>Of course you should really be writing to the WSGI interface rather than CGI directly. You can then deploy through CGI using:</p>
<pre><code>wsgiref.handlers.CGIHandler().run(application)
</code></pre>
<p>and use the same application object to deploy through mod_wsgi other whatever other WSGI server you prefer in the production environment where speed matters (and the testing environment where you want it to be as close to production as possible).</p>
| 5
|
2009-03-10T14:27:20Z
|
[
"php",
"python",
".htaccess",
"cgi"
] |
BeautifulSoup gives me unicode+html symbols, rather than straight up unicode. Is this a bug or misunderstanding?
| 629,999
|
<p>I'm using BeautifulSoup to scrape a website. The website's page renders fine in my browser: </p>
<blockquote>
<p>Oxfam Internationalâs report entitled âOffside!
<a href="http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271">http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271</a></p>
</blockquote>
<p>In particular, the single and double quotes look fine. They look html symbols rather than ascii, though strangely when I view source in FF3 they appear to be normal ascii.</p>
<p>Unfortunately, when I scrape I get something like this</p>
<blockquote>
<p>u'Oxfam International\xe2â¬â¢s report
entitled \xe2â¬ÅOffside!</p>
</blockquote>
<p>oops, I mean this:</p>
<pre><code>u'Oxfam International\xe2â¬â¢s report entitled \xe2â¬ÅOffside!
</code></pre>
<p>The page's meta data indicates 'iso-88959-1' encoding. I've tried different encodings, played with unicode->ascii and html->ascii third party functions, and looked at the MS/iso-8859-1 discrepancy, but the fact of the matter is that ⢠has nothing to do with a single quote, and I can't seem to turn the unicode+htmlsymbol combo into the right ascii or html symbol--in my limited knowledge, which is why I'm seeking help.</p>
<p>I'd be happy with an ascii double quote, " or "</p>
<p>The problem the following is that I'm concerned there are other funny symbols decoded incorrectly. </p>
<pre><code>\xe2â¬â¢
</code></pre>
<p>Below is some python to reproduce what I'm seeing, followed by the things I've tried.</p>
<pre><code>import twill
from twill import get_browser
from twill.commands import go
from BeautifulSoup import BeautifulSoup as BSoup
url = 'http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271'
twill.commands.go(url)
soup = BSoup(twill.commands.get_browser().get_html())
ps = soup.body("p")
p = ps[52]
>>> p
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe2' in position 22: ordinal not in range(128)
>>> p.string
u'Oxfam International\xe2â¬â¢s report entitled \xe2â¬ÅOffside!<elided>\r\n'
</code></pre>
<p><a href="http://groups.google.com/group/comp.lang.python/browse%5Ffrm/thread/9b7bb3f621b4b8e4/3b00a890cf3a5e46?q=htmlentitydefs&rnum=3&hl=en#3b00a890cf3a5e46">http://groups.google.com/group/comp.lang.python/browse_frm/thread/9b7bb3f621b4b8e4/3b00a890cf3a5e46?q=htmlentitydefs&rnum=3&hl=en#3b00a890cf3a5e46</a></p>
<p><a href="http://www.fourmilab.ch/webtools/demoroniser/">http://www.fourmilab.ch/webtools/demoroniser/</a></p>
<p><a href="http://www.crummy.com/software/BeautifulSoup/documentation.html">http://www.crummy.com/software/BeautifulSoup/documentation.html</a></p>
<p><a href="http://www.cs.tut.fi/~jkorpela/www/windows-chars.html">http://www.cs.tut.fi/~jkorpela/www/windows-chars.html</a></p>
<pre><code>>>> AsciiDammit.asciiDammit(p.decode())
u'<p>Oxfam International\xe2â¬â¢s report entitled \xe2â¬ÅOffside!
>>> handle_html_entities(p.decode())
u'<p>Oxfam International\xe2\u20ac\u2122s report entitled \xe2\u20ac\u0153Offside!
>>> unicodedata.normalize('NFKC', p.decode()).encode('ascii','ignore')
'<p>Oxfam Internationalâ¬â¢s report entitled â¬ÅOffside!
>>> htmlStripEscapes(p.string)
u'Oxfam International\xe2TMs report entitled \xe2Offside!
</code></pre>
<p>EDIT:</p>
<p>I've tried using a different BS parser:</p>
<pre><code>import html5lib
bsoup_parser = html5lib.HTMLParser(tree=html5lib.treebuilders.getTreeBuilder("beautifulsoup"))
soup = bsoup_parser.parse(twill.commands.get_browser().get_html())
ps = soup.body("p")
ps[55].decode()
</code></pre>
<p>which gives me this</p>
<pre><code>u'<p>Oxfam International\xe2\u20ac\u2122s report entitled \xe2\u20ac\u0153Offside!
</code></pre>
<p>the best case decode seems to give me the same results:</p>
<pre><code>unicodedata.normalize('NFKC', p.decode()).encode('ascii','ignore')
'<p>Oxfam InternationalTMs report entitled Offside!
</code></pre>
<p>EDIT 2:</p>
<p>I am running Mac OS X 4 with FF 3.0.7 and Firebug</p>
<p>Python 2.5 (wow, can't believe I didn't state this from the beginning)</p>
| 5
|
2009-03-10T12:52:00Z
| 630,099
|
<p>That's one seriously messed up page, encoding-wise :-)</p>
<p>There's nothing really wrong with your approach at all. I would probably tend to do the conversion before passing it to BeautifulSoup, just because I'm persnickity:</p>
<pre><code>import urllib
html = urllib.urlopen('http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271').read()
h = html.decode('iso-8859-1')
soup = BeautifulSoup(h)
</code></pre>
<p>In this case, the page's meta tag is lying about the encoding. The page is actually in utf-8... Firefox's page info reveals the real encoding, and you can actually see this charset in the response headers returned by the server:</p>
<pre><code>curl -i http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271
HTTP/1.1 200 OK
Connection: close
Date: Tue, 10 Mar 2009 13:14:29 GMT
Server: Microsoft-IIS/6.0
X-Powered-By: ASP.NET
Set-Cookie: COMPANYID=271;path=/
Content-Language: en-US
Content-Type: text/html; charset=UTF-8
</code></pre>
<p>If you do the decode using 'utf-8', it will work for you (or, at least, is did for me):</p>
<pre><code>import urllib
html = urllib.urlopen('http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271').read()
h = html.decode('utf-8')
soup = BeautifulSoup(h)
ps = soup.body("p")
p = ps[52]
print p
</code></pre>
| 8
|
2009-03-10T13:15:41Z
|
[
"python",
"html",
"unicode",
"beautifulsoup"
] |
BeautifulSoup gives me unicode+html symbols, rather than straight up unicode. Is this a bug or misunderstanding?
| 629,999
|
<p>I'm using BeautifulSoup to scrape a website. The website's page renders fine in my browser: </p>
<blockquote>
<p>Oxfam Internationalâs report entitled âOffside!
<a href="http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271">http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271</a></p>
</blockquote>
<p>In particular, the single and double quotes look fine. They look html symbols rather than ascii, though strangely when I view source in FF3 they appear to be normal ascii.</p>
<p>Unfortunately, when I scrape I get something like this</p>
<blockquote>
<p>u'Oxfam International\xe2â¬â¢s report
entitled \xe2â¬ÅOffside!</p>
</blockquote>
<p>oops, I mean this:</p>
<pre><code>u'Oxfam International\xe2â¬â¢s report entitled \xe2â¬ÅOffside!
</code></pre>
<p>The page's meta data indicates 'iso-88959-1' encoding. I've tried different encodings, played with unicode->ascii and html->ascii third party functions, and looked at the MS/iso-8859-1 discrepancy, but the fact of the matter is that ⢠has nothing to do with a single quote, and I can't seem to turn the unicode+htmlsymbol combo into the right ascii or html symbol--in my limited knowledge, which is why I'm seeking help.</p>
<p>I'd be happy with an ascii double quote, " or "</p>
<p>The problem the following is that I'm concerned there are other funny symbols decoded incorrectly. </p>
<pre><code>\xe2â¬â¢
</code></pre>
<p>Below is some python to reproduce what I'm seeing, followed by the things I've tried.</p>
<pre><code>import twill
from twill import get_browser
from twill.commands import go
from BeautifulSoup import BeautifulSoup as BSoup
url = 'http://www.coopamerica.org/programs/responsibleshopper/company.cfm?id=271'
twill.commands.go(url)
soup = BSoup(twill.commands.get_browser().get_html())
ps = soup.body("p")
p = ps[52]
>>> p
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe2' in position 22: ordinal not in range(128)
>>> p.string
u'Oxfam International\xe2â¬â¢s report entitled \xe2â¬ÅOffside!<elided>\r\n'
</code></pre>
<p><a href="http://groups.google.com/group/comp.lang.python/browse%5Ffrm/thread/9b7bb3f621b4b8e4/3b00a890cf3a5e46?q=htmlentitydefs&rnum=3&hl=en#3b00a890cf3a5e46">http://groups.google.com/group/comp.lang.python/browse_frm/thread/9b7bb3f621b4b8e4/3b00a890cf3a5e46?q=htmlentitydefs&rnum=3&hl=en#3b00a890cf3a5e46</a></p>
<p><a href="http://www.fourmilab.ch/webtools/demoroniser/">http://www.fourmilab.ch/webtools/demoroniser/</a></p>
<p><a href="http://www.crummy.com/software/BeautifulSoup/documentation.html">http://www.crummy.com/software/BeautifulSoup/documentation.html</a></p>
<p><a href="http://www.cs.tut.fi/~jkorpela/www/windows-chars.html">http://www.cs.tut.fi/~jkorpela/www/windows-chars.html</a></p>
<pre><code>>>> AsciiDammit.asciiDammit(p.decode())
u'<p>Oxfam International\xe2â¬â¢s report entitled \xe2â¬ÅOffside!
>>> handle_html_entities(p.decode())
u'<p>Oxfam International\xe2\u20ac\u2122s report entitled \xe2\u20ac\u0153Offside!
>>> unicodedata.normalize('NFKC', p.decode()).encode('ascii','ignore')
'<p>Oxfam Internationalâ¬â¢s report entitled â¬ÅOffside!
>>> htmlStripEscapes(p.string)
u'Oxfam International\xe2TMs report entitled \xe2Offside!
</code></pre>
<p>EDIT:</p>
<p>I've tried using a different BS parser:</p>
<pre><code>import html5lib
bsoup_parser = html5lib.HTMLParser(tree=html5lib.treebuilders.getTreeBuilder("beautifulsoup"))
soup = bsoup_parser.parse(twill.commands.get_browser().get_html())
ps = soup.body("p")
ps[55].decode()
</code></pre>
<p>which gives me this</p>
<pre><code>u'<p>Oxfam International\xe2\u20ac\u2122s report entitled \xe2\u20ac\u0153Offside!
</code></pre>
<p>the best case decode seems to give me the same results:</p>
<pre><code>unicodedata.normalize('NFKC', p.decode()).encode('ascii','ignore')
'<p>Oxfam InternationalTMs report entitled Offside!
</code></pre>
<p>EDIT 2:</p>
<p>I am running Mac OS X 4 with FF 3.0.7 and Firebug</p>
<p>Python 2.5 (wow, can't believe I didn't state this from the beginning)</p>
| 5
|
2009-03-10T12:52:00Z
| 630,126
|
<p>It's actually UTF-8 misencoded as CP1252:</p>
<pre><code>>>> print u'Oxfam International\xe2â¬â¢s report entitled \xe2â¬ÅOffside!'.encode('cp1252').decode('utf8')
Oxfam Internationalâs report entitled âOffside!
</code></pre>
| 4
|
2009-03-10T13:21:42Z
|
[
"python",
"html",
"unicode",
"beautifulsoup"
] |
How can I use python's telnetlib to fetch data from a device for a fixed period of time?
| 630,217
|
<p>I'm connecting to a hardware device via telnet. That device is pretty simple in terms of I/O. So I submit a command to it, and after that the device pumps out data one line at a time, once per second. Each line just contains a number.</p>
<p>So my question is this: if I connect to this device using python's telnetlib, how can I fetch data for a fixed period of time (or a fixed number of lines of data)?</p>
<p>I've tried using all the various read_ commands, but they all seem to block indefinitely, apart from read_until, which I can't use as the output can't be used to determine when to stop.</p>
<p>(I'm running python 2.5 under Cygwin, btw).</p>
<p>Edit: Maybe the real question is, should I be using telnetlib at all for this, or should I just use the socket module?</p>
| 2
|
2009-03-10T13:41:54Z
| 630,253
|
<p>Read lines in a loop until you have either read the required number of lines or the time limit has been reached. However, it doesn't sound like you actual need a telnet library. Why not just use a simple TCP <a href="http://docs.python.org/library/socket.html" rel="nofollow">socket</a> for the connection? </p>
| 1
|
2009-03-10T13:49:49Z
|
[
"python",
"telnet"
] |
How can I use python's telnetlib to fetch data from a device for a fixed period of time?
| 630,217
|
<p>I'm connecting to a hardware device via telnet. That device is pretty simple in terms of I/O. So I submit a command to it, and after that the device pumps out data one line at a time, once per second. Each line just contains a number.</p>
<p>So my question is this: if I connect to this device using python's telnetlib, how can I fetch data for a fixed period of time (or a fixed number of lines of data)?</p>
<p>I've tried using all the various read_ commands, but they all seem to block indefinitely, apart from read_until, which I can't use as the output can't be used to determine when to stop.</p>
<p>(I'm running python 2.5 under Cygwin, btw).</p>
<p>Edit: Maybe the real question is, should I be using telnetlib at all for this, or should I just use the socket module?</p>
| 2
|
2009-03-10T13:41:54Z
| 630,257
|
<p>In my experience, most such devices use some prompt, in which case <a href="http://docs.python.org/library/telnetlib.html#telnetlib.Telnet.read%5Funtil" rel="nofollow"><code>Telnet.read_until()</code></a> is appropriate:</p>
<blockquote>
<p><code>Telnet.read_until(expected[, timeout])</code></p>
<p>Read until a given string, expected, is encountered or until timeout seconds have passed.
When no match is found, return whatever is available instead, possibly the empty string. Raise EOFError if the connection is closed and no cooked data is available.</p>
</blockquote>
<p>If no usable (repetitive) prompt is presented by the device, try <a href="http://docs.python.org/library/telnetlib.html#telnetlib.Telnet.read%5Fvery%5Feager" rel="nofollow"><code>Telnet.read_very_eager()</code></a>, or <code>Telnet.read_very_lazy()</code>:</p>
<blockquote>
<p><code>Telnet.read_very_eager()</code></p>
<p>Read everything that can be without blocking in I/O (eager).</p>
<p>Raise EOFError if connection closed and no cooked data available. Return '' if no cooked data available otherwise. Do not block unless in the midst of an IAC sequence.</p>
</blockquote>
| 2
|
2009-03-10T13:50:50Z
|
[
"python",
"telnet"
] |
How can I use python's telnetlib to fetch data from a device for a fixed period of time?
| 630,217
|
<p>I'm connecting to a hardware device via telnet. That device is pretty simple in terms of I/O. So I submit a command to it, and after that the device pumps out data one line at a time, once per second. Each line just contains a number.</p>
<p>So my question is this: if I connect to this device using python's telnetlib, how can I fetch data for a fixed period of time (or a fixed number of lines of data)?</p>
<p>I've tried using all the various read_ commands, but they all seem to block indefinitely, apart from read_until, which I can't use as the output can't be used to determine when to stop.</p>
<p>(I'm running python 2.5 under Cygwin, btw).</p>
<p>Edit: Maybe the real question is, should I be using telnetlib at all for this, or should I just use the socket module?</p>
| 2
|
2009-03-10T13:41:54Z
| 630,258
|
<p>From your description I'm not clear if you're using telnetlib because the device you're connecting to <em>requires terminal setup provided by telnet</em> or because it seemed like the right thing to do.</p>
<p>If the device is as simple as you describe--i.e. not negotiating terminal options on connection--have you considered the <a href="http://docs.python.org/library/asynchat.html" rel="nofollow">asynchat</a> module? It would be appropriate for the "send command, read lines" sort of IO pattern you are describing.</p>
<p>Alternatively, for something lower-level, you could use the <a href="http://docs.python.org/library/socket.html" rel="nofollow">socket</a> module to open the connection to the device and then sit in a timed loop and <code>read()</code> the incoming data. If the lines are newline-terminated it should be simple for you to identify each individual number. If you are concerned with blocking, stick this loop in its own thread.</p>
| 4
|
2009-03-10T13:51:22Z
|
[
"python",
"telnet"
] |
How can I use python's telnetlib to fetch data from a device for a fixed period of time?
| 630,217
|
<p>I'm connecting to a hardware device via telnet. That device is pretty simple in terms of I/O. So I submit a command to it, and after that the device pumps out data one line at a time, once per second. Each line just contains a number.</p>
<p>So my question is this: if I connect to this device using python's telnetlib, how can I fetch data for a fixed period of time (or a fixed number of lines of data)?</p>
<p>I've tried using all the various read_ commands, but they all seem to block indefinitely, apart from read_until, which I can't use as the output can't be used to determine when to stop.</p>
<p>(I'm running python 2.5 under Cygwin, btw).</p>
<p>Edit: Maybe the real question is, should I be using telnetlib at all for this, or should I just use the socket module?</p>
| 2
|
2009-03-10T13:41:54Z
| 630,260
|
<p>It sounds like blocking isn't really your problem, since you know that you'll only be blocking for a second. Why not do something like:</p>
<pre><code>lines_to_read = 10
for i in range(lines_to_read):
line = tel.read_until("\n")
</code></pre>
| 2
|
2009-03-10T13:52:11Z
|
[
"python",
"telnet"
] |
Is there any reasonable SSDP or DIDL Lib for java/groovy/python?
| 630,296
|
<p>For a future project I am looking for a library to handle SSDP communication and messages in DIDL-Lite xml dialect. Is there any reasonable implementation of java, groovy or python? </p>
<p>I don't like to use implementations of existing UPnP stacks like cybergarage or the frauenhofer UPnP stack because they are highly depending on these stacks.</p>
| 3
|
2009-03-10T13:57:55Z
| 3,255,815
|
<p><a href="http://teleal.org/projects/cling" rel="nofollow">http://teleal.org/projects/cling</a></p>
<p>Open Source DLNA/UPnP stack, libraries, and tools for Java and Android developers</p>
<p>Cling is very modular, so you could only use its SSDP functionality. You can integrate it with your existing code at any level (data transport, protocol execution, etc). </p>
<p>The Cling Support package contains a JAXB-based DIDL parser for UPnP A/V service implementors that can be used standalone.</p>
| 3
|
2010-07-15T13:14:57Z
|
[
"java",
"python",
"groovy",
"upnp"
] |
Detect whether charset exists in python
| 630,938
|
<p>Is it possible to check in Python whether a given charset exists/is installed.
For example:<br />
check('iso-8859-1') -> True<br />
check('bla') -> False</p>
| 0
|
2009-03-10T16:00:02Z
| 630,974
|
<p>You can use the <code>lookup()</code> function in the <code>codecs</code> module. It throws an exception if a codec does not exist:</p>
<pre><code>import codecs
def exists_encoding(enc):
try:
codecs.lookup(enc)
except LookupError:
return False
return True
exists_encoding('latin1')
</code></pre>
| 3
|
2009-03-10T16:06:01Z
|
[
"python",
"character-encoding"
] |
Hello world Pyamf small error message
| 631,436
|
<p>Hi i am trying to link flex to django with Pyamf</p>
<p>As a first step i tried the basic Hello World
<a href="http://pyamf.org/wiki/DjangoHowto" rel="nofollow">http://pyamf.org/wiki/DjangoHowto</a></p>
<p>But that results in an ErrorFault.</p>
<p>I use django 1.0.2</p>
<p><strong>amfgateway.py</strong> in the root folder of my project (same level as settings)</p>
<pre><code>import pyamf
from pyamf.remoting.gateway.django import DjangoGateway
from django.contrib.auth.models import User
pyamf.register_class(User, 'django.contrib.auth.models.User')
def get_users(requet):
return User.objects.all()
def echo(request, data):
return data
services = {
'myservice.echo': echo,
'myservice.get_users': get_users,
}
edoGateway = DjangoGateway(services, expose_request=False)
</code></pre>
<p><strong>In urls.py</strong></p>
<pre><code>urlpatterns = patterns('',
# test pyamf
url(r'^gateway/', 'amfgateway.edoGateway'),
...
)
</code></pre>
<p>Then when i test the example with pyamf client</p>
<pre><code>from pyamf.remoting.client import RemotingService
gw = RemotingService('http://127.0.0.1:8000/gateway/')
service = gw.getService('myservice')
print service.echo('Hello World!')
</code></pre>
<p><strong>I get</strong> </p>
<p><em>ErrorFault level=error code=500 type=u'AttributeError' description=u"Cannot find a view
for the path ['/gateway/myservice/echo'], 'DjangoGateway' object has no attribute '<strong>nam
e</strong>'"
Traceback:
u"Cannot find a view for the path ['/gateway/myservice/echo'], 'DjangoGateway' object ha
s no attribute '<strong>name</strong>'"</em></p>
| 1
|
2009-03-10T17:27:25Z
| 631,760
|
<p>I think you may need to take the request parameter out of your echo def, at least the method on the pyamf example site doesn't have that parameter in the method</p>
| 3
|
2009-03-10T18:54:05Z
|
[
"python",
"django",
"flex",
"pyamf"
] |
Hello world Pyamf small error message
| 631,436
|
<p>Hi i am trying to link flex to django with Pyamf</p>
<p>As a first step i tried the basic Hello World
<a href="http://pyamf.org/wiki/DjangoHowto" rel="nofollow">http://pyamf.org/wiki/DjangoHowto</a></p>
<p>But that results in an ErrorFault.</p>
<p>I use django 1.0.2</p>
<p><strong>amfgateway.py</strong> in the root folder of my project (same level as settings)</p>
<pre><code>import pyamf
from pyamf.remoting.gateway.django import DjangoGateway
from django.contrib.auth.models import User
pyamf.register_class(User, 'django.contrib.auth.models.User')
def get_users(requet):
return User.objects.all()
def echo(request, data):
return data
services = {
'myservice.echo': echo,
'myservice.get_users': get_users,
}
edoGateway = DjangoGateway(services, expose_request=False)
</code></pre>
<p><strong>In urls.py</strong></p>
<pre><code>urlpatterns = patterns('',
# test pyamf
url(r'^gateway/', 'amfgateway.edoGateway'),
...
)
</code></pre>
<p>Then when i test the example with pyamf client</p>
<pre><code>from pyamf.remoting.client import RemotingService
gw = RemotingService('http://127.0.0.1:8000/gateway/')
service = gw.getService('myservice')
print service.echo('Hello World!')
</code></pre>
<p><strong>I get</strong> </p>
<p><em>ErrorFault level=error code=500 type=u'AttributeError' description=u"Cannot find a view
for the path ['/gateway/myservice/echo'], 'DjangoGateway' object has no attribute '<strong>nam
e</strong>'"
Traceback:
u"Cannot find a view for the path ['/gateway/myservice/echo'], 'DjangoGateway' object ha
s no attribute '<strong>name</strong>'"</em></p>
| 1
|
2009-03-10T17:27:25Z
| 1,853,408
|
<p>Although the error is unrelated, JMP is correct - you have <code>expose_request=False</code> on the gateway and the service definition for echo has the first argument as the Django Http request object.</p>
<p>This isn't going to work, however PyAMF does allow some granularity here, you can use the expose_request decorator, e.g.:</p>
<pre><code>from pyamf.remoting.gateway import expose_request
@expose_request
def echo(request, data):
return echo
</code></pre>
| 2
|
2009-12-05T20:48:25Z
|
[
"python",
"django",
"flex",
"pyamf"
] |
Interruptible thread join in Python
| 631,441
|
<p><strong>Is there any way to wait for termination of a thread, but still intercept signals?</strong> </p>
<p>Consider the following <strong>C</strong> program:</p>
<pre><code>#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
void* server_thread(void* dummy) {
sleep(10);
printf("Served\n");
return NULL;
}
void* kill_thread(void* dummy) {
sleep(1); // Let the main thread join
printf("Killing\n");
kill(getpid(), SIGUSR1);
return NULL;
}
void handler(int signum) {
printf("Handling %d\n", signum);
exit(42);
}
int main() {
pthread_t servth;
pthread_t killth;
signal(SIGUSR1, handler);
pthread_create(&servth, NULL, server_thread, NULL);
pthread_create(&killth, NULL, kill_thread, NULL);
pthread_join(servth, NULL);
printf("Main thread finished\n");
return 0;
}
</code></pre>
<p>It ends after one second and prints:</p>
<pre><code>Killing
Handling 10
</code></pre>
<p>In contrast, here's my attempt to write it in <strong>Python</strong>:</p>
<pre><code>#!/usr/bin/env python
import signal, time, threading, os, sys
def handler(signum, frame):
print("Handling " + str(signum) + ", frame:" + str(frame))
exit(42)
signal.signal(signal.SIGUSR1, handler)
def server_thread():
time.sleep(10)
print("Served")
servth = threading.Thread(target=server_thread)
servth.start()
def kill_thread():
time.sleep(1) # Let the main thread join
print("Killing")
os.kill(os.getpid(), signal.SIGUSR1)
killth = threading.Thread(target=kill_thread)
killth.start()
servth.join()
print("Main thread finished")
</code></pre>
<p>It prints:</p>
<pre><code>Killing
Served
Handling 10, frame:<frame object at 0x12649c0>
</code></pre>
<p><strong>How do I make it behave like the C version?</strong></p>
| 21
|
2009-03-10T17:28:16Z
| 631,491
|
<p>Poll on <code>isAlive</code> before calling <code>join</code>. This polling can be interrupted, of course, and once the thread isn't <code>isAlive</code>, <code>join</code> is immediate.</p>
<p>An alternative would be polling on <code>join</code> with a timeout, checking with <code>isAlive</code> whether the timeout occurred. This can spend less CPU than the previous method.</p>
| 3
|
2009-03-10T17:43:59Z
|
[
"python",
"multithreading"
] |
Interruptible thread join in Python
| 631,441
|
<p><strong>Is there any way to wait for termination of a thread, but still intercept signals?</strong> </p>
<p>Consider the following <strong>C</strong> program:</p>
<pre><code>#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
void* server_thread(void* dummy) {
sleep(10);
printf("Served\n");
return NULL;
}
void* kill_thread(void* dummy) {
sleep(1); // Let the main thread join
printf("Killing\n");
kill(getpid(), SIGUSR1);
return NULL;
}
void handler(int signum) {
printf("Handling %d\n", signum);
exit(42);
}
int main() {
pthread_t servth;
pthread_t killth;
signal(SIGUSR1, handler);
pthread_create(&servth, NULL, server_thread, NULL);
pthread_create(&killth, NULL, kill_thread, NULL);
pthread_join(servth, NULL);
printf("Main thread finished\n");
return 0;
}
</code></pre>
<p>It ends after one second and prints:</p>
<pre><code>Killing
Handling 10
</code></pre>
<p>In contrast, here's my attempt to write it in <strong>Python</strong>:</p>
<pre><code>#!/usr/bin/env python
import signal, time, threading, os, sys
def handler(signum, frame):
print("Handling " + str(signum) + ", frame:" + str(frame))
exit(42)
signal.signal(signal.SIGUSR1, handler)
def server_thread():
time.sleep(10)
print("Served")
servth = threading.Thread(target=server_thread)
servth.start()
def kill_thread():
time.sleep(1) # Let the main thread join
print("Killing")
os.kill(os.getpid(), signal.SIGUSR1)
killth = threading.Thread(target=kill_thread)
killth.start()
servth.join()
print("Main thread finished")
</code></pre>
<p>It prints:</p>
<pre><code>Killing
Served
Handling 10, frame:<frame object at 0x12649c0>
</code></pre>
<p><strong>How do I make it behave like the C version?</strong></p>
| 21
|
2009-03-10T17:28:16Z
| 631,605
|
<p>Threads in Python are somewhat strange beasts given the global interpreter lock. You may not be able to achieve what you want without resorting to a join timeout and isAlive as eliben suggests.</p>
<p>There are two spots in the docs that give the reason for this (and possibly more).</p>
<p>The first:</p>
<p>From <a href="http://docs.python.org/library/signal.html#module-signal">http://docs.python.org/library/signal.html#module-signal</a>:</p>
<blockquote>
<p>Some care must be taken if both
signals and threads are used in the
same program. The fundamental thing to
remember in using signals and threads
simultaneously is: always perform
signal() operations in the main thread
of execution. Any thread can perform
an alarm(), getsignal(), pause(),
setitimer() or getitimer(); only the
main thread can set a new signal
handler, and the main thread will be
the only one to receive signals (this
is enforced by the Python signal
module, even if the underlying thread
implementation supports sending
signals to individual threads). This
means that signals canât be used as a
means of inter-thread communication.
Use locks instead.</p>
</blockquote>
<p>The second, from <a href="http://docs.python.org/library/thread.html#module-thread">http://docs.python.org/library/thread.html#module-thread</a>:</p>
<blockquote>
<p>Threads interact strangely with interrupts: the KeyboardInterrupt exception will be
received by an arbitrary thread. (When the signal module is available, interrupts
always go to the main thread.)</p>
</blockquote>
<p><strong>EDIT:</strong> There was a decent discussion of the mechanics of this on the python bug tracker here: <a href="http://bugs.python.org/issue1167930">http://bugs.python.org/issue1167930</a>. Of course, it ends with Guido saying: " That's unlikely to go away, so you'll just have to live
with this. As you've discovered, specifying a timeout solves the issue
(sort of)." YMMV :-)</p>
| 15
|
2009-03-10T18:12:29Z
|
[
"python",
"multithreading"
] |
Interruptible thread join in Python
| 631,441
|
<p><strong>Is there any way to wait for termination of a thread, but still intercept signals?</strong> </p>
<p>Consider the following <strong>C</strong> program:</p>
<pre><code>#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
void* server_thread(void* dummy) {
sleep(10);
printf("Served\n");
return NULL;
}
void* kill_thread(void* dummy) {
sleep(1); // Let the main thread join
printf("Killing\n");
kill(getpid(), SIGUSR1);
return NULL;
}
void handler(int signum) {
printf("Handling %d\n", signum);
exit(42);
}
int main() {
pthread_t servth;
pthread_t killth;
signal(SIGUSR1, handler);
pthread_create(&servth, NULL, server_thread, NULL);
pthread_create(&killth, NULL, kill_thread, NULL);
pthread_join(servth, NULL);
printf("Main thread finished\n");
return 0;
}
</code></pre>
<p>It ends after one second and prints:</p>
<pre><code>Killing
Handling 10
</code></pre>
<p>In contrast, here's my attempt to write it in <strong>Python</strong>:</p>
<pre><code>#!/usr/bin/env python
import signal, time, threading, os, sys
def handler(signum, frame):
print("Handling " + str(signum) + ", frame:" + str(frame))
exit(42)
signal.signal(signal.SIGUSR1, handler)
def server_thread():
time.sleep(10)
print("Served")
servth = threading.Thread(target=server_thread)
servth.start()
def kill_thread():
time.sleep(1) # Let the main thread join
print("Killing")
os.kill(os.getpid(), signal.SIGUSR1)
killth = threading.Thread(target=kill_thread)
killth.start()
servth.join()
print("Main thread finished")
</code></pre>
<p>It prints:</p>
<pre><code>Killing
Served
Handling 10, frame:<frame object at 0x12649c0>
</code></pre>
<p><strong>How do I make it behave like the C version?</strong></p>
| 21
|
2009-03-10T17:28:16Z
| 634,233
|
<p>Jarret Hardie already <a href="http://stackoverflow.com/questions/631441/interruptible-thread-join-in-python/631605#631605">mentioned it</a>: According to <a href="http://bugs.python.org/msg56947" rel="nofollow">Guido van Rossum</a>, there's no better way as of now: As stated in the <a href="http://docs.python.org/library/threading.html#threading.Thread.join" rel="nofollow">documentation</a>, <code>join(None)</code> blocks (and that means no signals). The alternative - calling with a huge timeout (<code>join(2**31)</code> or so) and checking <code>isAlive</code> looks great. However, the way Python handles timers is disastrous, as seen when running the python test program with <code>servth.join(100)</code> instead of <code>servth.join()</code>:</p>
<pre><code>select(0, NULL, NULL, NULL, {0, 1000}) = 0 (Timeout)
select(0, NULL, NULL, NULL, {0, 2000}) = 0 (Timeout)
select(0, NULL, NULL, NULL, {0, 4000}) = 0 (Timeout)
select(0, NULL, NULL, NULL, {0, 8000}) = 0 (Timeout)
select(0, NULL, NULL, NULL, {0, 16000}) = 0 (Timeout)
select(0, NULL, NULL, NULL, {0, 32000}) = 0 (Timeout)
select(0, NULL, NULL, NULL, {0, 50000}) = 0 (Timeout)
select(0, NULL, NULL, NULL, {0, 50000}) = 0 (Timeout)
select(0, NULL, NULL, NULL, {0, 50000}) = 0 (Timeout)
--- Skipped 15 equal lines ---
select(0, NULL, NULL, NULL, {0, 50000}Killing
</code></pre>
<p>I.e., Python wakes up every 50 ms, leading to a single application keeping the CPU from sleeping.</p>
| 3
|
2009-03-11T12:04:39Z
|
[
"python",
"multithreading"
] |
Interruptible thread join in Python
| 631,441
|
<p><strong>Is there any way to wait for termination of a thread, but still intercept signals?</strong> </p>
<p>Consider the following <strong>C</strong> program:</p>
<pre><code>#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
void* server_thread(void* dummy) {
sleep(10);
printf("Served\n");
return NULL;
}
void* kill_thread(void* dummy) {
sleep(1); // Let the main thread join
printf("Killing\n");
kill(getpid(), SIGUSR1);
return NULL;
}
void handler(int signum) {
printf("Handling %d\n", signum);
exit(42);
}
int main() {
pthread_t servth;
pthread_t killth;
signal(SIGUSR1, handler);
pthread_create(&servth, NULL, server_thread, NULL);
pthread_create(&killth, NULL, kill_thread, NULL);
pthread_join(servth, NULL);
printf("Main thread finished\n");
return 0;
}
</code></pre>
<p>It ends after one second and prints:</p>
<pre><code>Killing
Handling 10
</code></pre>
<p>In contrast, here's my attempt to write it in <strong>Python</strong>:</p>
<pre><code>#!/usr/bin/env python
import signal, time, threading, os, sys
def handler(signum, frame):
print("Handling " + str(signum) + ", frame:" + str(frame))
exit(42)
signal.signal(signal.SIGUSR1, handler)
def server_thread():
time.sleep(10)
print("Served")
servth = threading.Thread(target=server_thread)
servth.start()
def kill_thread():
time.sleep(1) # Let the main thread join
print("Killing")
os.kill(os.getpid(), signal.SIGUSR1)
killth = threading.Thread(target=kill_thread)
killth.start()
servth.join()
print("Main thread finished")
</code></pre>
<p>It prints:</p>
<pre><code>Killing
Served
Handling 10, frame:<frame object at 0x12649c0>
</code></pre>
<p><strong>How do I make it behave like the C version?</strong></p>
| 21
|
2009-03-10T17:28:16Z
| 5,063,521
|
<p>I know I'm a bit late to the party, but I came to this question hoping for a better answer than joining with a timeout, which I was already doing. In the end I cooked something up that may or may not be a horrible bastardisation of signals, but it involves using <code>signal.pause()</code> instead of <code>Thread.join()</code> and signalling the current process when the thread reaches the end of its execution:</p>
<pre><code>import signal, os, time, sys, threading, random
threadcount = 200
threadlock = threading.Lock()
pid = os.getpid()
sigchld_count = 0
def handle_sigterm(signalnum, frame):
print "SIGTERM"
def handle_sigchld(signalnum, frame):
global sigchld_count
sigchld_count += 1
def faux_join():
global threadcount, threadlock
threadlock.acquire()
threadcount -= 1
threadlock.release()
os.kill(pid, signal.SIGCHLD)
def thread_doer():
time.sleep(2+(2*random.random()))
faux_join()
if __name__ == '__main__':
signal.signal(signal.SIGCHLD, handle_sigchld)
signal.signal(signal.SIGTERM, handle_sigterm)
print pid
for i in xrange(0, threadcount):
t = threading.Thread(target=thread_doer)
t.start()
while 1:
if threadcount == 0: break
signal.pause()
print "Signal unpaused, thread count %s" % threadcount
print "All threads finished"
print "SIGCHLD handler called %s times" % sigchld_count
</code></pre>
<p>If you want to see the SIGTERMs in action, extend the length of the sleep time in <code>thread_doer</code> and issue a <code>kill $pid</code> command from another terminal, where <code>$pid</code> is the pid id printed at the start.</p>
<p>I post this as much in the hope of helping others as being told that this is crazy or has a bug. I'm not sure if the lock on threadcount is still necessary - I put it in there early in my experimentation and thought I should leave it in there in case.</p>
| 0
|
2011-02-21T07:53:52Z
|
[
"python",
"multithreading"
] |
Interruptible thread join in Python
| 631,441
|
<p><strong>Is there any way to wait for termination of a thread, but still intercept signals?</strong> </p>
<p>Consider the following <strong>C</strong> program:</p>
<pre><code>#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
void* server_thread(void* dummy) {
sleep(10);
printf("Served\n");
return NULL;
}
void* kill_thread(void* dummy) {
sleep(1); // Let the main thread join
printf("Killing\n");
kill(getpid(), SIGUSR1);
return NULL;
}
void handler(int signum) {
printf("Handling %d\n", signum);
exit(42);
}
int main() {
pthread_t servth;
pthread_t killth;
signal(SIGUSR1, handler);
pthread_create(&servth, NULL, server_thread, NULL);
pthread_create(&killth, NULL, kill_thread, NULL);
pthread_join(servth, NULL);
printf("Main thread finished\n");
return 0;
}
</code></pre>
<p>It ends after one second and prints:</p>
<pre><code>Killing
Handling 10
</code></pre>
<p>In contrast, here's my attempt to write it in <strong>Python</strong>:</p>
<pre><code>#!/usr/bin/env python
import signal, time, threading, os, sys
def handler(signum, frame):
print("Handling " + str(signum) + ", frame:" + str(frame))
exit(42)
signal.signal(signal.SIGUSR1, handler)
def server_thread():
time.sleep(10)
print("Served")
servth = threading.Thread(target=server_thread)
servth.start()
def kill_thread():
time.sleep(1) # Let the main thread join
print("Killing")
os.kill(os.getpid(), signal.SIGUSR1)
killth = threading.Thread(target=kill_thread)
killth.start()
servth.join()
print("Main thread finished")
</code></pre>
<p>It prints:</p>
<pre><code>Killing
Served
Handling 10, frame:<frame object at 0x12649c0>
</code></pre>
<p><strong>How do I make it behave like the C version?</strong></p>
| 21
|
2009-03-10T17:28:16Z
| 5,063,871
|
<p>As far as I understand, a similar question is solved in <a href="http://greenteapress.com/semaphores/" rel="nofollow">The Little Book of Semaphores</a> (free download), appendix A part 3â¦</p>
| 1
|
2011-02-21T08:47:08Z
|
[
"python",
"multithreading"
] |
Dictionaries in Python
| 631,463
|
<p>I am trying to get to speed on the use of dictionaries. I spent three hours last night searching the web for examples similar to some of the things I am trying to do. For example, suppose I have two dictionaries (actually I have two lists of dictionaries). </p>
<pre><code>d1={key1:1, key2:2}
d2={key1:1, key2:'A', key4:4}
</code></pre>
<p>I want to update d1 so it looks like the following:</p>
<pre><code>d1={key1:1, key2:[2,'A'], key3:3, key4:4}
</code></pre>
<p>Ii can't seem to find adequate examples to get me started. I have a fair number of books and I also reviewed them but they all seem to have the same type of examples that I am finding on the web. </p>
<p>Does anyone know of a place or a book that has explicit examples and descriptions of how to use dictionaries? </p>
<p>I think one of the problems I am having is that I am not understanding how references are maintained as I access the dictionary. </p>
<p>I can check to see if the two dictionaries have a common key:</p>
<pre><code>for k in d1.keys():
for k2 in d2.keys():
if k==k2:
print 'true'
</code></pre>
<p>but if they do I can't seem to combine the values into a list.</p>
<p>More than a direct answer to this particular example I would appreciate any suggestions about places where there are good examples of using dictionaries.</p>
| 5
|
2009-03-10T17:34:43Z
| 631,474
|
<p>Try this:</p>
<pre><code>import collections
merged = collections.defaultdict(list)
for k in d1:
merged[k].append( d1[k] )
for k in d2:
merged[k].append( d2[k] )
</code></pre>
<p>This may be what you're looking for.</p>
<p>Or possibly this.</p>
<pre><code>import collections
merged = collections.defaultdict(set)
for k in d1:
merged[k].add( d1[k] )
for k in d2:
merged[k].add( d2[k] )
</code></pre>
| 14
|
2009-03-10T17:37:22Z
|
[
"python",
"dictionary"
] |
Dictionaries in Python
| 631,463
|
<p>I am trying to get to speed on the use of dictionaries. I spent three hours last night searching the web for examples similar to some of the things I am trying to do. For example, suppose I have two dictionaries (actually I have two lists of dictionaries). </p>
<pre><code>d1={key1:1, key2:2}
d2={key1:1, key2:'A', key4:4}
</code></pre>
<p>I want to update d1 so it looks like the following:</p>
<pre><code>d1={key1:1, key2:[2,'A'], key3:3, key4:4}
</code></pre>
<p>Ii can't seem to find adequate examples to get me started. I have a fair number of books and I also reviewed them but they all seem to have the same type of examples that I am finding on the web. </p>
<p>Does anyone know of a place or a book that has explicit examples and descriptions of how to use dictionaries? </p>
<p>I think one of the problems I am having is that I am not understanding how references are maintained as I access the dictionary. </p>
<p>I can check to see if the two dictionaries have a common key:</p>
<pre><code>for k in d1.keys():
for k2 in d2.keys():
if k==k2:
print 'true'
</code></pre>
<p>but if they do I can't seem to combine the values into a list.</p>
<p>More than a direct answer to this particular example I would appreciate any suggestions about places where there are good examples of using dictionaries.</p>
| 5
|
2009-03-10T17:34:43Z
| 631,476
|
<p>Here are some good links:</p>
<p><a href="http://www.diveintopython.org/getting_to_know_python/dictionaries.html" rel="nofollow">http://www.diveintopython.org/getting_to_know_python/dictionaries.html</a><br />
<a href="http://docs.python.org/tutorial/datastructures.html#dictionaries" rel="nofollow">http://docs.python.org/tutorial/datastructures.html#dictionaries</a></p>
| 2
|
2009-03-10T17:37:53Z
|
[
"python",
"dictionary"
] |
Dictionaries in Python
| 631,463
|
<p>I am trying to get to speed on the use of dictionaries. I spent three hours last night searching the web for examples similar to some of the things I am trying to do. For example, suppose I have two dictionaries (actually I have two lists of dictionaries). </p>
<pre><code>d1={key1:1, key2:2}
d2={key1:1, key2:'A', key4:4}
</code></pre>
<p>I want to update d1 so it looks like the following:</p>
<pre><code>d1={key1:1, key2:[2,'A'], key3:3, key4:4}
</code></pre>
<p>Ii can't seem to find adequate examples to get me started. I have a fair number of books and I also reviewed them but they all seem to have the same type of examples that I am finding on the web. </p>
<p>Does anyone know of a place or a book that has explicit examples and descriptions of how to use dictionaries? </p>
<p>I think one of the problems I am having is that I am not understanding how references are maintained as I access the dictionary. </p>
<p>I can check to see if the two dictionaries have a common key:</p>
<pre><code>for k in d1.keys():
for k2 in d2.keys():
if k==k2:
print 'true'
</code></pre>
<p>but if they do I can't seem to combine the values into a list.</p>
<p>More than a direct answer to this particular example I would appreciate any suggestions about places where there are good examples of using dictionaries.</p>
| 5
|
2009-03-10T17:34:43Z
| 631,487
|
<p>Python dictionaries also work much like associative arrays in PHP, if you have any experience in that language.</p>
<p>The Built-in Types page in the Python docs also has a good section on dictionaries, and the section also has a list of functions available for them:</p>
<p><a href="http://docs.python.org/library/stdtypes.html#mapping-types-dict" rel="nofollow">http://docs.python.org/library/stdtypes.html#mapping-types-dict</a></p>
| 1
|
2009-03-10T17:42:18Z
|
[
"python",
"dictionary"
] |
Dictionaries in Python
| 631,463
|
<p>I am trying to get to speed on the use of dictionaries. I spent three hours last night searching the web for examples similar to some of the things I am trying to do. For example, suppose I have two dictionaries (actually I have two lists of dictionaries). </p>
<pre><code>d1={key1:1, key2:2}
d2={key1:1, key2:'A', key4:4}
</code></pre>
<p>I want to update d1 so it looks like the following:</p>
<pre><code>d1={key1:1, key2:[2,'A'], key3:3, key4:4}
</code></pre>
<p>Ii can't seem to find adequate examples to get me started. I have a fair number of books and I also reviewed them but they all seem to have the same type of examples that I am finding on the web. </p>
<p>Does anyone know of a place or a book that has explicit examples and descriptions of how to use dictionaries? </p>
<p>I think one of the problems I am having is that I am not understanding how references are maintained as I access the dictionary. </p>
<p>I can check to see if the two dictionaries have a common key:</p>
<pre><code>for k in d1.keys():
for k2 in d2.keys():
if k==k2:
print 'true'
</code></pre>
<p>but if they do I can't seem to combine the values into a list.</p>
<p>More than a direct answer to this particular example I would appreciate any suggestions about places where there are good examples of using dictionaries.</p>
| 5
|
2009-03-10T17:34:43Z
| 631,514
|
<p>One good place to start is by getting iPython (<code>easy_install ipython</code>) then poking around with tab completion, <code>?</code> and <code>dir</code>:</p>
<pre><code>In [2]: dir {}
------> dir({})
Out[2]:
['__class__',
...
'keys',
'pop',
'popitem',
'setdefault',
'update',
'values']
In [3]: {}.update?
Type: dict
Base Class: <type 'dict'>
String Form: {}
Namespace: Interactive
Length: 0
Docstring:
dict() -> new empty dictionary.
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs.
dict(seq) -> new dictionary initialized as if via:
d = {}
for k, v in seq:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
in the keyword argument list. For example: dict(one=1, two=2)
</code></pre>
<p>(just for example)</p>
<p>Anyway, your problem with checking keys common between the two dictionaries: there are a few things to consider (maybe look at the <code>set</code> class?), but here's how I'd do it:</p>
<pre><code>common_keys = [k for k in dict1 if k in dict2]
</code></pre>
<p>(ie, "each key <code>k</code> in dict1 if that key is also in dict2")
(note, too, that testing for dictionary membership is an O(1) operation, so this will run in O(|dict1|))</p>
<p><strong>edit</strong>: alright, so this doesn't solve the problem of merging the two dicts into one with lists... But Lott's answer is good for that, or you could use the <code>setdefault</code> method:</p>
<pre><code>new = {}
for (k, v) in dict1.items():
new.setdefault(k, []).append(v)
for (k, v) in dict2.items():
new.setdefault(k, []).append(v)
</code></pre>
| 6
|
2009-03-10T17:49:32Z
|
[
"python",
"dictionary"
] |
Dictionaries in Python
| 631,463
|
<p>I am trying to get to speed on the use of dictionaries. I spent three hours last night searching the web for examples similar to some of the things I am trying to do. For example, suppose I have two dictionaries (actually I have two lists of dictionaries). </p>
<pre><code>d1={key1:1, key2:2}
d2={key1:1, key2:'A', key4:4}
</code></pre>
<p>I want to update d1 so it looks like the following:</p>
<pre><code>d1={key1:1, key2:[2,'A'], key3:3, key4:4}
</code></pre>
<p>Ii can't seem to find adequate examples to get me started. I have a fair number of books and I also reviewed them but they all seem to have the same type of examples that I am finding on the web. </p>
<p>Does anyone know of a place or a book that has explicit examples and descriptions of how to use dictionaries? </p>
<p>I think one of the problems I am having is that I am not understanding how references are maintained as I access the dictionary. </p>
<p>I can check to see if the two dictionaries have a common key:</p>
<pre><code>for k in d1.keys():
for k2 in d2.keys():
if k==k2:
print 'true'
</code></pre>
<p>but if they do I can't seem to combine the values into a list.</p>
<p>More than a direct answer to this particular example I would appreciate any suggestions about places where there are good examples of using dictionaries.</p>
| 5
|
2009-03-10T17:34:43Z
| 631,549
|
<p>I believe here is what you want:</p>
<pre><code>>>> d1={'key1':1, 'key2':2}
>>> d2={'key1':1, 'key2':'A', 'key4':4}
>>> d = {}
>>> d.update(d1)
>>> for i in d2:
if i in d and d2[i] != d[i]:
d[i] = [d[i], d2[i]]
else:
d[i] = d2[i]
>>> d
{'key2': [2, 'A'], 'key1': 1, 'key4': 4}
</code></pre>
| 4
|
2009-03-10T17:55:08Z
|
[
"python",
"dictionary"
] |
Dictionaries in Python
| 631,463
|
<p>I am trying to get to speed on the use of dictionaries. I spent three hours last night searching the web for examples similar to some of the things I am trying to do. For example, suppose I have two dictionaries (actually I have two lists of dictionaries). </p>
<pre><code>d1={key1:1, key2:2}
d2={key1:1, key2:'A', key4:4}
</code></pre>
<p>I want to update d1 so it looks like the following:</p>
<pre><code>d1={key1:1, key2:[2,'A'], key3:3, key4:4}
</code></pre>
<p>Ii can't seem to find adequate examples to get me started. I have a fair number of books and I also reviewed them but they all seem to have the same type of examples that I am finding on the web. </p>
<p>Does anyone know of a place or a book that has explicit examples and descriptions of how to use dictionaries? </p>
<p>I think one of the problems I am having is that I am not understanding how references are maintained as I access the dictionary. </p>
<p>I can check to see if the two dictionaries have a common key:</p>
<pre><code>for k in d1.keys():
for k2 in d2.keys():
if k==k2:
print 'true'
</code></pre>
<p>but if they do I can't seem to combine the values into a list.</p>
<p>More than a direct answer to this particular example I would appreciate any suggestions about places where there are good examples of using dictionaries.</p>
| 5
|
2009-03-10T17:34:43Z
| 631,581
|
<p>well, for your first case, you might want a helper that combines two objects into a list of two objects, and two lists into one list containing items from the two lists, </p>
<p>This is assuming of course, that you always merge keys into lists, but you don't want your keys to end up being "lists of lists"</p>
<pre><code>def listify( obj ):
if type(obj) != type([]): return [obj]
else: return obj
def merge( v1, v2 ):
return listify(v1) + listify(v2)
#so now you can merge two dictionaries:
dict1 = dict(a = 2, b = 5, c = 7 )
dict2 = dict(b = 4, d = 9, f = 10 )
dikt = {}
for k in set( dict1.keys() + dict2.keys() ):
dikt[k] = merge( dict1.get(k, []), dict2.get(k, []) )
#resutls in:
# {'a': [2], 'c': [7], 'b': [5, 4], 'd': [9], 'f': [10]}
</code></pre>
<p>You may notice, <code>dict.keys()</code> returns a list of keys,
<code>set</code> returns a list without duplicate items, so <code>set( d1.keys(), d2.keys() )</code> returns union of the keys of d1 and d2</p>
| 0
|
2009-03-10T18:04:25Z
|
[
"python",
"dictionary"
] |
Dictionaries in Python
| 631,463
|
<p>I am trying to get to speed on the use of dictionaries. I spent three hours last night searching the web for examples similar to some of the things I am trying to do. For example, suppose I have two dictionaries (actually I have two lists of dictionaries). </p>
<pre><code>d1={key1:1, key2:2}
d2={key1:1, key2:'A', key4:4}
</code></pre>
<p>I want to update d1 so it looks like the following:</p>
<pre><code>d1={key1:1, key2:[2,'A'], key3:3, key4:4}
</code></pre>
<p>Ii can't seem to find adequate examples to get me started. I have a fair number of books and I also reviewed them but they all seem to have the same type of examples that I am finding on the web. </p>
<p>Does anyone know of a place or a book that has explicit examples and descriptions of how to use dictionaries? </p>
<p>I think one of the problems I am having is that I am not understanding how references are maintained as I access the dictionary. </p>
<p>I can check to see if the two dictionaries have a common key:</p>
<pre><code>for k in d1.keys():
for k2 in d2.keys():
if k==k2:
print 'true'
</code></pre>
<p>but if they do I can't seem to combine the values into a list.</p>
<p>More than a direct answer to this particular example I would appreciate any suggestions about places where there are good examples of using dictionaries.</p>
| 5
|
2009-03-10T17:34:43Z
| 632,136
|
<p>A variation on <a href="http://stackoverflow.com/questions/631463/dictionaries-in-python/631549#631549">@SilentGhost's answer</a> (all other answers produce wrong dictionaries):</p>
<pre><code>>>> d1 = dict(key1=1, key2=2)
>>> d2 = dict(key1=1, key2='A', key4=4)
>>> d = dict(d1)
>>> for k, v2 in d2.iteritems():
... v = d.get(k, None)
... d[k] = [v, v2] if v is not None and v != v2 else v2
...
>>> d
{'key2': [2, 'A'], 'key1': 1, 'key4': 4}
</code></pre>
| 0
|
2009-03-10T20:30:38Z
|
[
"python",
"dictionary"
] |
Dictionaries in Python
| 631,463
|
<p>I am trying to get to speed on the use of dictionaries. I spent three hours last night searching the web for examples similar to some of the things I am trying to do. For example, suppose I have two dictionaries (actually I have two lists of dictionaries). </p>
<pre><code>d1={key1:1, key2:2}
d2={key1:1, key2:'A', key4:4}
</code></pre>
<p>I want to update d1 so it looks like the following:</p>
<pre><code>d1={key1:1, key2:[2,'A'], key3:3, key4:4}
</code></pre>
<p>Ii can't seem to find adequate examples to get me started. I have a fair number of books and I also reviewed them but they all seem to have the same type of examples that I am finding on the web. </p>
<p>Does anyone know of a place or a book that has explicit examples and descriptions of how to use dictionaries? </p>
<p>I think one of the problems I am having is that I am not understanding how references are maintained as I access the dictionary. </p>
<p>I can check to see if the two dictionaries have a common key:</p>
<pre><code>for k in d1.keys():
for k2 in d2.keys():
if k==k2:
print 'true'
</code></pre>
<p>but if they do I can't seem to combine the values into a list.</p>
<p>More than a direct answer to this particular example I would appreciate any suggestions about places where there are good examples of using dictionaries.</p>
| 5
|
2009-03-10T17:34:43Z
| 633,005
|
<p>Maybe this is a bit awkward to do because the data structure you are trying to create is not as natural as it could be. For example instead of having some values be lone values, and some be lists, why not keep everything in lists? E.g.</p>
<pre><code>{'key1': [1], 'key2': [2, 'A'], 'key4': [4]}
</code></pre>
<p>It is possible in Python to have a collection of mixed data types but your code will often be cleaner if you keep it coherent. If you use this sort of data structure, inserting is as easy as</p>
<pre><code># Inserting a (key, value) pair
if key in my_dict:
my_dict[key].append(value)
else:
my_dict[key] = [value]
</code></pre>
| 0
|
2009-03-11T01:40:11Z
|
[
"python",
"dictionary"
] |
Dictionaries in Python
| 631,463
|
<p>I am trying to get to speed on the use of dictionaries. I spent three hours last night searching the web for examples similar to some of the things I am trying to do. For example, suppose I have two dictionaries (actually I have two lists of dictionaries). </p>
<pre><code>d1={key1:1, key2:2}
d2={key1:1, key2:'A', key4:4}
</code></pre>
<p>I want to update d1 so it looks like the following:</p>
<pre><code>d1={key1:1, key2:[2,'A'], key3:3, key4:4}
</code></pre>
<p>Ii can't seem to find adequate examples to get me started. I have a fair number of books and I also reviewed them but they all seem to have the same type of examples that I am finding on the web. </p>
<p>Does anyone know of a place or a book that has explicit examples and descriptions of how to use dictionaries? </p>
<p>I think one of the problems I am having is that I am not understanding how references are maintained as I access the dictionary. </p>
<p>I can check to see if the two dictionaries have a common key:</p>
<pre><code>for k in d1.keys():
for k2 in d2.keys():
if k==k2:
print 'true'
</code></pre>
<p>but if they do I can't seem to combine the values into a list.</p>
<p>More than a direct answer to this particular example I would appreciate any suggestions about places where there are good examples of using dictionaries.</p>
| 5
|
2009-03-10T17:34:43Z
| 2,319,295
|
<p>Here is another variation. </p>
<pre><code>d1 = {'key1'=1, 'key2'=2}
d2 = {'key1'=1, 'key2'='A', 'key4'=4)
d = d2
for k, v in d.iteritems():
... if k in d1.keys() and v!=d1[k]:
... d[k] = [d1[k], v2]
d
{'key2': [2, 'A'], 'key1': 1, 'key4': 4}
</code></pre>
| 0
|
2010-02-23T15:27:56Z
|
[
"python",
"dictionary"
] |
What is the best method to read a double from a Binary file created in C?
| 631,607
|
<p>A C program spits out consecutive doubles into a binary file. I wish to read them into Python. I tried using <code>struct.unpack('d',f.read(8))</code></p>
<p>EDIT:
I used the following in C to write a random double number</p>
<pre><code>r = drand48();
fwrite((void*)&r, sizeof(double), 1, data);
</code></pre>
<p>The Errors are now fixed but I cannot read the first value. for an all 0.000.. number it reads it as 3.90798504668055 but the rest are fine.</p>
| 4
|
2009-03-10T18:13:05Z
| 631,640
|
<p>Could you please elaborate on "didn't work"? Did the command crash? Did the data come out wrong? What actually happened?</p>
<p>If the command crashed:</p>
<ul>
<li>Please share the error output of the command</li>
</ul>
<p>If the data simply came out wrong:</p>
<ul>
<li><p>Do the systems that create and read the data have the same endianness? If one is big-endian, and the other is little-endian, then you need to specify an endianness conversion in your format string.</p></li>
<li><p>If the endianness of the two computers are the same, how was the data written to the file, <em>exactly</em>? Do you know? If you do, then what was the value written to the file and what was the incorrect value you got out?</p></li>
</ul>
| 1
|
2009-03-10T18:24:38Z
|
[
"python",
"c",
"double"
] |
What is the best method to read a double from a Binary file created in C?
| 631,607
|
<p>A C program spits out consecutive doubles into a binary file. I wish to read them into Python. I tried using <code>struct.unpack('d',f.read(8))</code></p>
<p>EDIT:
I used the following in C to write a random double number</p>
<pre><code>r = drand48();
fwrite((void*)&r, sizeof(double), 1, data);
</code></pre>
<p>The Errors are now fixed but I cannot read the first value. for an all 0.000.. number it reads it as 3.90798504668055 but the rest are fine.</p>
| 4
|
2009-03-10T18:13:05Z
| 631,768
|
<ul>
<li><code>f.read(8)</code> might return less than 8 bytes</li>
<li><p>Data might have different alignment and/or endianness:</p>
<pre><code>>>> for c in '@=<>':
... print repr(struct.pack(c+'d', -1.05))
...
'\xcd\xcc\xcc\xcc\xcc\xcc\xf0\xbf'
'\xcd\xcc\xcc\xcc\xcc\xcc\xf0\xbf'
'\xcd\xcc\xcc\xcc\xcc\xcc\xf0\xbf'
'\xbf\xf0\xcc\xcc\xcc\xcc\xcc\xcd'
>>> struct.unpack('<d', '\xbf\xf0\xcc\xcc\xcc\xcc\xcc\xcd')
(-6.0659880001157799e+066,)
>>> struct.unpack('>d', '\xbf\xf0\xcc\xcc\xcc\xcc\xcc\xcd')
(-1.05,)
</code></pre></li>
</ul>
| 0
|
2009-03-10T18:56:14Z
|
[
"python",
"c",
"double"
] |
What is the best method to read a double from a Binary file created in C?
| 631,607
|
<p>A C program spits out consecutive doubles into a binary file. I wish to read them into Python. I tried using <code>struct.unpack('d',f.read(8))</code></p>
<p>EDIT:
I used the following in C to write a random double number</p>
<pre><code>r = drand48();
fwrite((void*)&r, sizeof(double), 1, data);
</code></pre>
<p>The Errors are now fixed but I cannot read the first value. for an all 0.000.. number it reads it as 3.90798504668055 but the rest are fine.</p>
| 4
|
2009-03-10T18:13:05Z
| 632,542
|
<p>The <em>best</em> method would be to use an ASCII text file:</p>
<blockquote>
<p>0.0<br />
3.1416<br />
3.90798504668055 </p>
</blockquote>
<p>in that it would be portable and work with any kind of floating point implementation to a degree.</p>
<p>Reading raw binary data from a <code>double</code>'s memory address is not portable at all, and is bound to fail in some different implementation.</p>
<p>You may of course use a binary format for compactness, but a portable C function writing in that format would not look like your snippet at all.</p>
<p>At the very least, the code should be surrounded by a series of ifs/ifdefs checking that the memory representation of <code>double</code>s used by the current machine exactly matches the one expected by the Python interpreter.</p>
<p>Writing such code would be difficult, which is why I'm suggesting the easy, clean, portable and human-readable solution of ASCII text.</p>
<p>This would be <em>my</em> definition of "best".</p>
| -1
|
2009-03-10T22:29:12Z
|
[
"python",
"c",
"double"
] |
What is the best method to read a double from a Binary file created in C?
| 631,607
|
<p>A C program spits out consecutive doubles into a binary file. I wish to read them into Python. I tried using <code>struct.unpack('d',f.read(8))</code></p>
<p>EDIT:
I used the following in C to write a random double number</p>
<pre><code>r = drand48();
fwrite((void*)&r, sizeof(double), 1, data);
</code></pre>
<p>The Errors are now fixed but I cannot read the first value. for an all 0.000.. number it reads it as 3.90798504668055 but the rest are fine.</p>
| 4
|
2009-03-10T18:13:05Z
| 632,673
|
<p>First, have you tried <a href="http://www.python.org/doc/1.5.2p2/lib/module-pickle.html" rel="nofollow">pickle</a>?
No one has shown any Python code yet... Here is some code for reading in binary in python:</p>
<pre><code>import Numeric as N
import array
filename = "tmp.bin"
file = open(filename, mode='rb')
binvalues = array.array('f')
binvalues.read(file, num_lon * num_lat)
data = N.array(binvalues, typecode=N.Float)
file.close()
</code></pre>
<p>Where the f here specified single-precision, 4-byte floating, numbers. Find whatever size your data is per entry and use that. </p>
<p>For non binary data you could do something simple like this:</p>
<pre><code> tmp=[]
for line in open("data.dat"):
tmp.append(float(line))
</code></pre>
| 1
|
2009-03-10T23:19:34Z
|
[
"python",
"c",
"double"
] |
What is the best method to read a double from a Binary file created in C?
| 631,607
|
<p>A C program spits out consecutive doubles into a binary file. I wish to read them into Python. I tried using <code>struct.unpack('d',f.read(8))</code></p>
<p>EDIT:
I used the following in C to write a random double number</p>
<pre><code>r = drand48();
fwrite((void*)&r, sizeof(double), 1, data);
</code></pre>
<p>The Errors are now fixed but I cannot read the first value. for an all 0.000.. number it reads it as 3.90798504668055 but the rest are fine.</p>
| 4
|
2009-03-10T18:13:05Z
| 632,823
|
<p>I think you are actually reading the number correctly, but are getting confused by the display. When I read the number from your provided file, I get "<code>3.907985046680551e-14</code>" - this is almost but not quite zero (0.000000000000039 in expanded form). I suspect your C code is just printing it with less precision than python is.</p>
<p>[Edit] I've just tried reading the file in C, and I get the same result (though slightly less precision: 3.90799e-14) (using printf("%g", val)), so I think if this value is incorrect, it's happened on the writing side, rather than the reading.</p>
| 3
|
2009-03-11T00:22:48Z
|
[
"python",
"c",
"double"
] |
How do I assign a version number for a Python package using SVN and distutils?
| 631,813
|
<p>I'm writing a Python package. The package needs to know its version number internally, while also including this version in the <code>setup.py</code> script for <code>distutils</code>.</p>
<p>What's the best way of doing this, so that the version number doesn't need to be maintained in two separate places? I don't want to import the <code>setup.py</code> script from the rest of my library (that seems rather silly) and I don't want to import my library from the <code>setup.py</code> script (likewise). Ideally, I'd just set a keyword in <code>svn</code> and have that automatically substituted into the files, but that doesn't seem to be possible in <code>svn</code>. I could read a common text file containing the version number in both places--is this the best solution?</p>
<p><strong>To clarify</strong>: I want to maintain the version number in <em>one</em> place. Yes, I could put a variable in the package, and again in the <code>setup.py</code> file. But then they'd inevitably get out of sync.</p>
| 4
|
2009-03-10T19:08:49Z
| 631,985
|
<p>Inside of your main package, you probably have an <code>__init__.py</code>, right?</p>
<p>Directory structure:</p>
<pre><code>> ./packageTest
> ./packageTest/__init__.py
> ./packageTest/setup.py
</code></pre>
<p>Inside the <code>__init__.py</code> file, add the following line:</p>
<pre><code># package directory __init__.py
__version__ = 1.0
</code></pre>
<p>setup.py file:</p>
<pre><code># setup.py
from packageTest import __version__
...
</code></pre>
<p>Now in any module that imports from the package directory (I'll call packageTest), you can do this:</p>
<pre><code>from packageTest import setup
print 'Setup.py version:', setup.__version__
# prints Setup.py version: 1.0
</code></pre>
| 5
|
2009-03-10T19:50:52Z
|
[
"python",
"svn",
"distutils"
] |
How do I assign a version number for a Python package using SVN and distutils?
| 631,813
|
<p>I'm writing a Python package. The package needs to know its version number internally, while also including this version in the <code>setup.py</code> script for <code>distutils</code>.</p>
<p>What's the best way of doing this, so that the version number doesn't need to be maintained in two separate places? I don't want to import the <code>setup.py</code> script from the rest of my library (that seems rather silly) and I don't want to import my library from the <code>setup.py</code> script (likewise). Ideally, I'd just set a keyword in <code>svn</code> and have that automatically substituted into the files, but that doesn't seem to be possible in <code>svn</code>. I could read a common text file containing the version number in both places--is this the best solution?</p>
<p><strong>To clarify</strong>: I want to maintain the version number in <em>one</em> place. Yes, I could put a variable in the package, and again in the <code>setup.py</code> file. But then they'd inevitably get out of sync.</p>
| 4
|
2009-03-10T19:08:49Z
| 632,040
|
<p>Importing the setup script inside your package is silly (especially since it may no longer be present after your library is installed), but importing your library inside setup.py should be fine.
A separate text file would work too, but has the problem that you must install the text file with your package if you want to access the version number at runtime.</p>
| 0
|
2009-03-10T20:04:51Z
|
[
"python",
"svn",
"distutils"
] |
How do I assign a version number for a Python package using SVN and distutils?
| 631,813
|
<p>I'm writing a Python package. The package needs to know its version number internally, while also including this version in the <code>setup.py</code> script for <code>distutils</code>.</p>
<p>What's the best way of doing this, so that the version number doesn't need to be maintained in two separate places? I don't want to import the <code>setup.py</code> script from the rest of my library (that seems rather silly) and I don't want to import my library from the <code>setup.py</code> script (likewise). Ideally, I'd just set a keyword in <code>svn</code> and have that automatically substituted into the files, but that doesn't seem to be possible in <code>svn</code>. I could read a common text file containing the version number in both places--is this the best solution?</p>
<p><strong>To clarify</strong>: I want to maintain the version number in <em>one</em> place. Yes, I could put a variable in the package, and again in the <code>setup.py</code> file. But then they'd inevitably get out of sync.</p>
| 4
|
2009-03-10T19:08:49Z
| 632,077
|
<p>I had a similar problem with my project. I have written a top-level, test/build/package/deploy script called <a href="https://fisheye.springframework.org/browse/se-springpython-py/trunk/springpython/build.py?r=470" rel="nofollow">build.py</a> (not distutils-based, mind you). It reads a <a href="https://fisheye.springframework.org/browse/se-springpython-py/trunk/springpython/springpython.properties?r=468" rel="nofollow">properties file</a>, which contains the centralized version number. Instead of maintaining a setup.py file directly, I instead keep a <a href="https://fisheye.springframework.org/browse/se-springpython-py/trunk/springpython/src/build.py?r=461" rel="nofollow">template file</a>, and my build.py script reads it in, substitutes the version variable with the value from the props file, and then writes out a setup.py script. Then my script file will execute it, to generate a package or upload to pypi.</p>
| 0
|
2009-03-10T20:14:27Z
|
[
"python",
"svn",
"distutils"
] |
How do I assign a version number for a Python package using SVN and distutils?
| 631,813
|
<p>I'm writing a Python package. The package needs to know its version number internally, while also including this version in the <code>setup.py</code> script for <code>distutils</code>.</p>
<p>What's the best way of doing this, so that the version number doesn't need to be maintained in two separate places? I don't want to import the <code>setup.py</code> script from the rest of my library (that seems rather silly) and I don't want to import my library from the <code>setup.py</code> script (likewise). Ideally, I'd just set a keyword in <code>svn</code> and have that automatically substituted into the files, but that doesn't seem to be possible in <code>svn</code>. I could read a common text file containing the version number in both places--is this the best solution?</p>
<p><strong>To clarify</strong>: I want to maintain the version number in <em>one</em> place. Yes, I could put a variable in the package, and again in the <code>setup.py</code> file. But then they'd inevitably get out of sync.</p>
| 4
|
2009-03-10T19:08:49Z
| 8,882,419
|
<p>See also <a href="http://stackoverflow.com/questions/458550/standard-way-to-embed-version-into-python-package">Standard way to embed version into python package?</a> which is about how to propagate the version information from the one location (a file named <code>_version.py</code>) to the places where other code looks for it (e.g. an attribute named <code>__version__</code> and <code>PEP 0345</code> metadata).</p>
<p>Then see Brian Warner's <a href="https://github.com/warner/python-versioneer" rel="nofollow">new "versioneer" tool</a>, which produces the <code>_version.py</code> file from revision control history.</p>
<p>Also, please check out my answer to <a href="http://stackoverflow.com/a/7071358/2742805">Standard way to embed version into python package?</a>, the more people that realize there is a way to do it which avoids the problems of importing your module from your setup script, the better.</p>
| 0
|
2012-01-16T15:45:55Z
|
[
"python",
"svn",
"distutils"
] |
base64 png in python on Windows
| 631,884
|
<p>How do you encode a png image into base64 using python on Windows?</p>
<pre><code>iconfile = open("icon.png")
icondata = iconfile.read()
icondata = base64.b64encode(icondata)
</code></pre>
<p>The above works fine in Linux and OSX, but on Windows it will encode the first few characters then cut short. Why is this?</p>
| 11
|
2009-03-10T19:25:42Z
| 631,899
|
<p><a href="http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files">Open the file in binary mode</a>:</p>
<pre><code>open("icon.png", "rb")
</code></pre>
<p>I'm not very familiar with Windows, but I'd imagine what's happening is that the file contains a character (0x1A) that <a href="http://www.google.com/search?q=windows%2Bend%2Bof%2Bfile%2Bcharacter">Windows is interpreting as the end of the file</a> (for legacy reasons) when it is opened in text mode. The other issue is that opening a file in text mode (without the 'b') on Windows will cause line endings to be rewritten, which will generally break binary files where those characters don't actually indicate the end of a line.</p>
| 26
|
2009-03-10T19:29:26Z
|
[
"python",
"windows",
"base64"
] |
base64 png in python on Windows
| 631,884
|
<p>How do you encode a png image into base64 using python on Windows?</p>
<pre><code>iconfile = open("icon.png")
icondata = iconfile.read()
icondata = base64.b64encode(icondata)
</code></pre>
<p>The above works fine in Linux and OSX, but on Windows it will encode the first few characters then cut short. Why is this?</p>
| 11
|
2009-03-10T19:25:42Z
| 632,495
|
<p>To augment the answer from Miles, the <a href="http://www.libpng.org/pub/png/spec/1.2/PNG-Rationale.html#R.PNG-file-signature">first eight bytes in a PNG file</a> are specially designed:</p>
<ul>
<li>89 - the first byte is a check that
bit 8 hasn't been stripped</li>
<li>"PNG" - let someone read that it's a
PNG format</li>
<li>0d 0a - the DOS end-of-line
indicator, to check if there was
DOS->unix conversion</li>
<li>1a - the DOS end-of-file character,
to check that the file was opened in
binary mode</li>
<li>0a - unix end-of-line character, to
check if there was a unix->DOS
conversion</li>
</ul>
<p>Your code stops at the 1a, as designed.</p>
| 9
|
2009-03-10T22:16:13Z
|
[
"python",
"windows",
"base64"
] |
figure out whether python module is installed or in develop mode programmatically
| 631,996
|
<p>I tend to develop my apps in 'setup.py develop' -mode. I'd want the configuration to switch automagically on production mode when the program gets 'setup.py install'ed.</p>
<p>This can be done by poor hacks, like checking whether installation directory contains 'setup.py', but I wonder whether pkg_resources can do this for me somehow.</p>
| 1
|
2009-03-10T19:52:42Z
| 632,051
|
<p>Isn't it easier, and cleaner, to just set an environment variable on your development machine, and test for <code>os.environ['development_mode']</code> (or a setting of your choice)?</p>
| 5
|
2009-03-10T20:08:36Z
|
[
"python",
"packaging"
] |
figure out whether python module is installed or in develop mode programmatically
| 631,996
|
<p>I tend to develop my apps in 'setup.py develop' -mode. I'd want the configuration to switch automagically on production mode when the program gets 'setup.py install'ed.</p>
<p>This can be done by poor hacks, like checking whether installation directory contains 'setup.py', but I wonder whether pkg_resources can do this for me somehow.</p>
| 1
|
2009-03-10T19:52:42Z
| 632,314
|
<p>Indeed, <a href="http://peak.telecommunity.com/DevCenter/PkgResources#distribution-attributes" rel="nofollow"><code>pkg_resources</code> will do that</a>:</p>
<pre><code>dist = pkg_resources.get_distribution('your-app')
if dist.precedence == pkg_resources.DEVELOP_DIST:
# package is in development mode
...
</code></pre>
| 4
|
2009-03-10T21:16:28Z
|
[
"python",
"packaging"
] |
figure out whether python module is installed or in develop mode programmatically
| 631,996
|
<p>I tend to develop my apps in 'setup.py develop' -mode. I'd want the configuration to switch automagically on production mode when the program gets 'setup.py install'ed.</p>
<p>This can be done by poor hacks, like checking whether installation directory contains 'setup.py', but I wonder whether pkg_resources can do this for me somehow.</p>
| 1
|
2009-03-10T19:52:42Z
| 632,320
|
<p>Another option is to use <a href="http://pypi.python.org/pypi/virtualenv" rel="nofollow">virtualenv</a>. Then your development environment could be identical to your production environment. Setuptools is a pretty heavy thing to depend on, in my opinion.</p>
| 0
|
2009-03-10T21:18:00Z
|
[
"python",
"packaging"
] |
Looking to get started with Apache, PHP, MySQL, Python, Django on a fresh Mac
| 632,046
|
<p>I've looked for other questions, but could not find any...</p>
<p>I have freshly installed my Mac with OSX 10.5. I need to learn Python/Django for a new job, so want to set it all up correctly, ready to develop and run from my browser using <a href="http://localhost/" rel="nofollow">http://localhost/</a></p>
<p>I come from a PHP background and always used MAMP before. But I want to get everything working together... Apache, PHP, MySQL, Python, Django. Using MAMP is easy to install a local development server, but I want to get Python and Django running nicely too. So I can just start developing and also following tutorials on Python/Django.</p>
<p>Please give me some steps (with MAMP or not) to get a nicely working environment for Apache, PHP, MySQL, Python and Django. Thank you, all have great days!</p>
<p>James</p>
| 0
|
2009-03-10T20:07:13Z
| 632,082
|
<p>Your Mac should come pre-installed with Python 2.4 (or later) which is fine for Django 1.0.2.</p>
| 1
|
2009-03-10T20:15:16Z
|
[
"php",
"python",
"django",
"osx",
"osx-leopard"
] |
Looking to get started with Apache, PHP, MySQL, Python, Django on a fresh Mac
| 632,046
|
<p>I've looked for other questions, but could not find any...</p>
<p>I have freshly installed my Mac with OSX 10.5. I need to learn Python/Django for a new job, so want to set it all up correctly, ready to develop and run from my browser using <a href="http://localhost/" rel="nofollow">http://localhost/</a></p>
<p>I come from a PHP background and always used MAMP before. But I want to get everything working together... Apache, PHP, MySQL, Python, Django. Using MAMP is easy to install a local development server, but I want to get Python and Django running nicely too. So I can just start developing and also following tutorials on Python/Django.</p>
<p>Please give me some steps (with MAMP or not) to get a nicely working environment for Apache, PHP, MySQL, Python and Django. Thank you, all have great days!</p>
<p>James</p>
| 0
|
2009-03-10T20:07:13Z
| 632,098
|
<p>Why not try <a href="http://docs.djangoproject.com/en/dev/intro/install/#intro-install" rel="nofollow">the official installation instructions</a>? Really all you need to do is install Django. You can use its built-in server (<code>http://localhost:8000</code> by default) for testing:</p>
<pre><code>./manage.py runserver
</code></pre>
| 6
|
2009-03-10T20:19:07Z
|
[
"php",
"python",
"django",
"osx",
"osx-leopard"
] |
Looking to get started with Apache, PHP, MySQL, Python, Django on a fresh Mac
| 632,046
|
<p>I've looked for other questions, but could not find any...</p>
<p>I have freshly installed my Mac with OSX 10.5. I need to learn Python/Django for a new job, so want to set it all up correctly, ready to develop and run from my browser using <a href="http://localhost/" rel="nofollow">http://localhost/</a></p>
<p>I come from a PHP background and always used MAMP before. But I want to get everything working together... Apache, PHP, MySQL, Python, Django. Using MAMP is easy to install a local development server, but I want to get Python and Django running nicely too. So I can just start developing and also following tutorials on Python/Django.</p>
<p>Please give me some steps (with MAMP or not) to get a nicely working environment for Apache, PHP, MySQL, Python and Django. Thank you, all have great days!</p>
<p>James</p>
| 0
|
2009-03-10T20:07:13Z
| 632,122
|
<p>10.5 comes with Apache installed by default System Preferences > Sharing > Web Sharing. </p>
<p>To enable Apache php module edit the Apache conf (/etc/Apache/httpd.conf) file and uncomment the php module line.</p>
<pre><code>LoadModule php5_module libexec/apache2/libphp5.so.
</code></pre>
<p>Restart Apache after by disabling & enabling web sharing</p>
<p>Mysql package can be downloaded form the official website and is easy to install</p>
| 0
|
2009-03-10T20:25:13Z
|
[
"php",
"python",
"django",
"osx",
"osx-leopard"
] |
Looking to get started with Apache, PHP, MySQL, Python, Django on a fresh Mac
| 632,046
|
<p>I've looked for other questions, but could not find any...</p>
<p>I have freshly installed my Mac with OSX 10.5. I need to learn Python/Django for a new job, so want to set it all up correctly, ready to develop and run from my browser using <a href="http://localhost/" rel="nofollow">http://localhost/</a></p>
<p>I come from a PHP background and always used MAMP before. But I want to get everything working together... Apache, PHP, MySQL, Python, Django. Using MAMP is easy to install a local development server, but I want to get Python and Django running nicely too. So I can just start developing and also following tutorials on Python/Django.</p>
<p>Please give me some steps (with MAMP or not) to get a nicely working environment for Apache, PHP, MySQL, Python and Django. Thank you, all have great days!</p>
<p>James</p>
| 0
|
2009-03-10T20:07:13Z
| 632,124
|
<p>Okay. I'd just install MySQL from their site and stick with what's already on my Mac as of 10.5, then install Django and the Python MySQL driver. But since you like MAMP, install <a href="http://www.mamp.info/" rel="nofollow">MAMP</a> or <a href="http://www.apachefriends.org/en/xampp.html" rel="nofollow">XAMPP</a> and read something like <a href="http://antoniocangiano.com/2007/12/22/how-to-install-django-with-mysql-on-mac-os-x/" rel="nofollow">this</a> which summarized says:</p>
<p><em>Mac OS X 10.5 comes with "Python 2.5.1</em>, thus you wonât have to install it. You can verify this by running python in the Terminal." </p>
<p><em>Checkout Django</em> <code>cd $HOME/Code; svn co <a href="http://code.djangoproject.com/svn/django/trunk" rel="nofollow">http://code.djangoproject.com/svn/django/trunk</a> django_trunk</code></p>
<p><em>Tell Python where Django is</em> <code>echo "$HOME/Code/django_trunk">/Library/Python/2.5/site-packages/django.pth</code></p>
<p><em>Add django-admin.py to your PATH</em></p>
<p><em>Install the MySQLdb driver</em> from <a href="http://sourceforge.net/project/showfiles.php?group%5Fid=22307" rel="nofollow">sf.net</a> this probably requires GCC which means you might want the set with Xcode from Apple's Dev Tools.</p>
<p><em>Do a source code edit</em></p>
<p>"At this point, edit the _mysql.c file
and comment out lines 37, 38 and 39 as
follows:"</p>
<pre><code>//#ifndef uint
//#define uint unsigned int
//#endif
</code></pre>
<p>run</p>
<pre><code>python setup.py build
sudo python setup.py install
</code></pre>
<p><em>Verify the installation</em></p>
| -1
|
2009-03-10T20:26:55Z
|
[
"php",
"python",
"django",
"osx",
"osx-leopard"
] |
Looking to get started with Apache, PHP, MySQL, Python, Django on a fresh Mac
| 632,046
|
<p>I've looked for other questions, but could not find any...</p>
<p>I have freshly installed my Mac with OSX 10.5. I need to learn Python/Django for a new job, so want to set it all up correctly, ready to develop and run from my browser using <a href="http://localhost/" rel="nofollow">http://localhost/</a></p>
<p>I come from a PHP background and always used MAMP before. But I want to get everything working together... Apache, PHP, MySQL, Python, Django. Using MAMP is easy to install a local development server, but I want to get Python and Django running nicely too. So I can just start developing and also following tutorials on Python/Django.</p>
<p>Please give me some steps (with MAMP or not) to get a nicely working environment for Apache, PHP, MySQL, Python and Django. Thank you, all have great days!</p>
<p>James</p>
| 0
|
2009-03-10T20:07:13Z
| 632,154
|
<p>The fastest way to get started with Django, will be to use TurnKey linux Django appliance.</p>
<p>Link: <a href="http://www.turnkeylinux.org/appliances/django" rel="nofollow">http://www.turnkeylinux.org/appliances/django</a></p>
| 0
|
2009-03-10T20:34:50Z
|
[
"php",
"python",
"django",
"osx",
"osx-leopard"
] |
Looking to get started with Apache, PHP, MySQL, Python, Django on a fresh Mac
| 632,046
|
<p>I've looked for other questions, but could not find any...</p>
<p>I have freshly installed my Mac with OSX 10.5. I need to learn Python/Django for a new job, so want to set it all up correctly, ready to develop and run from my browser using <a href="http://localhost/" rel="nofollow">http://localhost/</a></p>
<p>I come from a PHP background and always used MAMP before. But I want to get everything working together... Apache, PHP, MySQL, Python, Django. Using MAMP is easy to install a local development server, but I want to get Python and Django running nicely too. So I can just start developing and also following tutorials on Python/Django.</p>
<p>Please give me some steps (with MAMP or not) to get a nicely working environment for Apache, PHP, MySQL, Python and Django. Thank you, all have great days!</p>
<p>James</p>
| 0
|
2009-03-10T20:07:13Z
| 635,218
|
<p>I also came from PHP a few months ago. I'm not sure if this will get moderated up or down because my answer changes your question:</p>
<ol>
<li>Do not use MySQL and Apache for local development on your Mac. Use Sqlite3 and the development server that is bundled with Django - this allows for inline debugging, etc...</li>
<li>Sqlite3 is basically the same as MySQL except you need to use .schema instead of describe.</li>
<li>If you start having problems, get <a href="http://wiki.python.org/moin/MacPython/Leopard" rel="nofollow">MacPython</a>. This has helped me instantly solve problems faster than trying to work with the stock Python on Leopard.</li>
<li>Try to use <a href="http://pypi.python.org/pypi/pip" rel="nofollow">pip</a> instead of easy_install where possible.</li>
</ol>
<p>When you are ready for real deployment, then you'll need MySQL/Apache/Nginx, etc... but those will be on a Linux system and you'll be better prepared at that point to make a good production installation than you are now. Getting a production-quality stack running on the Mac is more of a pain than it's worth. </p>
<p>BTW, when you do install Apache, use wsgi, not mod_python.</p>
| 0
|
2009-03-11T16:04:48Z
|
[
"php",
"python",
"django",
"osx",
"osx-leopard"
] |
Automatically fetching latest version of a file on import
| 632,171
|
<p>I have a module that I want to keep up to date, and I'm wondering if this is a bad idea: </p>
<blockquote>
<p>Have a module (mod1.py) in the
site-packages directory that copies a
different module from some other
location into the site-packages
directory, and then imports * from
that module.</p>
</blockquote>
<pre><code>import shutil
from distutils.sysconfig import get_python_lib
p_source = r'\\SourceSafeServer\mod1_current.py'
p_local = get_python_lib() + r'\mod1_current.py'
shutil.copyfile(p_source, p_local)
from mod1_current import *
</code></pre>
<p>Now I can do this in any module, and it will always be the latest version:</p>
<pre><code>from mod1 import function1
</code></pre>
<p>This works.... but is there a better way of doing this?</p>
<p><strong>Update</strong></p>
<p>Here is the current process... there is a project under source-control that has a single module: <code>mod1.py</code> There is also a <code>setup.py</code> Running <code>setup.py</code> copies <code>mod1.py</code> to the site-packages directory. </p>
<p>Developers that use the module must run <code>setup.py</code> to update the module. Sometimes, they don't and not having the latest version causes problems.</p>
<p>I want to be able to just check-in the a new version, and any code that imports that module will automatically grab the latest version every time, without anyone having to run <code>setup.py</code></p>
| 1
|
2009-03-10T20:38:28Z
| 632,196
|
<p>Do you <em>really</em> want to do this? This means you could very easily roll code to a production app simply by committing to source control. I would consider this a nasty side-effect for someone who isn't aware of your setup.</p>
<p>That being said this seems like a pretty good solution - you may want to add some exception-handling around the network file calls as those are prone to failure.</p>
| 2
|
2009-03-10T20:45:11Z
|
[
"python",
"version-control",
"visual-sourcesafe"
] |
Automatically fetching latest version of a file on import
| 632,171
|
<p>I have a module that I want to keep up to date, and I'm wondering if this is a bad idea: </p>
<blockquote>
<p>Have a module (mod1.py) in the
site-packages directory that copies a
different module from some other
location into the site-packages
directory, and then imports * from
that module.</p>
</blockquote>
<pre><code>import shutil
from distutils.sysconfig import get_python_lib
p_source = r'\\SourceSafeServer\mod1_current.py'
p_local = get_python_lib() + r'\mod1_current.py'
shutil.copyfile(p_source, p_local)
from mod1_current import *
</code></pre>
<p>Now I can do this in any module, and it will always be the latest version:</p>
<pre><code>from mod1 import function1
</code></pre>
<p>This works.... but is there a better way of doing this?</p>
<p><strong>Update</strong></p>
<p>Here is the current process... there is a project under source-control that has a single module: <code>mod1.py</code> There is also a <code>setup.py</code> Running <code>setup.py</code> copies <code>mod1.py</code> to the site-packages directory. </p>
<p>Developers that use the module must run <code>setup.py</code> to update the module. Sometimes, they don't and not having the latest version causes problems.</p>
<p>I want to be able to just check-in the a new version, and any code that imports that module will automatically grab the latest version every time, without anyone having to run <code>setup.py</code></p>
| 1
|
2009-03-10T20:38:28Z
| 632,594
|
<p>In some cases, we put <code>.pth</code> files in the Python site-packages directory. The <code>.pth</code> files name our various SVN checkout directories. </p>
<p>No install. No copy.</p>
<p><code>.pth</code> files are described <a href="http://docs.python.org/library/site.html#module-site" rel="nofollow">here</a>.</p>
| 1
|
2009-03-10T22:49:36Z
|
[
"python",
"version-control",
"visual-sourcesafe"
] |
Automatically fetching latest version of a file on import
| 632,171
|
<p>I have a module that I want to keep up to date, and I'm wondering if this is a bad idea: </p>
<blockquote>
<p>Have a module (mod1.py) in the
site-packages directory that copies a
different module from some other
location into the site-packages
directory, and then imports * from
that module.</p>
</blockquote>
<pre><code>import shutil
from distutils.sysconfig import get_python_lib
p_source = r'\\SourceSafeServer\mod1_current.py'
p_local = get_python_lib() + r'\mod1_current.py'
shutil.copyfile(p_source, p_local)
from mod1_current import *
</code></pre>
<p>Now I can do this in any module, and it will always be the latest version:</p>
<pre><code>from mod1 import function1
</code></pre>
<p>This works.... but is there a better way of doing this?</p>
<p><strong>Update</strong></p>
<p>Here is the current process... there is a project under source-control that has a single module: <code>mod1.py</code> There is also a <code>setup.py</code> Running <code>setup.py</code> copies <code>mod1.py</code> to the site-packages directory. </p>
<p>Developers that use the module must run <code>setup.py</code> to update the module. Sometimes, they don't and not having the latest version causes problems.</p>
<p>I want to be able to just check-in the a new version, and any code that imports that module will automatically grab the latest version every time, without anyone having to run <code>setup.py</code></p>
| 1
|
2009-03-10T20:38:28Z
| 633,065
|
<p>The original strategy of having other developers copy mod1.py into their site-packages in order to use the module sounds like it's the real problem. Why aren't they just using the same source control are you are?</p>
<p>This auto-copying will make it hard to do rollbacks, especially if other developers copy your strategy. Imagine this same system used for dozens and dozens of files. And then imagine you actually <em>do</em> want to use a version of mod1.py that is not the latest for something.</p>
| 0
|
2009-03-11T02:03:18Z
|
[
"python",
"version-control",
"visual-sourcesafe"
] |
How to debug a file upload?
| 632,577
|
<p>I'm trying to upload a PDF file to a website using Hot Banana's content management system using a Python script. I've successfully logged into the site and can log out, but I can't seem to get file uploads to work. </p>
<p>The file upload is part of a large complicated web form that submits the form data and PDF file though a POST. Using Firefox along with the Firebug and Tamper Data extensions I took a peek at what the browser was sending in the POST and where it was going. I believe I mimicked the data the browser was sending in the code, but I'm still having trouble. </p>
<p>I'm importing cookielib to handle cookies, poster to encode the PDF, and urllib and urllib2 to build the request and send it to the URL. </p>
<p>Is it possible that registering the poster openers is clobbering the cookie processor openers? Am I doing this completely wrong?</p>
<p><hr /></p>
<p>Edit: What's a good way to debug the process? At the moment, I'm just dumping out the urllib2 response to a text file and examining the output to see if it matches what I get when I do a file upload manually. </p>
<p>Edit 2: Chris Lively suggested I post the error I'm getting. The response from urllib2 doesn't generate an exception, but just returns:</p>
<pre><code><script>
if (parent != window) {
parent.document.location.reload();
} else {
parent.document.location = 'login.cfm';
}
</script>
</code></pre>
<p>I'll keep at it. </p>
| 1
|
2009-03-10T22:43:51Z
| 633,045
|
<p>You might be better off instrumenting the server to see why this is failing, rather than trying to debug this on the client side.</p>
| 0
|
2009-03-11T01:54:55Z
|
[
"python",
"post",
"upload",
"urllib2"
] |
How to debug a file upload?
| 632,577
|
<p>I'm trying to upload a PDF file to a website using Hot Banana's content management system using a Python script. I've successfully logged into the site and can log out, but I can't seem to get file uploads to work. </p>
<p>The file upload is part of a large complicated web form that submits the form data and PDF file though a POST. Using Firefox along with the Firebug and Tamper Data extensions I took a peek at what the browser was sending in the POST and where it was going. I believe I mimicked the data the browser was sending in the code, but I'm still having trouble. </p>
<p>I'm importing cookielib to handle cookies, poster to encode the PDF, and urllib and urllib2 to build the request and send it to the URL. </p>
<p>Is it possible that registering the poster openers is clobbering the cookie processor openers? Am I doing this completely wrong?</p>
<p><hr /></p>
<p>Edit: What's a good way to debug the process? At the moment, I'm just dumping out the urllib2 response to a text file and examining the output to see if it matches what I get when I do a file upload manually. </p>
<p>Edit 2: Chris Lively suggested I post the error I'm getting. The response from urllib2 doesn't generate an exception, but just returns:</p>
<pre><code><script>
if (parent != window) {
parent.document.location.reload();
} else {
parent.document.location = 'login.cfm';
}
</script>
</code></pre>
<p>I'll keep at it. </p>
| 1
|
2009-03-10T22:43:51Z
| 633,252
|
<p>A tool like <a href="http://www.wireshark.org/" rel="nofollow">WireShark</a> will give you a more complete trace at a much lower-level than the firefox plugins.</p>
<p>Often this can be something as simple as not setting the content-type correctly, or failing to include content-length.</p>
| 1
|
2009-03-11T03:42:05Z
|
[
"python",
"post",
"upload",
"urllib2"
] |
How to debug a file upload?
| 632,577
|
<p>I'm trying to upload a PDF file to a website using Hot Banana's content management system using a Python script. I've successfully logged into the site and can log out, but I can't seem to get file uploads to work. </p>
<p>The file upload is part of a large complicated web form that submits the form data and PDF file though a POST. Using Firefox along with the Firebug and Tamper Data extensions I took a peek at what the browser was sending in the POST and where it was going. I believe I mimicked the data the browser was sending in the code, but I'm still having trouble. </p>
<p>I'm importing cookielib to handle cookies, poster to encode the PDF, and urllib and urllib2 to build the request and send it to the URL. </p>
<p>Is it possible that registering the poster openers is clobbering the cookie processor openers? Am I doing this completely wrong?</p>
<p><hr /></p>
<p>Edit: What's a good way to debug the process? At the moment, I'm just dumping out the urllib2 response to a text file and examining the output to see if it matches what I get when I do a file upload manually. </p>
<p>Edit 2: Chris Lively suggested I post the error I'm getting. The response from urllib2 doesn't generate an exception, but just returns:</p>
<pre><code><script>
if (parent != window) {
parent.document.location.reload();
} else {
parent.document.location = 'login.cfm';
}
</script>
</code></pre>
<p>I'll keep at it. </p>
| 1
|
2009-03-10T22:43:51Z
| 634,440
|
<p><strong>"What's a good way to debug [a web services] process?"</strong></p>
<p><em>At the moment, I'm just dumping out the urllib2 response to a text file and examining the output to see if it matches what I get when I do a file upload manually.</em></p>
<p>Correct. That's about all there is.</p>
<p>HTTP is a very simple protocol -- you make a request (POST, in this case) and the server responds. Not much else involved and not much more you can do while debugging.</p>
<p>What else would you like? Seriously. What kind of debugger are you imagining might exist for this kind of stateless protocol? </p>
| 0
|
2009-03-11T13:09:28Z
|
[
"python",
"post",
"upload",
"urllib2"
] |
Nested loop syntax in python server pages
| 632,624
|
<p>I am just trying to write a small web page that can parse some text using a regular expression and return the resulting matches in a table. This is the first I've used python for web development, and I have to say, it looks messy.</p>
<p>My question is why do I only get output for the last match in my data set? I figure it has to be because the nested loops aren't formatted correctly.</p>
<p>Here's the data I provide:</p>
<p>groups is just an id correspoding to the regex group, and it's name to provide the header for the table.</p>
<p>pattern is something like:</p>
<pre><code>(\d+)\s(\S+)\s(\S+)$
</code></pre>
<p>and data:</p>
<pre><code>12345 SOME USER
09876 SOMEONE ELSE
54678 ANOTHER USER
</code></pre>
<p>My simple page:</p>
<pre><code><%
import re
pattern = form['pattern']
p = re.compile(pattern)
data = form['data']
matches = p.finditer(data)
lines = form['groups'].split("\n")
groupids ={}
for line in lines:
key, val = line.split(' ')
groupids[int(key.strip())] = val.strip()
%>
<html>
<table style="border-width:1px;border-style:solid;width:60%;">
<tr>
<%
for k,v in groupids.iteritems():%>
<th style="width:30px;text-align:center"><%= v %></th>
<%
# end
%>
</tr>
<%
for match in matches:
#begin
%><tr>
<%
for i in range(1, len(match.groups())+1):
#begin
%>
<td style="border-style:solid;border-width:1px;border-spacing:0px;text-align:center;"><%= match.group(i) %></td>
<%
#end
# end
%>
</tr>
</table>
</html>
</code></pre>
<h2>Edit</h2>
<p>Below is the test I ran</p>
<p>Code:</p>
<pre><code>import re
pattern = "(\d\d\d\d\d)\s(\S+)\s(\S+)"
p = re.compile(pattern)
data = """12345 TESTS USERS
34567 TESTS USERS
56789 TESTS USERS"""
groups = """1 PIN
2 FNAME
3 LNAME"""
matches = p.finditer(data)
lines = groups.split("\n")
print lines
groupids ={}
for line in lines:
key, val = line.split(' ')
groupids[int(key.strip())] = val.strip()
for k,v in groupids.iteritems():
print "%s\t" % v,
print ''
for match in matches:
for i in range(1, len(match.groups())+1):
print "%s\t" % match.group(i),
print ''
</code></pre>
<p>Output:</p>
<pre><code>PIN FNAME LNAME
12345 TESTS USERS
34567 TESTS USERS
56789 TESTS USERS
</code></pre>
| 1
|
2009-03-10T23:00:48Z
| 632,664
|
<p>I'm not sure about the interaction with the templating engine, but python would expect the inner loop to be indented under the containing loop.</p>
<p>Try formatting it that way and see if it works.</p>
<pre><code><%
for match in matches:
%><tr><%
for i in range(1, len(match.groups())+1):
%><td style="border-style:solid;border-width:1px;border-spacing:0px;text-align:center;"><%= match.group(i) %></td><%
%>
</code></pre>
<p>Or some such. The above produces "IndentationError: unindent does not match any outer indentation level" so try:</p>
<pre><code><%
for match in matches:
%><tr><%
for i in range(1, len(match.groups())+1):
%><td style="border-style:solid;border-width:1px;border-spacing:0px;text-align:center;"><%= match.group(i) %></td><%
%>
</code></pre>
<p>or </p>
<pre><code><%
for match in matches:
%><tr><%
for i in range(1, len(match.groups())+1):
%><td style="border-style:solid;border-width:1px;border-spacing:0px;text-align:center;"><%= match.group(i) %></td><%
pass
%>
</code></pre>
<p>or some combination. Your problem is in indicating to python where the loop ends. To do this you must figure out a way to make the templating engine produce valid python with the right indentation.</p>
<p>Also, if you can get at the generated code you could split the problem in half: first tinker with the generated code to find out what python will accept and then tinker wit the template to get it produce that.</p>
| 0
|
2009-03-10T23:15:05Z
|
[
"python",
"python-server-pages"
] |
Nested loop syntax in python server pages
| 632,624
|
<p>I am just trying to write a small web page that can parse some text using a regular expression and return the resulting matches in a table. This is the first I've used python for web development, and I have to say, it looks messy.</p>
<p>My question is why do I only get output for the last match in my data set? I figure it has to be because the nested loops aren't formatted correctly.</p>
<p>Here's the data I provide:</p>
<p>groups is just an id correspoding to the regex group, and it's name to provide the header for the table.</p>
<p>pattern is something like:</p>
<pre><code>(\d+)\s(\S+)\s(\S+)$
</code></pre>
<p>and data:</p>
<pre><code>12345 SOME USER
09876 SOMEONE ELSE
54678 ANOTHER USER
</code></pre>
<p>My simple page:</p>
<pre><code><%
import re
pattern = form['pattern']
p = re.compile(pattern)
data = form['data']
matches = p.finditer(data)
lines = form['groups'].split("\n")
groupids ={}
for line in lines:
key, val = line.split(' ')
groupids[int(key.strip())] = val.strip()
%>
<html>
<table style="border-width:1px;border-style:solid;width:60%;">
<tr>
<%
for k,v in groupids.iteritems():%>
<th style="width:30px;text-align:center"><%= v %></th>
<%
# end
%>
</tr>
<%
for match in matches:
#begin
%><tr>
<%
for i in range(1, len(match.groups())+1):
#begin
%>
<td style="border-style:solid;border-width:1px;border-spacing:0px;text-align:center;"><%= match.group(i) %></td>
<%
#end
# end
%>
</tr>
</table>
</html>
</code></pre>
<h2>Edit</h2>
<p>Below is the test I ran</p>
<p>Code:</p>
<pre><code>import re
pattern = "(\d\d\d\d\d)\s(\S+)\s(\S+)"
p = re.compile(pattern)
data = """12345 TESTS USERS
34567 TESTS USERS
56789 TESTS USERS"""
groups = """1 PIN
2 FNAME
3 LNAME"""
matches = p.finditer(data)
lines = groups.split("\n")
print lines
groupids ={}
for line in lines:
key, val = line.split(' ')
groupids[int(key.strip())] = val.strip()
for k,v in groupids.iteritems():
print "%s\t" % v,
print ''
for match in matches:
for i in range(1, len(match.groups())+1):
print "%s\t" % match.group(i),
print ''
</code></pre>
<p>Output:</p>
<pre><code>PIN FNAME LNAME
12345 TESTS USERS
34567 TESTS USERS
56789 TESTS USERS
</code></pre>
| 1
|
2009-03-10T23:00:48Z
| 632,732
|
<pre><code><%
for match in matches:
#begin
%><tr>
<%
for i in range(1, len(match.groups())+1):
#begin
%>
<td style="border-style:solid;border-width:1px;border-spacing:0px;text-align:center;"><%= match.group(i) %></td>
<%
#end
# end
%>
</code></pre>
<p>Yeah, you haven't got a nested loop there. Instead you've got a loop over <code>matches</code> that outputs â<tr>\nâ, then a second loop over <code>range(...)</code> that only runs after the first has finished. The second is not inside the first because it isn't indented to say so.</p>
<p>From the <a href="http://www.modpython.org/live/mod%5Fpython-3.1.2b/doc-html/pyapi-psp.html" rel="nofollow">doc</a>, I <em>think</em> what you need to be saying is:</p>
<pre><code><%
for match in matches:
# begin
%><tr><%
for group in match.groups():
# begin
%><td style="border-style:solid;border-width:1px;border-spacing:0px;text-align:center;"><%= group %></td><%
# end
%></tr><%
# end
%>
</code></pre>
<p>But I can only agree with your âmessyâ comment: if PSP is requiring that you torture the indenting of your HTML to fit the structure of your Python like this, it is really Doing It Wrong and you should look for another, less awful templating syntax. There are many, many templating languages for Python that have a more sensible syntax for control structures. As an example, in the one I use the above would look like:</p>
<pre><code><px:for item="match" in="matches"><tr>
<px:for item="group" in="match.groups()">
<td style="border-style:solid;border-width:1px;border-spacing:0px;text-align:center;">
<?_ group ?>
</td>
</px:for>
</tr></px:for>
</code></pre>
| 1
|
2009-03-10T23:47:44Z
|
[
"python",
"python-server-pages"
] |
What is the feasibility of porting a legacy C program to Python?
| 632,730
|
<p>I have a program in C that communicates via UDP with another program (in Java) and then does process manipulation (start/stop) based on the UDP pkt exchange.
Now this C program has been legacy and I want to convert it to Python - do you think Python will be a good choice for the tasks mentioned?</p>
| 2
|
2009-03-10T23:47:15Z
| 632,738
|
<p>Yes, I do think that Python would be a good replacement. I understand that the <a href="http://twistedmatrix.com/trac/" rel="nofollow" title="Twisted">Twisted</a> Python framework is quite popular.</p>
| 9
|
2009-03-10T23:50:47Z
|
[
"python",
"c"
] |
What is the feasibility of porting a legacy C program to Python?
| 632,730
|
<p>I have a program in C that communicates via UDP with another program (in Java) and then does process manipulation (start/stop) based on the UDP pkt exchange.
Now this C program has been legacy and I want to convert it to Python - do you think Python will be a good choice for the tasks mentioned?</p>
| 2
|
2009-03-10T23:47:15Z
| 632,740
|
<p>Assuming that you have control over the environment which this application will run, and that the performance of interpreted language (python) compared to a compiled one (C) can be ignored, I believe Python is a great choice for this.</p>
| 1
|
2009-03-10T23:51:08Z
|
[
"python",
"c"
] |
What is the feasibility of porting a legacy C program to Python?
| 632,730
|
<p>I have a program in C that communicates via UDP with another program (in Java) and then does process manipulation (start/stop) based on the UDP pkt exchange.
Now this C program has been legacy and I want to convert it to Python - do you think Python will be a good choice for the tasks mentioned?</p>
| 2
|
2009-03-10T23:47:15Z
| 632,788
|
<p>I'd say that if:</p>
<ul>
<li>Your C code contains no platform specific requirements</li>
<li>You are sure speed is not going to be an issue going from C to python</li>
<li>You have a desire to not compile anymore</li>
<li>You would like to try utilise exception handling</li>
<li>You want to dabble in OO</li>
<li>You might choose to run on many platforms without porting</li>
<li>You are curious about dynamic typing</li>
<li>You want memory handled for you</li>
<li>You know or want to learn python</li>
</ul>
<p>Then sure, why not. </p>
<p>There doesn't seem to be any technical reason you shouldn't use python here, so it's a preference in this case.</p>
| 4
|
2009-03-11T00:09:10Z
|
[
"python",
"c"
] |
What is the feasibility of porting a legacy C program to Python?
| 632,730
|
<p>I have a program in C that communicates via UDP with another program (in Java) and then does process manipulation (start/stop) based on the UDP pkt exchange.
Now this C program has been legacy and I want to convert it to Python - do you think Python will be a good choice for the tasks mentioned?</p>
| 2
|
2009-03-10T23:47:15Z
| 632,844
|
<p>If I was faced with a similar situation I'd ask myself a couple of questions:</p>
<ul>
<li>Is there anything more important I could be working on?</li>
<li>Does Python bring anything to the table that is currently handled poorly by the current application?</li>
<li>Will this allow me to add functionality that was previously too difficult to implement?</li>
<li>Is this going to disrupt service in any way?</li>
</ul>
<p>If I can't answer those satisfactorily, then I'd put off the rewrite. </p>
| 1
|
2009-03-11T00:29:27Z
|
[
"python",
"c"
] |
What is the feasibility of porting a legacy C program to Python?
| 632,730
|
<p>I have a program in C that communicates via UDP with another program (in Java) and then does process manipulation (start/stop) based on the UDP pkt exchange.
Now this C program has been legacy and I want to convert it to Python - do you think Python will be a good choice for the tasks mentioned?</p>
| 2
|
2009-03-10T23:47:15Z
| 632,925
|
<p>Remember as well, you can leave parts of your program in C, turn them into Python modules and build python code around them - you don't need to re-write everything up-front.</p>
| 2
|
2009-03-11T00:53:28Z
|
[
"python",
"c"
] |
What is the feasibility of porting a legacy C program to Python?
| 632,730
|
<p>I have a program in C that communicates via UDP with another program (in Java) and then does process manipulation (start/stop) based on the UDP pkt exchange.
Now this C program has been legacy and I want to convert it to Python - do you think Python will be a good choice for the tasks mentioned?</p>
| 2
|
2009-03-10T23:47:15Z
| 632,935
|
<p>Yes, I think Python is a good choice, if all your platforms support it. Since this is a network program, I'm assuming the network is your runtime bottleneck? That's likely to still be the case in Python. If you really do need to speed it up, you can include your long-since-debugged, speedy C as Python modules.</p>
| 1
|
2009-03-11T00:57:10Z
|
[
"python",
"c"
] |
What is the feasibility of porting a legacy C program to Python?
| 632,730
|
<p>I have a program in C that communicates via UDP with another program (in Java) and then does process manipulation (start/stop) based on the UDP pkt exchange.
Now this C program has been legacy and I want to convert it to Python - do you think Python will be a good choice for the tasks mentioned?</p>
| 2
|
2009-03-10T23:47:15Z
| 634,093
|
<p>If this is an embedded program, then it might be a problem to port it since Python programs typically rely on the Python runtime and library, and those are fairly large. Especially when compared to a C program doing a well-defined task. Of course, it's likely you've already considered that aspect, but I wanted to mention it in the context of the question anyway, since I feel it's an important aspect when doing this type of comparison.</p>
| 0
|
2009-03-11T11:08:30Z
|
[
"python",
"c"
] |
Python, Evaluate a Variable value as a Variable
| 632,856
|
<p>I'd like to do something like below: particularly the 'f.eval(field)' part, such that it evaluates the value of the variable as the field name. How does one accomplish this in Python?</p>
<pre><code>def punctuated_object_list(objects, field):
field_list = [f.eval(field) for f in objects]
if len(field_list) > 0:
if len(field_list) == 1:
return field_list[0]
else:
return ', '.join(field_list[:-1]) + ' & ' + field_list[-1]
else:
return u''
</code></pre>
| 4
|
2009-03-11T00:31:50Z
| 632,869
|
<p><code>getattr(f, field)</code>, if I understand you correctly (that is, if you might have <code>field = "foo"</code>, and want <code>f.foo</code>). If not, you might want to clarify. Python has an <code>eval()</code>, and I don't know what other languages' <code>eval()</code> you want the equivalent of.</p>
| 11
|
2009-03-11T00:35:09Z
|
[
"python"
] |
Python, Evaluate a Variable value as a Variable
| 632,856
|
<p>I'd like to do something like below: particularly the 'f.eval(field)' part, such that it evaluates the value of the variable as the field name. How does one accomplish this in Python?</p>
<pre><code>def punctuated_object_list(objects, field):
field_list = [f.eval(field) for f in objects]
if len(field_list) > 0:
if len(field_list) == 1:
return field_list[0]
else:
return ', '.join(field_list[:-1]) + ' & ' + field_list[-1]
else:
return u''
</code></pre>
| 4
|
2009-03-11T00:31:50Z
| 632,880
|
<p>The python equivalent of <code>eval()</code> is <code>eval()</code></p>
<pre><code>x = 9
eval("x*2")
</code></pre>
<p>will give you 18.</p>
<pre><code>v = "x"
eval(v+"*2")
</code></pre>
<p>works too.</p>
| 0
|
2009-03-11T00:37:43Z
|
[
"python"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.