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 |
|---|---|---|---|---|---|---|---|---|---|
How can I create a Word document using Python? | 1,035,183 | <p>I'd like to create a Word document using Python, however, I want to re-use as much of my existing document-creation code as possible. I am currently using an XSLT to generate an HTML file that I <a href="http://www.xhtml2pdf.com/">programatically convert</a> to a PDF file. However, my client is now requesting that the same document be made available in Word (.doc) format.</p>
<p>So far, I haven't had much luck finding any solutions to this problem. Is anyone aware of an open source library (or *gulp* a proprietary solution) that may help resolve this issue?</p>
<p>NOTE: All possible solutions must run on Linux. I believe this eliminates pywin32.</p>
| 32 | 2009-06-23T20:59:08Z | 1,035,392 | <p>A couple ways you can create Word documents using Python:</p>
<ul>
<li>Use COM automation to create a document using the MS Word object model (using <code>pywin32</code>). <a href="http://python.net/crew/pirx/spam7/" rel="nofollow">http://python.net/crew/pirx/spam7/</a></li>
<li>Automate OpenOffice using Python: <a href="http://wiki.services.openoffice.org/wiki/Python" rel="nofollow">http://wiki.services.openoffice.org/wiki/Python</a></li>
<li>If rtf format is OK, use the PyRTF library: <a href="http://pyrtf.sourceforge.net/" rel="nofollow">http://pyrtf.sourceforge.net/</a></li>
</ul>
<p>EDIT:</p>
<p>Since COM is out of the question, I suggest the following (inspired by @kcrumley's answer):</p>
<p>Using the UNO library to automate Open Office from python, open the HTML file in OOWriter, then save as .doc.</p>
<p>EDIT2:</p>
<p>There is now a pure Python <a href="https://python-docx.readthedocs.org/en/latest/" rel="nofollow">python-docx project</a> that looks nice (I have not used it).</p>
| 33 | 2009-06-23T21:36:24Z | [
"python",
"xml",
"xslt",
"ms-word"
] |
How can I create a Word document using Python? | 1,035,183 | <p>I'd like to create a Word document using Python, however, I want to re-use as much of my existing document-creation code as possible. I am currently using an XSLT to generate an HTML file that I <a href="http://www.xhtml2pdf.com/">programatically convert</a> to a PDF file. However, my client is now requesting that the same document be made available in Word (.doc) format.</p>
<p>So far, I haven't had much luck finding any solutions to this problem. Is anyone aware of an open source library (or *gulp* a proprietary solution) that may help resolve this issue?</p>
<p>NOTE: All possible solutions must run on Linux. I believe this eliminates pywin32.</p>
| 32 | 2009-06-23T20:59:08Z | 1,035,433 | <p>1) If you want to just stick another step on the end of your current pipeline, there are several options out there now for converting PDF files to Word files. I haven't tried <a href="http://download.cnet.com/123PDFConverter-PDF-to-Word-Converter/3000-10743%5F4-10544297.html" rel="nofollow">123PDFConverter</a>, but the CNET Editors recommend it (same link); it has a free trial; and it supports automation. As with any 3rd-party file converter, your mileage may vary, depending how complicated your PDFs are, and how good the software actually is.</p>
<p>2) Building on codeape's COM automation suggestion, if you COM automate Word, you can open your actual HTML file in Word, and call the "Save As" command, to save it as a DOC file.</p>
| 2 | 2009-06-23T21:45:05Z | [
"python",
"xml",
"xslt",
"ms-word"
] |
How can I create a Word document using Python? | 1,035,183 | <p>I'd like to create a Word document using Python, however, I want to re-use as much of my existing document-creation code as possible. I am currently using an XSLT to generate an HTML file that I <a href="http://www.xhtml2pdf.com/">programatically convert</a> to a PDF file. However, my client is now requesting that the same document be made available in Word (.doc) format.</p>
<p>So far, I haven't had much luck finding any solutions to this problem. Is anyone aware of an open source library (or *gulp* a proprietary solution) that may help resolve this issue?</p>
<p>NOTE: All possible solutions must run on Linux. I believe this eliminates pywin32.</p>
| 32 | 2009-06-23T20:59:08Z | 1,135,357 | <p>I have had to do something similar with python as well. It is <em>far</em> more manual work than I want, but documents created with pyRTF were causing Word and OpenOffice to crash and I didn't have the motivation to try to figure it out.</p>
<p>I have found it simplest (but not ideal) to create a Word document template with the styles I want. Then my Python creates an HTML file whose <code><p></code> styles are labeled after the Word styles. Then I open the HTML file in Word and open the template in Word. I cut and paste all text from the HTML file into the template, and Word re-formats it all according to the styles I had set up previously. That works for the occasional file in my situation. It might not work for your situation. FYI.</p>
| 1 | 2009-07-16T04:14:37Z | [
"python",
"xml",
"xslt",
"ms-word"
] |
How can I create a Word document using Python? | 1,035,183 | <p>I'd like to create a Word document using Python, however, I want to re-use as much of my existing document-creation code as possible. I am currently using an XSLT to generate an HTML file that I <a href="http://www.xhtml2pdf.com/">programatically convert</a> to a PDF file. However, my client is now requesting that the same document be made available in Word (.doc) format.</p>
<p>So far, I haven't had much luck finding any solutions to this problem. Is anyone aware of an open source library (or *gulp* a proprietary solution) that may help resolve this issue?</p>
<p>NOTE: All possible solutions must run on Linux. I believe this eliminates pywin32.</p>
| 32 | 2009-06-23T20:59:08Z | 8,052,336 | <p>I tried <a href="https://github.com/mikemaccana/python-docx">python-docx</a> with succes, it enables you to make and edit docx within Python</p>
| 19 | 2011-11-08T14:54:21Z | [
"python",
"xml",
"xslt",
"ms-word"
] |
Reading binary file in Python and looping over each byte | 1,035,340 | <p>In Python, how do I read in a binary file and loop over each byte of that file?</p>
| 198 | 2009-06-23T21:26:52Z | 1,035,360 | <pre><code>f = open("myfile", "rb")
try:
byte = f.read(1)
while byte != "":
# Do stuff with byte.
byte = f.read(1)
finally:
f.close()
</code></pre>
<p>By suggestion of chrispy:</p>
<pre><code>with open("myfile", "rb") as f:
byte = f.read(1)
while byte != "":
# Do stuff with byte.
byte = f.read(1)
</code></pre>
<p>Note that the with statement is not available in versions of Python below 2.5. To use it in v 2.5 you'll need to import it:</p>
<pre><code>from __future__ import with_statement
</code></pre>
<p>In 2.6 this is not needed.</p>
<p>In Python 3, it's a bit different. We will no longer get raw characters from the stream in byte mode but byte objects, thus we need to alter the condition:</p>
<pre><code>with open("myfile", "rb") as f:
byte = f.read(1)
while byte != b"":
# Do stuff with byte.
byte = f.read(1)
</code></pre>
<p>Or as benhoyt says, skip the not equal and take advantage of the fact that <code>b""</code> evaluates to false. This makes the code compatible between 2.6 and 3.x without any changes. It would also save you from changing the condition if you go from byte mode to text or the reverse.</p>
<pre><code>with open("myfile", "rb") as f:
byte = f.read(1)
while byte:
# Do stuff with byte.
byte = f.read(1)
</code></pre>
| 196 | 2009-06-23T21:31:28Z | [
"python",
"file-io",
"binary"
] |
Reading binary file in Python and looping over each byte | 1,035,340 | <p>In Python, how do I read in a binary file and loop over each byte of that file?</p>
| 198 | 2009-06-23T21:26:52Z | 1,035,419 | <p>If the file is not too big that holding it in memory is a problem:</p>
<pre><code>bytes_read = open("filename", "rb").read()
for b in bytes_read:
process_byte(b)
</code></pre>
<p>where process_byte represents some operation you want to perform on the passed-in byte.</p>
<p>If you want to process a chunk at a time:</p>
<pre><code>file = open("filename", "rb")
try:
bytes_read = file.read(CHUNKSIZE)
while bytes_read:
for b in bytes_read:
process_byte(b)
bytes_read = file.read(CHUNKSIZE)
finally:
file.close()
</code></pre>
| 37 | 2009-06-23T21:43:03Z | [
"python",
"file-io",
"binary"
] |
Reading binary file in Python and looping over each byte | 1,035,340 | <p>In Python, how do I read in a binary file and loop over each byte of that file?</p>
| 198 | 2009-06-23T21:26:52Z | 1,035,456 | <p>This generator yields bytes from a file, reading the file in chunks:</p>
<pre><code>def bytes_from_file(filename, chunksize=8192):
with open(filename, "rb") as f:
while True:
chunk = f.read(chunksize)
if chunk:
for b in chunk:
yield b
else:
break
# example:
for b in bytes_from_file('filename'):
do_stuff_with(b)
</code></pre>
<p>See the Python documentation for information on <a href="http://docs.python.org/3/tutorial/classes.html#iterators">iterators</a> and <a href="http://docs.python.org/3/tutorial/classes.html#generators">generators</a>.</p>
| 109 | 2009-06-23T21:50:55Z | [
"python",
"file-io",
"binary"
] |
Reading binary file in Python and looping over each byte | 1,035,340 | <p>In Python, how do I read in a binary file and loop over each byte of that file?</p>
| 198 | 2009-06-23T21:26:52Z | 18,652,697 | <p>To sum up all the brilliant points of chrispy, Skurmedel, Ben Hoyt and Peter Hansen, this would be the optimal solution for processing a binary file one byte at a time:</p>
<pre><code>with open("myfile", "rb") as f:
while True:
byte = f.read(1)
if not byte:
break
do_stuff_with(ord(byte))
</code></pre>
<p>For python versions 2.6 and above, because:</p>
<ul>
<li>python buffers internally - no need to read chunks </li>
<li>DRY principle - do not repeat the read line</li>
<li>with statement ensures a clean file close</li>
<li>'byte' evaluates to false when there are no more bytes (not when a byte is zero)</li>
</ul>
<p>Or use J. F. Sebastians solution for improved speed</p>
<pre><code>from functools import partial
with open(filename, 'rb') as file:
for byte in iter(partial(file.read, 1), b''):
# Do stuff with byte
</code></pre>
<p>Or if you want it as a generator function like demonstrated by codeape:</p>
<pre><code>def bytes_from_file(filename):
with open(filename, "rb") as f:
while True:
byte = f.read(1)
if not byte:
break
yield(ord(byte))
# example:
for b in bytes_from_file('filename'):
do_stuff_with(b)
</code></pre>
| 13 | 2013-09-06T07:55:55Z | [
"python",
"file-io",
"binary"
] |
Reading binary file in Python and looping over each byte | 1,035,340 | <p>In Python, how do I read in a binary file and loop over each byte of that file?</p>
| 198 | 2009-06-23T21:26:52Z | 20,014,805 | <p>To read a file â one byte at a time (ignoring the buffering) â you could use the <a href="http://docs.python.org/2/library/functions.html#iter">two-argument <code>iter(callable, sentinel)</code> built-in function</a>:</p>
<pre><code>from functools import partial
with open(filename, 'rb') as file:
for byte in iter(partial(file.read, 1), b''):
# Do stuff with byte
</code></pre>
<p>It calls <code>file.read(1)</code> until it returns nothing <code>b''</code> (empty bytestring). The memory doesn't grow unlimited for large files. You could pass <code>buffering=0</code> to <code>open()</code>, to disable the buffering â it guarantees that only one byte is read per iteration.</p>
<p><code>with</code>-statement closes the file automatically â including the case when the code underneath raises an exception.</p>
<p>Despite the presence of internal buffering by default, it is still ineffective to process one byte at a time. For example, here's the <code>blackhole.py</code> utility that eats everything it is given:</p>
<pre><code>#!/usr/bin/env python3
"""Discard all input. `cat > /dev/null` analog."""
import sys
from functools import partial
from collections import deque
bufsize = int(sys.argv[1]) if len(sys.argv) > 1 else (1 << 15)
deque(iter(partial(sys.stdin.detach().read, bufsize), b''), maxlen=0)
</code></pre>
<p>Example:</p>
<pre><code>$ dd if=/dev/zero bs=1M count=1000 | python3 blackhole.py
</code></pre>
<p>It processes <em>~1.5 GB/s</em> with the default <code>bufsize</code> on my machine and only <em>~7.5 MB/s</em> if <code>bufsize=1</code>. That is, it is 200 times slower to read one byte at a time. Take it into account if you can rewrite your processing to use more than one byte at a time and <em>if</em> you need performance.</p>
<p><a href="http://docs.python.org/2/library/mmap.html"><code>mmap</code></a> allows you to treat a file as a <a href="http://docs.python.org/2/library/functions.html#bytearray"><code>bytearray</code></a> and a file object simultaneously. It can serve as an alternative to loading the whole file in memory if you need access to both interfaces. In particular, you can iterate one byte at a time over a memory-mapped file just using a plain <code>for</code>-loop:</p>
<pre><code>from mmap import ACCESS_READ, mmap
with open(filename, 'rb') as f, mmap(f.fileno(), 0, access=ACCESS_READ) as mm:
for byte in mm: # length is equal to the current file size
# Do stuff with byte
</code></pre>
<p><code>mmap</code> supports slice notation. For example, <code>mm[i:i+len]</code> returns <code>len</code> bytes from the file starting at position <code>i</code>. The context manager protocol is not supported before Python 3.2; you need to call <code>mm.close()</code> explicitly in this case. Iterating over each byte using <code>mmap</code> consumes more memory than <code>file.read(1)</code>, but <code>mmap</code> is an order of magnitude faster.</p>
| 16 | 2013-11-16T04:47:57Z | [
"python",
"file-io",
"binary"
] |
Reading binary file in Python and looping over each byte | 1,035,340 | <p>In Python, how do I read in a binary file and loop over each byte of that file?</p>
| 198 | 2009-06-23T21:26:52Z | 31,159,949 | <p>If you have a lot of binary data to read, you might want to consider the <a href="https://docs.python.org/3/library/struct.html" rel="nofollow">struct module</a>. It is documented as converting "between C and Python types", but of course, bytes are bytes, and whether those were created as C types does not matter. For example, if your binary data contains two 2-byte integers and one 4-byte integer, you can read them as follows (example taken from <code>struct</code> documentation):</p>
<pre><code>>>> struct.unpack('hhl', b'\x00\x01\x00\x02\x00\x00\x00\x03')
(1, 2, 3)
</code></pre>
<p>You might find this more convenient, faster, or both, than explicitly looping over the content of a file.</p>
| 1 | 2015-07-01T11:24:30Z | [
"python",
"file-io",
"binary"
] |
Reading binary file in Python and looping over each byte | 1,035,340 | <p>In Python, how do I read in a binary file and loop over each byte of that file?</p>
| 198 | 2009-06-23T21:26:52Z | 32,720,771 | <p>my solution actually returns a string:</p>
<pre><code>>>> from StringIO import StringIO
>>> from functools import partial # credit to J.F. Sebastian
>>> fl = StringIO('string\x00string2\x00') # simulated "file" object
>>> bytearray(iter(partial(fl.read, 1), b'\x00')).__str__() # read until terminated
'string'
>>> bytearray(iter(partial(fl.read, 1), b'\x00')).__str__() # again
'string2'
</code></pre>
<p>the only problem with this is if you're managing an external offset, you'll need to explicitly add 1 to make up for the termination character.</p>
<p>EDIT:<br>
typically though I'll do something like <code>array('B',[ord(c) for c in file.read()])</code> and do the data management manually from there.<br>
(this is the fastest way to handle file data, file.read(1) is many times slower)</p>
| 0 | 2015-09-22T15:20:23Z | [
"python",
"file-io",
"binary"
] |
Reading binary file in Python and looping over each byte | 1,035,340 | <p>In Python, how do I read in a binary file and loop over each byte of that file?</p>
| 198 | 2009-06-23T21:26:52Z | 37,222,446 | <blockquote>
<h1>Reading binary file in Python and looping over each byte</h1>
</blockquote>
<p>Let's make a file:</p>
<pre><code>>>> with open('foobarbaz', 'w') as f:
... f.write('foo\nbar\nbaz')
</code></pre>
<p>Now let's iterate over it, using the <code>rb</code> flag (read mode, bytes mode). </p>
<p>Note that the multiple for loops do not increase the complexity (which remains O(n)) - this is just how you lazily iterate over a file - line by line.</p>
<p>This will loop over each byte in the code, without any hacky <code>.read(1)</code> business. </p>
<pre><code>>>> with open('foobarbaz', 'rb') as f:
... for line in f:
... for byte in line:
... print(ord(byte))
...
102
111
111
10
98
97
114
10
98
97
122
</code></pre>
<p>This is far more Pythonic and natural than the while loop and complicatedness I've seen in the other answers here.</p>
<h2>Buffered Reading</h2>
<p>If you have large files with no newlines, you may want to buffer your reading. Python 2.7 requires <code>io.open</code> to get this:</p>
<pre><code>>>> import io
>>> with io.open('foobarbaz', 'rb') as f:
... for line in f:
... for byte in line:
... print(ord(byte))
</code></pre>
<p>And we now have a buffered reader:</p>
<pre><code>>>> f
<_io.BufferedReader name='foobarbaz'>
</code></pre>
<p>Python 3's builtin <code>open</code> function is 2's <code>io.open</code>.</p>
| 0 | 2016-05-14T04:16:06Z | [
"python",
"file-io",
"binary"
] |
Reading binary file in Python and looping over each byte | 1,035,340 | <p>In Python, how do I read in a binary file and loop over each byte of that file?</p>
| 198 | 2009-06-23T21:26:52Z | 39,683,695 | <p>Python 3, read all of the file at once:</p>
<pre><code>with open("filename", "rb") as binary_file:
# Read the whole file at once
data = binary_file.read()
print(data)
</code></pre>
<p>You can iterate whatever you want using <code>data</code> variable.</p>
| 0 | 2016-09-25T05:26:37Z | [
"python",
"file-io",
"binary"
] |
Python garbage collection | 1,035,489 | <p>I have created some python code which creates an object in a loop, and in every iteration overwrites this object with a new one of the same type. This is done 10.000 times, and Python takes up 7mb of memory every second until my 3gb RAM is used. Does anyone know of a way to remove the objects from memory?</p>
| 23 | 2009-06-23T21:59:01Z | 1,035,512 | <p>You haven't provided enough information - this depends on the specifics of the object you are creating and what else you're doing with it in the loop. If the object does not create circular references, it should be deallocated on the next iteration. For example, the code</p>
<pre><code>for x in range(100000):
obj = " " * 10000000
</code></pre>
<p>will not result in ever-increasing memory allocation.</p>
| 16 | 2009-06-23T22:07:41Z | [
"python",
"optimization",
"memory-management",
"garbage-collection"
] |
Python garbage collection | 1,035,489 | <p>I have created some python code which creates an object in a loop, and in every iteration overwrites this object with a new one of the same type. This is done 10.000 times, and Python takes up 7mb of memory every second until my 3gb RAM is used. Does anyone know of a way to remove the objects from memory?</p>
| 23 | 2009-06-23T21:59:01Z | 1,035,526 | <p>This is an old error that was corrected for some types in python 2.5. What was happening was that python was not so good at collecting things like empty lists/dictionaries/tupes/floats/ints. In python 2.5 this was fixed...mostly. However floats and ints are singletons for comparisons so once one of those is created it stays around as long as the interpreter is alive. I've been bitten by this worst when dealing with large amount of floats since they have a nasty habit of being unique. This was characterized <a href="http://evanjones.ca/python-memory.html">for python 2.4</a> and updated about it being folded into <a href="http://evanjones.ca/python-memory-part2.html">python 2.5</a></p>
<p>The best way I've found around it is to upgrade to python 2.5 or newer to take care of the lists/dictionaries/tuples issue. For numbers the only solution is to not let large amounts of numbers get into python. I've done it with my own wrapper to a c++ object, but I have the impression that numpy.array will give similar results.</p>
<p>As a post script I have no idea what has happened to this in python 3, but I'm suspicious that numbers are still part of a singleton. So the memory leak is actually a feature of the language.</p>
| 12 | 2009-06-23T22:11:24Z | [
"python",
"optimization",
"memory-management",
"garbage-collection"
] |
Python garbage collection | 1,035,489 | <p>I have created some python code which creates an object in a loop, and in every iteration overwrites this object with a new one of the same type. This is done 10.000 times, and Python takes up 7mb of memory every second until my 3gb RAM is used. Does anyone know of a way to remove the objects from memory?</p>
| 23 | 2009-06-23T21:59:01Z | 1,035,528 | <p>Here's one thing you can do at the REPL to force a dereferencing of a variable:</p>
<pre><code>>>> x = 5
>>> x
5
>>> del x
>>> x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined
</code></pre>
| 1 | 2009-06-23T22:11:59Z | [
"python",
"optimization",
"memory-management",
"garbage-collection"
] |
Python garbage collection | 1,035,489 | <p>I have created some python code which creates an object in a loop, and in every iteration overwrites this object with a new one of the same type. This is done 10.000 times, and Python takes up 7mb of memory every second until my 3gb RAM is used. Does anyone know of a way to remove the objects from memory?</p>
| 23 | 2009-06-23T21:59:01Z | 1,036,054 | <p>If you're creating circular references, your objects won't be deallocated immediately, but have to wait for a GC cycle to run.</p>
<p>You could use the <a href="https://docs.python.org/3/library/weakref.html" rel="nofollow">weakref</a> module to address this problem, or explicitly del your objects after use.</p>
| 3 | 2009-06-24T01:28:56Z | [
"python",
"optimization",
"memory-management",
"garbage-collection"
] |
Python garbage collection | 1,035,489 | <p>I have created some python code which creates an object in a loop, and in every iteration overwrites this object with a new one of the same type. This is done 10.000 times, and Python takes up 7mb of memory every second until my 3gb RAM is used. Does anyone know of a way to remove the objects from memory?</p>
| 23 | 2009-06-23T21:59:01Z | 2,037,626 | <p>I found that in my case (with Python 2.5.1), with circular references involving classes that have <code>__del__()</code> methods, not only was garbage collection not happening in a timely manner, the <code>__del__()</code> methods of my objects were never getting called, even when the script exited. So I used <a href="https://docs.python.org/2/library/weakref.html" rel="nofollow">weakref</a> to break the circular references and all was well.</p>
<p>Kudos to Miles who provided all the information in his comments for me to put this together.</p>
| 3 | 2010-01-10T16:30:33Z | [
"python",
"optimization",
"memory-management",
"garbage-collection"
] |
Python garbage collection | 1,035,489 | <p>I have created some python code which creates an object in a loop, and in every iteration overwrites this object with a new one of the same type. This is done 10.000 times, and Python takes up 7mb of memory every second until my 3gb RAM is used. Does anyone know of a way to remove the objects from memory?</p>
| 23 | 2009-06-23T21:59:01Z | 4,060,791 | <p>I think this is circular reference (though the question isn't explicit about this information.)</p>
<p>One way to solve this problem is to manually invoke garbage collection. When you manually run garbage collector, it will sweep circular referenced objects too.</p>
<pre><code>import gc
for i in xrange(10000):
j = myObj()
processObj(j)
#assuming count reference is not zero but still
#object won't remain usable after the iteration
if !(i%100):
gc.collect()
</code></pre>
<p>Here don't run garbage collector too often because it has its own overhead, e.g. if you run garbage collector in every loop, interpretation will become extremely slow.</p>
| 12 | 2010-10-30T21:37:29Z | [
"python",
"optimization",
"memory-management",
"garbage-collection"
] |
Google App Engine cannot find gdata module | 1,035,554 | <p>I can run a simple "Hello World" Google App Engine application on localhost with no problems. However, when I add the line "import gdata.auth" to my Python script I get "ImportError: No module named gdata.auth".</p>
<p>I have installed the gdata module and added the following line to my .bashrc:</p>
<pre>export PYTHONPATH=$PYTHONPATH:/Library/Python/2.5/site-packages/</pre>
<p>Is there anything else I need to do? Thanks.</p>
<p>EDIT: The strange thing is that if I run python from a shell and type "import gdata.auth" I do not get an error.</p>
| 4 | 2009-06-23T22:19:58Z | 1,035,670 | <p>try adding this to your script:</p>
<pre><code>import sys
sys.path.append('<directory where gdata.auth module is saved>')
import gdata.auth
</code></pre>
| 0 | 2009-06-23T22:48:49Z | [
"python",
"google-app-engine",
"osx",
"gdata",
"google-data-api"
] |
Google App Engine cannot find gdata module | 1,035,554 | <p>I can run a simple "Hello World" Google App Engine application on localhost with no problems. However, when I add the line "import gdata.auth" to my Python script I get "ImportError: No module named gdata.auth".</p>
<p>I have installed the gdata module and added the following line to my .bashrc:</p>
<pre>export PYTHONPATH=$PYTHONPATH:/Library/Python/2.5/site-packages/</pre>
<p>Is there anything else I need to do? Thanks.</p>
<p>EDIT: The strange thing is that if I run python from a shell and type "import gdata.auth" I do not get an error.</p>
| 4 | 2009-06-23T22:19:58Z | 1,036,152 | <p>Your .bashrc is not known to Google App Engine. Make sure the <code>gdata</code> directory (with all its proper contents) is under your application's main directory!</p>
<p>See <a href="http://code.google.com/appengine/articles/gdata.html">this article</a>, particularly (and I quote):</p>
<blockquote>
<p>To use this library with your Google
App Engine application, simply place
the library source files in your
application's directory, and import
them as you usually would. The source
directories you need to upload with
your application code are src/gdata
and src/atom. Then, be sure to call
the
<code>gdata.alt.appengine.run_on_appengine</code>
function on each instance of a
gdata.service.GDataService object.
There's nothing more to it than that!</p>
</blockquote>
| 9 | 2009-06-24T02:27:38Z | [
"python",
"google-app-engine",
"osx",
"gdata",
"google-data-api"
] |
Google App Engine cannot find gdata module | 1,035,554 | <p>I can run a simple "Hello World" Google App Engine application on localhost with no problems. However, when I add the line "import gdata.auth" to my Python script I get "ImportError: No module named gdata.auth".</p>
<p>I have installed the gdata module and added the following line to my .bashrc:</p>
<pre>export PYTHONPATH=$PYTHONPATH:/Library/Python/2.5/site-packages/</pre>
<p>Is there anything else I need to do? Thanks.</p>
<p>EDIT: The strange thing is that if I run python from a shell and type "import gdata.auth" I do not get an error.</p>
| 4 | 2009-06-23T22:19:58Z | 4,379,347 | <p>The gdata client library installation script installs the modules in the wrong directory for ubuntu python installation.</p>
<pre><code>sudo mv /usr/local/lib/python2.6/dist-packages/* /usr/lib/python2.6/dist-packages
</code></pre>
| 1 | 2010-12-07T16:58:42Z | [
"python",
"google-app-engine",
"osx",
"gdata",
"google-data-api"
] |
problem running scons | 1,035,581 | <p>I am trying to get started with <a href="http://www.scons.org/" rel="nofollow">scons</a>. I have Python 3.0.1 and downloaded Scons 1.2.0; when I try to run scons I get the following error. Am I doing something wrong here?</p>
<pre><code>C:\tmp\scons>c:\appl\python\3.0.1\Scripts\scons
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "c:\appl\python\3.0.1\Lib\site-packages\scons-1.2.0\SCons\__init__.py", l
ine 43, in <module>
import SCons.compat
File "c:\appl\python\3.0.1\Lib\site-packages\scons-1.2.0\SCons\compat\__init__
.py", line 208
raise Error, "Cannot move a directory '%s' into itself '%s'." % (src, dst)
^
SyntaxError: invalid syntax
</code></pre>
| 1 | 2009-06-23T22:25:00Z | 1,035,633 | <p>That's Python 2 syntax. I assume scons doesn't run on Python 3. You need to run it using Python 2. </p>
| 15 | 2009-06-23T22:37:20Z | [
"python",
"scons"
] |
Sensible python source line wrapping for printout | 1,035,721 | <p>I am working on a latex document that will require typesetting significant amounts of python source code. I'm using <a href="http://pygments.org/" rel="nofollow">pygments</a> (the python module, not the online demo) to encapsulate this python in latex, which works well except in the case of long individual lines - which simply continue off the page. I could manually wrap these lines except that this just doesn't seem that elegant a solution to me, and I prefer spending time puzzling about crazy automated solutions than on repetitive tasks.</p>
<p>What I would like is some way of processing the python source code to wrap the lines to a certain maximum character length, while preserving functionality. I've had a play around with some python and the closest I've come is inserting <code>\\\n</code> in the last whitespace before the maximum line length - but of course, if this ends up in strings and comments, things go wrong. Quite frankly, I'm not sure how to approach this problem.</p>
<p>So, is anyone aware of a module or tool that can process source code so that no lines exceed a certain length - or at least a good way to start to go about coding something like that?</p>
| 2 | 2009-06-23T23:07:54Z | 1,035,749 | <p>I'd check a reformat tool in an editor like NetBeans.</p>
<p>When you reformat java it properly fixes the lengths of lines both inside and outside of comments, if the same algorithm were applied to Python, it would work.</p>
<p>For Java it allows you to set any wrapping width and a bunch of other parameters. I'd be pretty surprised if that didn't exist either native or as a plugin.</p>
<p>Can't tell for sure just from the description, but it's worth a try:</p>
<p><a href="http://www.netbeans.org/features/python/" rel="nofollow">http://www.netbeans.org/features/python/</a></p>
| 1 | 2009-06-23T23:15:58Z | [
"python",
"latex",
"syntax-highlighting",
"code-formatting",
"pygments"
] |
Sensible python source line wrapping for printout | 1,035,721 | <p>I am working on a latex document that will require typesetting significant amounts of python source code. I'm using <a href="http://pygments.org/" rel="nofollow">pygments</a> (the python module, not the online demo) to encapsulate this python in latex, which works well except in the case of long individual lines - which simply continue off the page. I could manually wrap these lines except that this just doesn't seem that elegant a solution to me, and I prefer spending time puzzling about crazy automated solutions than on repetitive tasks.</p>
<p>What I would like is some way of processing the python source code to wrap the lines to a certain maximum character length, while preserving functionality. I've had a play around with some python and the closest I've come is inserting <code>\\\n</code> in the last whitespace before the maximum line length - but of course, if this ends up in strings and comments, things go wrong. Quite frankly, I'm not sure how to approach this problem.</p>
<p>So, is anyone aware of a module or tool that can process source code so that no lines exceed a certain length - or at least a good way to start to go about coding something like that?</p>
| 2 | 2009-06-23T23:07:54Z | 1,035,922 | <p>You might want to extend your current approach a bit, but using the <a href="http://docs.python.org/library/tokenize.html" rel="nofollow">tokenize</a> module from the standard library to determine where to put your line breaks. That way you can see the actual tokens (COMMENT, STRING, etc.) of your source code rather than just the whitespace-separated words.</p>
<p>Here is a short example of what tokenize can do:</p>
<pre><code>>>> from cStringIO import StringIO
>>> from tokenize import tokenize
>>>
>>> python_code = '''
... def foo(): # This is a comment
... print 'foo'
... '''
>>>
>>> fp = StringIO(python_code)
>>>
>>> tokenize(fp.readline)
1,0-1,1: NL '\n'
2,0-2,3: NAME 'def'
2,4-2,7: NAME 'foo'
2,7-2,8: OP '('
2,8-2,9: OP ')'
2,9-2,10: OP ':'
2,11-2,30: COMMENT '# This is a comment'
2,30-2,31: NEWLINE '\n'
3,0-3,4: INDENT ' '
3,4-3,9: NAME 'print'
3,10-3,15: STRING "'foo'"
3,15-3,16: NEWLINE '\n'
4,0-4,0: DEDENT ''
4,0-4,0: ENDMARKER ''
</code></pre>
| 3 | 2009-06-24T00:15:28Z | [
"python",
"latex",
"syntax-highlighting",
"code-formatting",
"pygments"
] |
Sensible python source line wrapping for printout | 1,035,721 | <p>I am working on a latex document that will require typesetting significant amounts of python source code. I'm using <a href="http://pygments.org/" rel="nofollow">pygments</a> (the python module, not the online demo) to encapsulate this python in latex, which works well except in the case of long individual lines - which simply continue off the page. I could manually wrap these lines except that this just doesn't seem that elegant a solution to me, and I prefer spending time puzzling about crazy automated solutions than on repetitive tasks.</p>
<p>What I would like is some way of processing the python source code to wrap the lines to a certain maximum character length, while preserving functionality. I've had a play around with some python and the closest I've come is inserting <code>\\\n</code> in the last whitespace before the maximum line length - but of course, if this ends up in strings and comments, things go wrong. Quite frankly, I'm not sure how to approach this problem.</p>
<p>So, is anyone aware of a module or tool that can process source code so that no lines exceed a certain length - or at least a good way to start to go about coding something like that?</p>
| 2 | 2009-06-23T23:07:54Z | 1,188,601 | <p>I use the <code>listings</code> package in LaTeX to insert source code; it does syntax highlight, linebreaks et al.</p>
<p>Put the following in your preamble:</p>
<pre><code>\usepackage{listings}
%\lstloadlanguages{Python} # Load only these languages
\newcommand{\MyHookSign}{\hbox{\ensuremath\hookleftarrow}}
\lstset{
% Language
language=Python,
% Basic setup
%basicstyle=\footnotesize,
basicstyle=\scriptsize,
keywordstyle=\bfseries,
commentstyle=,
% Looks
frame=single,
% Linebreaks
breaklines,
prebreak={\space\MyHookSign},
% Line numbering
tabsize=4,
stepnumber=5,
numbers=left,
firstnumber=1,
%numberstyle=\scriptsize,
numberstyle=\tiny,
% Above and beyond ASCII!
extendedchars=true
}
</code></pre>
<p>The package has hook for inline code, including entire files, showing it as figures, ...</p>
| 2 | 2009-07-27T14:47:04Z | [
"python",
"latex",
"syntax-highlighting",
"code-formatting",
"pygments"
] |
Setting the flags field of the IP header | 1,035,799 | <p>I have a simple Python script that uses the socket module to send a UDP packet. The script works fine on my Windows box, but on my Ubuntu Linux PC the packet it sends is slightly different. On Windows the flags field in the IP header is zero, but using the same code on Linux created a packet with the flags field set to 4. I'd like to modify my script so it has consistent behavior on Windows and Linux.</p>
<p>Is there a method for controlling the flags field in the socket module? Or, is this a setting I have to change in Linux?</p>
| 5 | 2009-06-23T23:33:21Z | 1,035,871 | <p><a href="http://construct.wikispaces.com/intro" rel="nofollow">construct</a> might do the job? </p>
| 1 | 2009-06-23T23:56:22Z | [
"python",
"sockets"
] |
Setting the flags field of the IP header | 1,035,799 | <p>I have a simple Python script that uses the socket module to send a UDP packet. The script works fine on my Windows box, but on my Ubuntu Linux PC the packet it sends is slightly different. On Windows the flags field in the IP header is zero, but using the same code on Linux created a packet with the flags field set to 4. I'd like to modify my script so it has consistent behavior on Windows and Linux.</p>
<p>Is there a method for controlling the flags field in the socket module? Or, is this a setting I have to change in Linux?</p>
| 5 | 2009-06-23T23:33:21Z | 1,035,878 | <p>I'm guessing that the flags field is actually set to 2 = b010 instead of 4 - flags equal to 4 is an invalid IP packet. Remember that flags is a 3 bit value in the <a href="http://en.wikipedia.org/wiki/IPv4#Packet%5Fstructure" rel="nofollow">IP Header</a>. I would expect to see UDP datagrams with a flags value of 2 which means "Don't fragment".</p>
<p>As for your question, I don't believe there is a way to set the IP flags directly without going all of the way to using <a href="http://en.wikipedia.org/wiki/Raw%5Fsocket" rel="nofollow">raw sockets</a>. I wouldn't worry about it since most applications don't really have a good reason to muck with IP or even UDP/TCP headers directly.</p>
| 2 | 2009-06-23T23:58:16Z | [
"python",
"sockets"
] |
Setting the flags field of the IP header | 1,035,799 | <p>I have a simple Python script that uses the socket module to send a UDP packet. The script works fine on my Windows box, but on my Ubuntu Linux PC the packet it sends is slightly different. On Windows the flags field in the IP header is zero, but using the same code on Linux created a packet with the flags field set to 4. I'd like to modify my script so it has consistent behavior on Windows and Linux.</p>
<p>Is there a method for controlling the flags field in the socket module? Or, is this a setting I have to change in Linux?</p>
| 5 | 2009-06-23T23:33:21Z | 1,044,918 | <p>Here's the route I ended up taking. I followed the link posted by SashaN in the comments of D.Shwley's answer and learned a little bit about why the "don't fragment" bit is set in Linux's UDP packets. Turns out it has something to do with PMTU discovery. Long story short, you can clear the don't fragment bit from your UDP packets in Python by using the setsockopts function in the socket object. </p>
<pre><code>import socket
IP_MTU_DISCOVER = 10
IP_PMTUDISC_DONT = 0 # Never send DF frames.
IP_PMTUDISC_WANT = 1 # Use per route hints.
IP_PMTUDISC_DO = 2 # Always DF.
IP_PMTUDISC_PROBE = 3 # Ignore dst pmtu.
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("10.0.0.1", 8000))
s.send("Hello World!") # DF bit is set in this packet
s.setsockopt(socket.SOL_IP, IP_MTU_DISCOVER, IP_PMTUDISC_DONT)
s.send("Hello World!") # DF bit is cleared in this packet
</code></pre>
| 6 | 2009-06-25T16:34:12Z | [
"python",
"sockets"
] |
Any Python Script to Save Websites Like Firefox? | 1,035,825 | <p>I am tired of clicking "File" and then "Save Page As" in Firefox when I want to save some websites.</p>
<p>Is there any script to do this in Python? I would like to save the pictures and css files so that when I read it offline, it looks normal.</p>
| 2 | 2009-06-23T23:40:19Z | 1,035,842 | <p>probably a tool like <a href="http://www.gnu.org/software/wget/" rel="nofollow">wget</a> is more appropriate for this type of thing.</p>
| 1 | 2009-06-23T23:45:21Z | [
"python"
] |
Any Python Script to Save Websites Like Firefox? | 1,035,825 | <p>I am tired of clicking "File" and then "Save Page As" in Firefox when I want to save some websites.</p>
<p>Is there any script to do this in Python? I would like to save the pictures and css files so that when I read it offline, it looks normal.</p>
| 2 | 2009-06-23T23:40:19Z | 1,035,850 | <p>This is a non-Python answer and I'm not sure what your machine is running, but have you consider using a <a href="http://stackoverflow.com/questions/522290/suggestions-for-a-site-ripper">site ripper</a> such as wget? </p>
<pre><code>import os
cmd = 'wget <parameters>'
os.system(cmd)
</code></pre>
| 0 | 2009-06-23T23:47:38Z | [
"python"
] |
Any Python Script to Save Websites Like Firefox? | 1,035,825 | <p>I am tired of clicking "File" and then "Save Page As" in Firefox when I want to save some websites.</p>
<p>Is there any script to do this in Python? I would like to save the pictures and css files so that when I read it offline, it looks normal.</p>
| 2 | 2009-06-23T23:40:19Z | 1,035,851 | <p>You could use wget</p>
<p>wget -m -k -E [url]</p>
<pre><code>-E, --html-extension save HTML documents with `.html' extension.
-m, --mirror shortcut for -N -r -l inf --no-remove-listing.
-k, --convert-links make links in downloaded HTML point to local files.
</code></pre>
| 8 | 2009-06-23T23:47:44Z | [
"python"
] |
Any Python Script to Save Websites Like Firefox? | 1,035,825 | <p>I am tired of clicking "File" and then "Save Page As" in Firefox when I want to save some websites.</p>
<p>Is there any script to do this in Python? I would like to save the pictures and css files so that when I read it offline, it looks normal.</p>
| 2 | 2009-06-23T23:40:19Z | 1,035,855 | <p>Like Cobbal stated, this is largely what wget is designed to do. I believe there's some flags/arguments that you can set to make it download the entire page, CSS + all. I suggest just alias-ing into something more convenient to type, or tossing it into a quick script.</p>
| 1 | 2009-06-23T23:48:29Z | [
"python"
] |
Any Python Script to Save Websites Like Firefox? | 1,035,825 | <p>I am tired of clicking "File" and then "Save Page As" in Firefox when I want to save some websites.</p>
<p>Is there any script to do this in Python? I would like to save the pictures and css files so that when I read it offline, it looks normal.</p>
| 2 | 2009-06-23T23:40:19Z | 1,036,063 | <p>Have you looked at <a href="http://www.httrack.com/" rel="nofollow">HTTrack</a>?</p>
| 0 | 2009-06-24T01:34:49Z | [
"python"
] |
Recursively convert python object graph to dictionary | 1,036,409 | <p>I'm trying to convert the data from a simple object graph into a dictionary. I don't need type information or methods and I don't need to be able to convert it back to an object again. </p>
<p>I found <a href="http://stackoverflow.com/questions/61517/python-dictionary-from-an-objects-fields">this question about creating a dictionary from an object's fields</a>, but it doesn't do it recursively.</p>
<p>Being relatively new to python, I'm concerned that my solution may be ugly, or unpythonic, or broken in some obscure way, or just plain old NIH.</p>
<p>My first attempt appeared to work until I tried it with lists and dictionaries, and it seemed easier just to check if the object passed had an internal dictionary, and if not, to just treat it as a value (rather than doing all that isinstance checking). My previous attempts also didn't recurse into lists of objects:</p>
<pre><code>def todict(obj):
if hasattr(obj, "__iter__"):
return [todict(v) for v in obj]
elif hasattr(obj, "__dict__"):
return dict([(key, todict(value))
for key, value in obj.__dict__.iteritems()
if not callable(value) and not key.startswith('_')])
else:
return obj
</code></pre>
<p>This seems to work better and doesn't require exceptions, but again I'm still not sure if there are cases here I'm not aware of where it falls down.</p>
<p>Any suggestions would be much appreciated.</p>
| 16 | 2009-06-24T04:30:36Z | 1,036,435 | <p>I don't know what is the purpose of checking for basestring or object is? also <strong>dict</strong> will not contain any callables unless you have attributes pointing to such callables, but in that case isn't that part of object?</p>
<p>so instead of checking for various types and values, let todict convert the object and if it raises the exception, user the orginal value.</p>
<p>todict will only raise exception if obj doesn't have <strong>dict</strong>
e.g.</p>
<pre><code>class A(object):
def __init__(self):
self.a1 = 1
class B(object):
def __init__(self):
self.b1 = 1
self.b2 = 2
self.o1 = A()
def func1(self):
pass
def todict(obj):
data = {}
for key, value in obj.__dict__.iteritems():
try:
data[key] = todict(value)
except AttributeError:
data[key] = value
return data
b = B()
print todict(b)
</code></pre>
<p>it prints {'b1': 1, 'b2': 2, 'o1': {'a1': 1}}
there may be some other cases to consider, but it may be a good start</p>
<p><strong>special cases</strong>
if a object uses slots then you will not be able to get <strong>dict</strong> e.g.</p>
<pre><code>class A(object):
__slots__ = ["a1"]
def __init__(self):
self.a1 = 1
</code></pre>
<p>fix for the slots cases can be to use dir() instead of directly using the <strong>dict</strong></p>
| 4 | 2009-06-24T04:41:47Z | [
"python",
"python-2.6"
] |
Recursively convert python object graph to dictionary | 1,036,409 | <p>I'm trying to convert the data from a simple object graph into a dictionary. I don't need type information or methods and I don't need to be able to convert it back to an object again. </p>
<p>I found <a href="http://stackoverflow.com/questions/61517/python-dictionary-from-an-objects-fields">this question about creating a dictionary from an object's fields</a>, but it doesn't do it recursively.</p>
<p>Being relatively new to python, I'm concerned that my solution may be ugly, or unpythonic, or broken in some obscure way, or just plain old NIH.</p>
<p>My first attempt appeared to work until I tried it with lists and dictionaries, and it seemed easier just to check if the object passed had an internal dictionary, and if not, to just treat it as a value (rather than doing all that isinstance checking). My previous attempts also didn't recurse into lists of objects:</p>
<pre><code>def todict(obj):
if hasattr(obj, "__iter__"):
return [todict(v) for v in obj]
elif hasattr(obj, "__dict__"):
return dict([(key, todict(value))
for key, value in obj.__dict__.iteritems()
if not callable(value) and not key.startswith('_')])
else:
return obj
</code></pre>
<p>This seems to work better and doesn't require exceptions, but again I'm still not sure if there are cases here I'm not aware of where it falls down.</p>
<p>Any suggestions would be much appreciated.</p>
| 16 | 2009-06-24T04:30:36Z | 1,036,575 | <p>In Python there are many ways of making objects behave slightly differently, like metaclasses and whatnot, and it can override <strong>getattr</strong> and thereby have "magical" attributes you can't see through <strong>dict</strong>, etc. In short, it's unlikely that you are going to get a 100% complete picture in the generic case with whatever method you use.</p>
<p>Therefore, the answer is: If it works for you in the use case you have now, then the code is correct. ;-)</p>
<p>To make somewhat more generic code you could do something like this:</p>
<pre><code>import types
def todict(obj):
# Functions, methods and None have no further info of interest.
if obj is None or isinstance(subobj, (types.FunctionType, types.MethodType))
return obj
try: # If it's an iterable, return all the contents
return [todict(x) for x in iter(obj)]
except TypeError:
pass
try: # If it's a dictionary, recurse over it:
result = {}
for key in obj:
result[key] = todict(obj)
return result
except TypeError:
pass
# It's neither a list nor a dict, so it's a normal object.
# Get everything from dir and __dict__. That should be most things we can get hold of.
attrs = set(dir(obj))
try:
attrs.update(obj.__dict__.keys())
except AttributeError:
pass
result = {}
for attr in attrs:
result[attr] = todict(getattr(obj, attr, None))
return result
</code></pre>
<p>Something like that. That code is untested, though. This still doesn't cover the case when you override <strong>getattr</strong>, and I'm sure there are many more cases that it doens't cover and may not be coverable. :)</p>
| 2 | 2009-06-24T05:46:05Z | [
"python",
"python-2.6"
] |
Recursively convert python object graph to dictionary | 1,036,409 | <p>I'm trying to convert the data from a simple object graph into a dictionary. I don't need type information or methods and I don't need to be able to convert it back to an object again. </p>
<p>I found <a href="http://stackoverflow.com/questions/61517/python-dictionary-from-an-objects-fields">this question about creating a dictionary from an object's fields</a>, but it doesn't do it recursively.</p>
<p>Being relatively new to python, I'm concerned that my solution may be ugly, or unpythonic, or broken in some obscure way, or just plain old NIH.</p>
<p>My first attempt appeared to work until I tried it with lists and dictionaries, and it seemed easier just to check if the object passed had an internal dictionary, and if not, to just treat it as a value (rather than doing all that isinstance checking). My previous attempts also didn't recurse into lists of objects:</p>
<pre><code>def todict(obj):
if hasattr(obj, "__iter__"):
return [todict(v) for v in obj]
elif hasattr(obj, "__dict__"):
return dict([(key, todict(value))
for key, value in obj.__dict__.iteritems()
if not callable(value) and not key.startswith('_')])
else:
return obj
</code></pre>
<p>This seems to work better and doesn't require exceptions, but again I'm still not sure if there are cases here I'm not aware of where it falls down.</p>
<p>Any suggestions would be much appreciated.</p>
| 16 | 2009-06-24T04:30:36Z | 1,118,038 | <p>An amalgamation of my own attempt and clues derived from Anurag Uniyal and Lennart Regebro's answers works best for me:</p>
<pre><code>def todict(obj, classkey=None):
if isinstance(obj, dict):
data = {}
for (k, v) in obj.items():
data[k] = todict(v, classkey)
return data
elif hasattr(obj, "_ast"):
return todict(obj._ast())
elif hasattr(obj, "__iter__"):
return [todict(v, classkey) for v in obj]
elif hasattr(obj, "__dict__"):
data = dict([(key, todict(value, classkey))
for key, value in obj.__dict__.iteritems()
if not callable(value) and not key.startswith('_')])
if classkey is not None and hasattr(obj, "__class__"):
data[classkey] = obj.__class__.__name__
return data
else:
return obj
</code></pre>
| 24 | 2009-07-13T07:06:27Z | [
"python",
"python-2.6"
] |
Recursively convert python object graph to dictionary | 1,036,409 | <p>I'm trying to convert the data from a simple object graph into a dictionary. I don't need type information or methods and I don't need to be able to convert it back to an object again. </p>
<p>I found <a href="http://stackoverflow.com/questions/61517/python-dictionary-from-an-objects-fields">this question about creating a dictionary from an object's fields</a>, but it doesn't do it recursively.</p>
<p>Being relatively new to python, I'm concerned that my solution may be ugly, or unpythonic, or broken in some obscure way, or just plain old NIH.</p>
<p>My first attempt appeared to work until I tried it with lists and dictionaries, and it seemed easier just to check if the object passed had an internal dictionary, and if not, to just treat it as a value (rather than doing all that isinstance checking). My previous attempts also didn't recurse into lists of objects:</p>
<pre><code>def todict(obj):
if hasattr(obj, "__iter__"):
return [todict(v) for v in obj]
elif hasattr(obj, "__dict__"):
return dict([(key, todict(value))
for key, value in obj.__dict__.iteritems()
if not callable(value) and not key.startswith('_')])
else:
return obj
</code></pre>
<p>This seems to work better and doesn't require exceptions, but again I'm still not sure if there are cases here I'm not aware of where it falls down.</p>
<p>Any suggestions would be much appreciated.</p>
| 16 | 2009-06-24T04:30:36Z | 16,993,744 | <p>A slow but easy way to do this is to use <code>jsonpickle</code> to convert the object to a JSON string and then <code>json.loads</code> to convert it back to a python dictionary:</p>
<p><code>dict = json.loads(jsonpickle.encode( obj, unpicklable=False ))</code></p>
| 1 | 2013-06-07T22:12:37Z | [
"python",
"python-2.6"
] |
Recursively convert python object graph to dictionary | 1,036,409 | <p>I'm trying to convert the data from a simple object graph into a dictionary. I don't need type information or methods and I don't need to be able to convert it back to an object again. </p>
<p>I found <a href="http://stackoverflow.com/questions/61517/python-dictionary-from-an-objects-fields">this question about creating a dictionary from an object's fields</a>, but it doesn't do it recursively.</p>
<p>Being relatively new to python, I'm concerned that my solution may be ugly, or unpythonic, or broken in some obscure way, or just plain old NIH.</p>
<p>My first attempt appeared to work until I tried it with lists and dictionaries, and it seemed easier just to check if the object passed had an internal dictionary, and if not, to just treat it as a value (rather than doing all that isinstance checking). My previous attempts also didn't recurse into lists of objects:</p>
<pre><code>def todict(obj):
if hasattr(obj, "__iter__"):
return [todict(v) for v in obj]
elif hasattr(obj, "__dict__"):
return dict([(key, todict(value))
for key, value in obj.__dict__.iteritems()
if not callable(value) and not key.startswith('_')])
else:
return obj
</code></pre>
<p>This seems to work better and doesn't require exceptions, but again I'm still not sure if there are cases here I'm not aware of where it falls down.</p>
<p>Any suggestions would be much appreciated.</p>
| 16 | 2009-06-24T04:30:36Z | 22,679,824 | <p>I realize that this answer is a few years too late, but I thought it might be worth sharing since it's a Python 3.3+ compatible modification to the original solution by @Shabbyrobe that has generally worked well for me:</p>
<pre><code>import collections
try:
# Python 2.7+
basestring
except NameError:
# Python 3.3+
basestring = str
def todict(obj):
"""
Recursively convert a Python object graph to sequences (lists)
and mappings (dicts) of primitives (bool, int, float, string, ...)
"""
if isinstance(obj, basestring):
return obj
elif isinstance(obj, dict):
return dict((key, todict(val)) for key, val in obj.items())
elif isinstance(obj, collections.Iterable):
return [todict(val) for val in obj]
elif hasattr(obj, '__dict__'):
return todict(vars(obj))
elif hasattr(obj, '__slots__'):
return todict(dict((name, getattr(obj, name)) for name in getattr(obj, '__slots__')))
return obj
</code></pre>
<p>If you're not interested in callable attributes, for example, they can be stripped in the dictionary comprehension:</p>
<pre><code>elif isinstance(obj, dict):
return dict((key, todict(val)) for key, val in obj.items() if not callable(val))
</code></pre>
| 0 | 2014-03-27T06:24:19Z | [
"python",
"python-2.6"
] |
Django: Model name clash | 1,036,506 | <p>I am trying to use different open source apps in my project. Problem is that there is a same Model name used by two different apps with their own model definition. </p>
<p>I tried using:</p>
<pre><code> class Meta:
db_table = "db_name"
</code></pre>
<p>but it didn't work. I am still getting field name clash error at syncdb. Any suggestions.</p>
<p><strong>Update</strong></p>
<p>I am actually trying to integrate Satchmo with Pinax. And the error is:</p>
<blockquote>
<p>Error: One or more models did not validate:</p>
<p>contact.contact: Accessor for field 'user' clashes with related m2m field 'User.contact_set'. Add a related_name argument to the definition for 'user'.</p>
<p>friends.contact: Accessor for m2m field 'users' clashes with related field User.contact_set'. Add a related_name argument to the definition for 'users'.</p>
</blockquote>
<p>You are right, table names are already unique. I analyzed the model and the Model 'Contact' is in two models of two different apps. When I comment out one of these models, it works fine. </p>
<p>May be the error is there because both apps are in PYTHON_PATH and when other app defines the its model with same name the clash occurs.</p>
| 3 | 2009-06-24T05:19:37Z | 1,045,135 | <p>The problem is that both Satchmo and Pinax have a Contact model with a ForeignKey to User. Django tries to add a "contact_set" reverse relationship attribute to User for each of those ForeignKeys, so there is a clash.</p>
<p>The solution is to add something like related_name="pinax_contact_set" as an argument to the ForeignKey in Pinax's Contact model, or similarly in the Satchmo Contact model. That will require editing the source directly for one or the other. You might be able to find a way to do it via monkeypatching, but I'd expect that to be tricky.</p>
| 5 | 2009-06-25T17:16:28Z | [
"python",
"django",
"django-models"
] |
Python's asyncore to periodically send data using a variable timeout. Is there a better way? | 1,036,646 | <p>I wanted to write a server that a client could connect to and receive periodic updates without having to poll. The problem I have experienced with asyncore is that if you do not return true when dispatcher.writable() is called, you have to wait until after the asyncore.loop has timed out (default is 30s).</p>
<p>The two ways I have tried to work around this is 1) reduce timeout to a low value or 2) query connections for when they will next update and generate an adequate timeout value. However if you refer to 'Select Law' in 'man 2 select_tut', it states, "You should always try to use select() without a timeout."</p>
<p>Is there a better way to do this? Twisted maybe? I wanted to try and avoid extra threads. I'll include the variable timeout example here:</p>
<pre><code>#!/usr/bin/python
import time
import socket
import asyncore
# in seconds
UPDATE_PERIOD = 4.0
class Channel(asyncore.dispatcher):
def __init__(self, sock, sck_map):
asyncore.dispatcher.__init__(self, sock=sock, map=sck_map)
self.last_update = 0.0 # should update immediately
self.send_buf = ''
self.recv_buf = ''
def writable(self):
return len(self.send_buf) > 0
def handle_write(self):
nbytes = self.send(self.send_buf)
self.send_buf = self.send_buf[nbytes:]
def handle_read(self):
print 'read'
print 'recv:', self.recv(4096)
def handle_close(self):
print 'close'
self.close()
# added for variable timeout
def update(self):
if time.time() >= self.next_update():
self.send_buf += 'hello %f\n'%(time.time())
self.last_update = time.time()
def next_update(self):
return self.last_update + UPDATE_PERIOD
class Server(asyncore.dispatcher):
def __init__(self, port, sck_map):
asyncore.dispatcher.__init__(self, map=sck_map)
self.port = port
self.sck_map = sck_map
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind( ("", port))
self.listen(16)
print "listening on port", self.port
def handle_accept(self):
(conn, addr) = self.accept()
Channel(sock=conn, sck_map=self.sck_map)
# added for variable timeout
def update(self):
pass
def next_update(self):
return None
sck_map = {}
server = Server(9090, sck_map)
while True:
next_update = time.time() + 30.0
for c in sck_map.values():
c.update() # <-- fill write buffers
n = c.next_update()
#print 'n:',n
if n is not None:
next_update = min(next_update, n)
_timeout = max(0.1, next_update - time.time())
asyncore.loop(timeout=_timeout, count=1, map=sck_map)
</code></pre>
| 8 | 2009-06-24T06:11:04Z | 1,036,817 | <p>The "select law" doesn't apply to your case, as you have not only client-triggered (pure server) activities, but also time-triggered activities - this is precisely what the select timeout is for. What the law should really say is "if you specify a timeout, make sure you actually have to do something useful when the timeout arrives". The law is meant to protect against busy-waiting; your code does not busy-wait.</p>
<p>I would not set _timeout to the maximum of 0.1 and the next update time, but to the maximum of 0.0 and the next timeout. IOW, if an update period has expired while you were doing updates, you should do that specific update right away.</p>
<p>Instead of asking each channel every time whether it wants to update, you could store all channels in a priority queue (sorted by next-update time), and then only run update for the earliest channels (until you find one whose update time has not arrived). You can use the heapq module for that.</p>
<p>You can also save a few system calls by not having each channel ask for the current time, but only poll the current time once, and pass it to .update.</p>
| 4 | 2009-06-24T07:10:18Z | [
"python",
"sockets",
"asynchronous"
] |
Python's asyncore to periodically send data using a variable timeout. Is there a better way? | 1,036,646 | <p>I wanted to write a server that a client could connect to and receive periodic updates without having to poll. The problem I have experienced with asyncore is that if you do not return true when dispatcher.writable() is called, you have to wait until after the asyncore.loop has timed out (default is 30s).</p>
<p>The two ways I have tried to work around this is 1) reduce timeout to a low value or 2) query connections for when they will next update and generate an adequate timeout value. However if you refer to 'Select Law' in 'man 2 select_tut', it states, "You should always try to use select() without a timeout."</p>
<p>Is there a better way to do this? Twisted maybe? I wanted to try and avoid extra threads. I'll include the variable timeout example here:</p>
<pre><code>#!/usr/bin/python
import time
import socket
import asyncore
# in seconds
UPDATE_PERIOD = 4.0
class Channel(asyncore.dispatcher):
def __init__(self, sock, sck_map):
asyncore.dispatcher.__init__(self, sock=sock, map=sck_map)
self.last_update = 0.0 # should update immediately
self.send_buf = ''
self.recv_buf = ''
def writable(self):
return len(self.send_buf) > 0
def handle_write(self):
nbytes = self.send(self.send_buf)
self.send_buf = self.send_buf[nbytes:]
def handle_read(self):
print 'read'
print 'recv:', self.recv(4096)
def handle_close(self):
print 'close'
self.close()
# added for variable timeout
def update(self):
if time.time() >= self.next_update():
self.send_buf += 'hello %f\n'%(time.time())
self.last_update = time.time()
def next_update(self):
return self.last_update + UPDATE_PERIOD
class Server(asyncore.dispatcher):
def __init__(self, port, sck_map):
asyncore.dispatcher.__init__(self, map=sck_map)
self.port = port
self.sck_map = sck_map
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind( ("", port))
self.listen(16)
print "listening on port", self.port
def handle_accept(self):
(conn, addr) = self.accept()
Channel(sock=conn, sck_map=self.sck_map)
# added for variable timeout
def update(self):
pass
def next_update(self):
return None
sck_map = {}
server = Server(9090, sck_map)
while True:
next_update = time.time() + 30.0
for c in sck_map.values():
c.update() # <-- fill write buffers
n = c.next_update()
#print 'n:',n
if n is not None:
next_update = min(next_update, n)
_timeout = max(0.1, next_update - time.time())
asyncore.loop(timeout=_timeout, count=1, map=sck_map)
</code></pre>
| 8 | 2009-06-24T06:11:04Z | 1,036,918 | <p>I would use Twisted, long time since I used asyncore but I think this should be the twisted equivalent (not tested, written from memory):</p>
<pre><code>from twisted.internet import reactor, protocol
import time
UPDATE_PERIOD = 4.0
class MyClient(protocol.Protocol):
def connectionMade(self):
self.updateCall = reactor.callLater(UPDATE_PERIOD, self.update)
def connectionLost(self, reason):
self.updateCall.cancel()
def update(self):
self.transport.write("hello %f\n" % (time.time(),))
def dataReceived(self, data):
print "recv:", data
f = protocol.ServerFactory()
f.protocol = MyClient
reactor.listenTCP(9090, f)
reactor.run()
</code></pre>
| 1 | 2009-06-24T07:38:11Z | [
"python",
"sockets",
"asynchronous"
] |
Python's asyncore to periodically send data using a variable timeout. Is there a better way? | 1,036,646 | <p>I wanted to write a server that a client could connect to and receive periodic updates without having to poll. The problem I have experienced with asyncore is that if you do not return true when dispatcher.writable() is called, you have to wait until after the asyncore.loop has timed out (default is 30s).</p>
<p>The two ways I have tried to work around this is 1) reduce timeout to a low value or 2) query connections for when they will next update and generate an adequate timeout value. However if you refer to 'Select Law' in 'man 2 select_tut', it states, "You should always try to use select() without a timeout."</p>
<p>Is there a better way to do this? Twisted maybe? I wanted to try and avoid extra threads. I'll include the variable timeout example here:</p>
<pre><code>#!/usr/bin/python
import time
import socket
import asyncore
# in seconds
UPDATE_PERIOD = 4.0
class Channel(asyncore.dispatcher):
def __init__(self, sock, sck_map):
asyncore.dispatcher.__init__(self, sock=sock, map=sck_map)
self.last_update = 0.0 # should update immediately
self.send_buf = ''
self.recv_buf = ''
def writable(self):
return len(self.send_buf) > 0
def handle_write(self):
nbytes = self.send(self.send_buf)
self.send_buf = self.send_buf[nbytes:]
def handle_read(self):
print 'read'
print 'recv:', self.recv(4096)
def handle_close(self):
print 'close'
self.close()
# added for variable timeout
def update(self):
if time.time() >= self.next_update():
self.send_buf += 'hello %f\n'%(time.time())
self.last_update = time.time()
def next_update(self):
return self.last_update + UPDATE_PERIOD
class Server(asyncore.dispatcher):
def __init__(self, port, sck_map):
asyncore.dispatcher.__init__(self, map=sck_map)
self.port = port
self.sck_map = sck_map
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind( ("", port))
self.listen(16)
print "listening on port", self.port
def handle_accept(self):
(conn, addr) = self.accept()
Channel(sock=conn, sck_map=self.sck_map)
# added for variable timeout
def update(self):
pass
def next_update(self):
return None
sck_map = {}
server = Server(9090, sck_map)
while True:
next_update = time.time() + 30.0
for c in sck_map.values():
c.update() # <-- fill write buffers
n = c.next_update()
#print 'n:',n
if n is not None:
next_update = min(next_update, n)
_timeout = max(0.1, next_update - time.time())
asyncore.loop(timeout=_timeout, count=1, map=sck_map)
</code></pre>
| 8 | 2009-06-24T06:11:04Z | 2,703,669 | <p>Maybe you can do this with <code>sched.scheduler</code>, like this (n.b. not tested):</p>
<pre><code>import sched, asyncore, time
# Create a scheduler with a delay function that calls asyncore.loop
scheduler = sched.scheduler(time.time, lambda t: _poll_loop(t, time.time()) )
# Add the update timeouts with scheduler.enter
# ...
def _poll_loop(timeout, start_time):
asyncore.loop(timeout, count=1)
finish_time = time.time()
timeleft = finish_time - start_time
if timeleft > timeout: # there was a message and the timeout delay is not finished
_poll_loop(timeleft, finish_time) # so wait some more polling the socket
def main_loop():
while True:
if scheduler.empty():
asyncore.loop(30.0, count=1) # just default timeout, use what suits you
# add other work that might create scheduled events here
else:
scheduler.run()
</code></pre>
| 3 | 2010-04-24T07:56:52Z | [
"python",
"sockets",
"asynchronous"
] |
Python's asyncore to periodically send data using a variable timeout. Is there a better way? | 1,036,646 | <p>I wanted to write a server that a client could connect to and receive periodic updates without having to poll. The problem I have experienced with asyncore is that if you do not return true when dispatcher.writable() is called, you have to wait until after the asyncore.loop has timed out (default is 30s).</p>
<p>The two ways I have tried to work around this is 1) reduce timeout to a low value or 2) query connections for when they will next update and generate an adequate timeout value. However if you refer to 'Select Law' in 'man 2 select_tut', it states, "You should always try to use select() without a timeout."</p>
<p>Is there a better way to do this? Twisted maybe? I wanted to try and avoid extra threads. I'll include the variable timeout example here:</p>
<pre><code>#!/usr/bin/python
import time
import socket
import asyncore
# in seconds
UPDATE_PERIOD = 4.0
class Channel(asyncore.dispatcher):
def __init__(self, sock, sck_map):
asyncore.dispatcher.__init__(self, sock=sock, map=sck_map)
self.last_update = 0.0 # should update immediately
self.send_buf = ''
self.recv_buf = ''
def writable(self):
return len(self.send_buf) > 0
def handle_write(self):
nbytes = self.send(self.send_buf)
self.send_buf = self.send_buf[nbytes:]
def handle_read(self):
print 'read'
print 'recv:', self.recv(4096)
def handle_close(self):
print 'close'
self.close()
# added for variable timeout
def update(self):
if time.time() >= self.next_update():
self.send_buf += 'hello %f\n'%(time.time())
self.last_update = time.time()
def next_update(self):
return self.last_update + UPDATE_PERIOD
class Server(asyncore.dispatcher):
def __init__(self, port, sck_map):
asyncore.dispatcher.__init__(self, map=sck_map)
self.port = port
self.sck_map = sck_map
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind( ("", port))
self.listen(16)
print "listening on port", self.port
def handle_accept(self):
(conn, addr) = self.accept()
Channel(sock=conn, sck_map=self.sck_map)
# added for variable timeout
def update(self):
pass
def next_update(self):
return None
sck_map = {}
server = Server(9090, sck_map)
while True:
next_update = time.time() + 30.0
for c in sck_map.values():
c.update() # <-- fill write buffers
n = c.next_update()
#print 'n:',n
if n is not None:
next_update = min(next_update, n)
_timeout = max(0.1, next_update - time.time())
asyncore.loop(timeout=_timeout, count=1, map=sck_map)
</code></pre>
| 8 | 2009-06-24T06:11:04Z | 4,956,882 | <p>This is basically demiurgus' solution with the rough edges made round. It retains his basic idea, but prevents RuntimeErrors and busy loops and is tested. [Edit: resolved issues with modifying the scheduler during _delay]</p>
<pre><code>class asynschedcore(sched.scheduler):
"""Combine sched.scheduler and asyncore.loop."""
# On receiving a signal asyncore kindly restarts select. However the signal
# handler might change the scheduler instance. This tunable determines the
# maximum time in seconds to spend in asycore.loop before reexamining the
# scheduler.
maxloop = 30
def __init__(self, map=None):
sched.scheduler.__init__(self, time.time, self._delay)
if map is None:
self._asynmap = asyncore.socket_map
else:
self._asynmap = map
self._abort_delay = False
def _maybe_abort_delay(self):
if not self._abort_delay:
return False
# Returning from this function causes the next event to be executed, so
# it might be executed too early. This can be avoided by modifying the
# head of the queue. Also note that enterabs sets _abort_delay to True.
self.enterabs(0, 0, lambda:None, ())
self._abort_delay = False
return True
def _delay(self, timeout):
if self._maybe_abort_delay():
return
if 0 == timeout:
# Should we support this hack, too?
# asyncore.loop(0, map=self._asynmap, count=1)
return
now = time.time()
finish = now + timeout
while now < finish and self._asynmap:
asyncore.loop(min(finish - now, self.maxloop), map=self._asynmap,
count=1)
if self._maybe_abort_delay():
return
now = time.time()
if now < finish:
time.sleep(finish - now)
def enterabs(self, abstime, priority, action, argument):
# We might insert an event before the currently next event.
self._abort_delay = True
return sched.scheduler.enterabs(self, abstime, priority, action,
argument)
# Overwriting enter is not necessary, because it is implemented using enter.
def cancel(self, event):
# We might cancel the next event.
self._abort_delay = True
return sched.scheduler.cancel(self, event)
def run(self):
"""Runs as long as either an event is scheduled or there are
sockets in the map."""
while True:
if not self.empty():
sched.scheduler.run(self)
elif self._asynmap:
asyncore.loop(self.maxloop, map=self._asynmap, count=1)
else:
break
</code></pre>
| 2 | 2011-02-10T12:08:57Z | [
"python",
"sockets",
"asynchronous"
] |
Python's asyncore to periodically send data using a variable timeout. Is there a better way? | 1,036,646 | <p>I wanted to write a server that a client could connect to and receive periodic updates without having to poll. The problem I have experienced with asyncore is that if you do not return true when dispatcher.writable() is called, you have to wait until after the asyncore.loop has timed out (default is 30s).</p>
<p>The two ways I have tried to work around this is 1) reduce timeout to a low value or 2) query connections for when they will next update and generate an adequate timeout value. However if you refer to 'Select Law' in 'man 2 select_tut', it states, "You should always try to use select() without a timeout."</p>
<p>Is there a better way to do this? Twisted maybe? I wanted to try and avoid extra threads. I'll include the variable timeout example here:</p>
<pre><code>#!/usr/bin/python
import time
import socket
import asyncore
# in seconds
UPDATE_PERIOD = 4.0
class Channel(asyncore.dispatcher):
def __init__(self, sock, sck_map):
asyncore.dispatcher.__init__(self, sock=sock, map=sck_map)
self.last_update = 0.0 # should update immediately
self.send_buf = ''
self.recv_buf = ''
def writable(self):
return len(self.send_buf) > 0
def handle_write(self):
nbytes = self.send(self.send_buf)
self.send_buf = self.send_buf[nbytes:]
def handle_read(self):
print 'read'
print 'recv:', self.recv(4096)
def handle_close(self):
print 'close'
self.close()
# added for variable timeout
def update(self):
if time.time() >= self.next_update():
self.send_buf += 'hello %f\n'%(time.time())
self.last_update = time.time()
def next_update(self):
return self.last_update + UPDATE_PERIOD
class Server(asyncore.dispatcher):
def __init__(self, port, sck_map):
asyncore.dispatcher.__init__(self, map=sck_map)
self.port = port
self.sck_map = sck_map
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind( ("", port))
self.listen(16)
print "listening on port", self.port
def handle_accept(self):
(conn, addr) = self.accept()
Channel(sock=conn, sck_map=self.sck_map)
# added for variable timeout
def update(self):
pass
def next_update(self):
return None
sck_map = {}
server = Server(9090, sck_map)
while True:
next_update = time.time() + 30.0
for c in sck_map.values():
c.update() # <-- fill write buffers
n = c.next_update()
#print 'n:',n
if n is not None:
next_update = min(next_update, n)
_timeout = max(0.1, next_update - time.time())
asyncore.loop(timeout=_timeout, count=1, map=sck_map)
</code></pre>
| 8 | 2009-06-24T06:11:04Z | 6,640,413 | <p>Maybe I don't understand what the OP was trying to accomplish, but I just solved this issue using 1 thread that gets a weakref of each Channel(asyncore.dispatcher) object. This thread determines its own timing and will send the Channel an update periodically using a Queue in that channel. It gets the Queue from the Channel object by calling getQueue. </p>
<p>The reason I use a weakref is because clients are transient. If the channel dies then the weakref returns None. That way the timing thread doesn't keep old objects alive because it references them.</p>
<p>I know the OP wanted to avoid threads, but this solution is very simple. It only ever creates one thread and it talks to any Channels that are created as the Server object adds them to the threads list of objects to monitor.</p>
| 0 | 2011-07-10T09:55:48Z | [
"python",
"sockets",
"asynchronous"
] |
Python Web-based Bot | 1,036,660 | <p>I am trying to write a Python-based Web Bot that can read and interpret an HTML page, then execute an onClick function and receive the resulting new HTML page. I can already read the HTML page and I can determine the functions to be called by the onClick command, but I have no idea how to execute those functions or how to receive the resulting HTML code.</p>
<p>Any ideas?</p>
| 3 | 2009-06-24T06:15:59Z | 1,036,757 | <p>The only tool in Python for Javascript, that I am aware of is <a href="http://code.google.com/p/python-spidermonkey/" rel="nofollow">python-spidermonkey</a>. I have never used it though.</p>
<p>With Jython you could (ab-)use <a href="http://httpunit.sourceforge.net/index.html" rel="nofollow">HttpUnit</a>. </p>
<p><strong>Edit</strong>: forgot that you can use <a href="http://scrapy.org/" rel="nofollow">Scrapy</a>. It supports Javascript through Spidermonkey, and you can even use Firefox for crawling the web.</p>
<p><strong>Edit 2</strong>: Recently, I find myself using browser automation more and more for such tasks thanks to some excellent libraries. <a href="http://qt-project.org/doc/qt-5.0/qtwebkit/qtwebkit-module.html" rel="nofollow">QtWebKit</a> offers full access to a WebKit browser, which can be used in Python thanks to language bindings (<a href="http://qt-project.org/wiki/PySide" rel="nofollow">PySide</a> or <a href="http://www.riverbankcomputing.co.uk/software/pyqt/intro" rel="nofollow">PyQt</a>). There seem to be similar libraries and bindings for Gtk+ which I haven't tried. <a href="http://seleniumhq.org/docs/03_webdriver.jsp" rel="nofollow">Selenium WebDriver API</a> also works great and has an active community.</p>
| 5 | 2009-06-24T06:49:31Z | [
"python",
"html",
"bots"
] |
Python Web-based Bot | 1,036,660 | <p>I am trying to write a Python-based Web Bot that can read and interpret an HTML page, then execute an onClick function and receive the resulting new HTML page. I can already read the HTML page and I can determine the functions to be called by the onClick command, but I have no idea how to execute those functions or how to receive the resulting HTML code.</p>
<p>Any ideas?</p>
| 3 | 2009-06-24T06:15:59Z | 1,036,758 | <p>Well obviously python won't interpret the JS for you (though there may be modules out there that can). I suppose you need to convert the JS instructions to equivalent transformations in Python.</p>
<p>I suppose ElementTree or BeautifulSoup would be good starting points to interpret the HTML structure.</p>
| 0 | 2009-06-24T06:49:46Z | [
"python",
"html",
"bots"
] |
Python Web-based Bot | 1,036,660 | <p>I am trying to write a Python-based Web Bot that can read and interpret an HTML page, then execute an onClick function and receive the resulting new HTML page. I can already read the HTML page and I can determine the functions to be called by the onClick command, but I have no idea how to execute those functions or how to receive the resulting HTML code.</p>
<p>Any ideas?</p>
| 3 | 2009-06-24T06:15:59Z | 1,036,761 | <p>To execute JavaScript, you need to do much of what a full web browser does, except for the rendering. In particular, you need a JavaScript interpreter, in addition to the Python interpreter.</p>
<p>One starting point might be <a href="http://pypi.python.org/pypi/python-spidermonkey" rel="nofollow">python-spidermonkey</a>. Depending on the specific JavaScript, you might have to provide a good DOM API to the spidermonkey, in addition to providing an XmlHttpRequest implementation.</p>
| 0 | 2009-06-24T06:50:07Z | [
"python",
"html",
"bots"
] |
Python Web-based Bot | 1,036,660 | <p>I am trying to write a Python-based Web Bot that can read and interpret an HTML page, then execute an onClick function and receive the resulting new HTML page. I can already read the HTML page and I can determine the functions to be called by the onClick command, but I have no idea how to execute those functions or how to receive the resulting HTML code.</p>
<p>Any ideas?</p>
| 3 | 2009-06-24T06:15:59Z | 1,036,804 | <p>You can try to leverage <a href="http://code.google.com/apis/v8/intro.html" rel="nofollow">V8</a>,</p>
<blockquote>
<p>V8 is Google's open source, high performance JavaScript engine. It is written in C++ and is used in Google Chrome, Google's open source browser.</p>
</blockquote>
<p>Calling it from <code>Python</code> may not be straightforward, without a framework to provide the DOM.
<a href="http://pyjs.org/" rel="nofollow"><code>Pyjamas</code></a> has an experimental project, <a href="http://pyjd.org/" rel="nofollow"><em>Pyjamas Desktop</em></a>, providing <code>V8</code> integration for <code>Javascript</code> execution. </p>
<p><a href="http://advogato.org/article/985.html" rel="nofollow"><code>Pyv8</code></a> is an experimental python v8 bindings and a python-javascript compiler.</p>
| 0 | 2009-06-24T07:05:08Z | [
"python",
"html",
"bots"
] |
Python Web-based Bot | 1,036,660 | <p>I am trying to write a Python-based Web Bot that can read and interpret an HTML page, then execute an onClick function and receive the resulting new HTML page. I can already read the HTML page and I can determine the functions to be called by the onClick command, but I have no idea how to execute those functions or how to receive the resulting HTML code.</p>
<p>Any ideas?</p>
| 3 | 2009-06-24T06:15:59Z | 1,037,143 | <p>For the browser part of this you might want to look into Mechanize, which basically is a webbrowser implemented as a Python library. <a href="http://pypi.python.org/pypi/mechanize/0.1.11" rel="nofollow">http://pypi.python.org/pypi/mechanize/0.1.11</a>
But as mentioned, the text n onClick is Javascript, and you'll need spidermonkey for that.</p>
<p>If you can make a generic support for spidermonkey in mechanize, I'm sure many people would be extremely happy. ;)</p>
<p>Mechanize may be overkill, maybe you just want to find specific parts of the HTML, and then lxml and BeautifulSoup both work well.</p>
| 0 | 2009-06-24T08:44:28Z | [
"python",
"html",
"bots"
] |
Python Web-based Bot | 1,036,660 | <p>I am trying to write a Python-based Web Bot that can read and interpret an HTML page, then execute an onClick function and receive the resulting new HTML page. I can already read the HTML page and I can determine the functions to be called by the onClick command, but I have no idea how to execute those functions or how to receive the resulting HTML code.</p>
<p>Any ideas?</p>
| 3 | 2009-06-24T06:15:59Z | 5,873,989 | <p>Why don't you just sniff what gets sent after the onclick event and replicate that with your bot?</p>
| 0 | 2011-05-03T18:29:05Z | [
"python",
"html",
"bots"
] |
Simple Image Metrics with PIL | 1,037,090 | <p>I want to process uploaded photos with PIL and determine some "soft" image metrics like:</p>
<ul>
<li>is the image contrastful or dull?</li>
<li>colorful or monochrome?</li>
<li>bright or dark?</li>
<li>is the image warm or cold (regarding light temperature)?</li>
<li>is there a dominant hue?</li>
</ul>
<p>the metrics should be measured in a rating-style, e.g. colorful++++ for a very colorful photo, colorful+ for a rather monochrome image.</p>
<p>I already noticed PIL's ImageStat Module, that calculates some interesting values for my metrics, e.g. RMS of histogram etc. However, this module is rather poorly documented, so I'm looking for more concrete algorithms to determine these metrics.</p>
| 4 | 2009-06-24T08:30:47Z | 1,037,217 | <p>I don't think there are methods that give you a metric exactly for what you want, but the methods that it has, like RMS, takes you a long way there. To do things with color, you can split the image into one layer per color, and get the RMS on each layer, which tells you some of the things you want to know. You can also convert the image in different ways so that you only retain color information, etc.</p>
| 1 | 2009-06-24T09:01:52Z | [
"python",
"python-imaging-library"
] |
How to automatically create postgis database for Django testing? | 1,037,388 | <p>I'm trying to test my Django apps which run on a PostGIS database, by following the info in the <a href="http://docs.djangoproject.com/en/dev/topics/testing/" rel="nofollow">Django testing docs</a>.</p>
<p>Normally I create a new database by copying a template:</p>
<p>(as user postgres)</p>
<pre><code>createdb -T template_postgis -O lizard test_geodjango2
</code></pre>
<p>When I run <code>./manage.py test</code>, I get the following message:</p>
<blockquote>
<p>Creating test database...
Got an error creating the test database: permission denied to create database</p>
<p>Type 'yes' if you would like to try deleting the test database 'test_geodjango2', or 'no' to > cancel: </p>
</blockquote>
<p>What's the best way to let the system create the database?</p>
| 4 | 2009-06-24T09:45:22Z | 1,037,580 | <p>It may be that your <code>DATABASE_USER</code> doesn't have permissions to create a new database/schema. </p>
<p><hr /></p>
<p><strong>Edit</strong></p>
<p>If you read the source for the Django <code>test</code> command, you'll see that it always creates a test database. Further, it modifies your settings to reference this test database.</p>
<p>See this: <a href="http://docs.djangoproject.com/en/dev/topics/testing/#id1">http://docs.djangoproject.com/en/dev/topics/testing/#id1</a></p>
<p>What you should do is use <a href="http://docs.djangoproject.com/en/dev/topics/testing/#fixture-loading">fixtures</a>. Here's how we do it.</p>
<ol>
<li><p>From your template database, create a "fixture". Use the <code>manage.py dumpdata</code> command to create a JSON file with all of your template data. [Hint, the <code>--indent=2</code> option gives you readable JSON that you can edit and modify.]</p></li>
<li><p>Put this in a <code>fixtures</code> directory under your application.</p></li>
<li><p>Reference the fixtures file in your TestCase class definition. This will load the fixture prior to running the test.</p>
<pre><code>class AnimalTestCase(TestCase):
fixtures = ['mammals.json', 'birds']
def testFluffyAnimals(self):
etc.
</code></pre></li>
</ol>
<p>The fixtures replace your template database. You don't need the template anymore once you have the fixtures.</p>
| 4 | 2009-06-24T10:36:48Z | [
"python",
"django",
"unit-testing"
] |
How to automatically create postgis database for Django testing? | 1,037,388 | <p>I'm trying to test my Django apps which run on a PostGIS database, by following the info in the <a href="http://docs.djangoproject.com/en/dev/topics/testing/" rel="nofollow">Django testing docs</a>.</p>
<p>Normally I create a new database by copying a template:</p>
<p>(as user postgres)</p>
<pre><code>createdb -T template_postgis -O lizard test_geodjango2
</code></pre>
<p>When I run <code>./manage.py test</code>, I get the following message:</p>
<blockquote>
<p>Creating test database...
Got an error creating the test database: permission denied to create database</p>
<p>Type 'yes' if you would like to try deleting the test database 'test_geodjango2', or 'no' to > cancel: </p>
</blockquote>
<p>What's the best way to let the system create the database?</p>
| 4 | 2009-06-24T09:45:22Z | 1,041,848 | <p>As S.Lott mentioned, use the standard <em>test</em> command.</p>
<p>Using geodjango with postgis you'll need to add the following to your settings for the spatial templates to be created properly.</p>
<p><strong>settings.py</strong></p>
<pre><code>POSTGIS_SQL_PATH = 'C:\\Program Files\\PostgreSQL\\8.3\\share\\contrib'
TEST_RUNNER='django.contrib.gis.tests.run_tests'
</code></pre>
<p><strong>console</strong></p>
<pre><code>manage.py test
</code></pre>
<p>Described here:
<a href="http://geodjango.org/docs/testing.html?highlight=testing#testing-geodjango-apps" rel="nofollow">http://geodjango.org/docs/testing.html?highlight=testing#testing-geodjango-apps</a></p>
<p>I haven't looked into it yet, but when I do this I get prompted for the database password when it attempts to install the necessary sql.</p>
| 2 | 2009-06-25T02:03:06Z | [
"python",
"django",
"unit-testing"
] |
Python urllib2 with keep alive | 1,037,406 | <p>How can I make a "keep alive" HTTP request using Python's urllib2?</p>
| 38 | 2009-06-24T09:50:43Z | 1,037,423 | <p>Use the <a href="http://urlgrabber.baseurl.org/" rel="nofollow">urlgrabber</a> library. This includes an HTTP handler for urllib2 that supports HTTP 1.1 and keepalive:</p>
<pre><code>>>> import urllib2
>>> from urlgrabber.keepalive import HTTPHandler
>>> keepalive_handler = HTTPHandler()
>>> opener = urllib2.build_opener(keepalive_handler)
>>> urllib2.install_opener(opener)
>>>
>>> fo = urllib2.urlopen('http://www.python.org')
</code></pre>
<p>Note: you should use urlgrabber version <a href="http://urlgrabber.baseurl.org/download/urlgrabber-3.9.0.tar.gz" rel="nofollow">3.9.0</a> or earlier, as the <a href="http://urlgrabber.baseurl.org/help/urlgrabber.keepalive.html" rel="nofollow">keepalive</a> module has been removed in version 3.9.1</p>
<p>There is a <a href="https://github.com/wikier/keepalive" rel="nofollow">port</a> the keepalive module to Python 3.</p>
| 28 | 2009-06-24T09:56:44Z | [
"python",
"http",
"urllib2",
"keep-alive"
] |
Python urllib2 with keep alive | 1,037,406 | <p>How can I make a "keep alive" HTTP request using Python's urllib2?</p>
| 38 | 2009-06-24T09:50:43Z | 2,024,633 | <p>Note that urlgrabber does not entirely work with python 2.6. I fixed the issues (I think) by making the following modifications in keepalive.py.</p>
<p>In keepalive.HTTPHandler.do_open() remove this</p>
<pre><code> if r.status == 200 or not HANDLE_ERRORS:
return r
</code></pre>
<p>And insert this</p>
<pre><code> if r.status == 200 or not HANDLE_ERRORS:
# [speedplane] Must return an adinfourl object
resp = urllib2.addinfourl(r, r.msg, req.get_full_url())
resp.code = r.status
resp.msg = r.reason
return resp
</code></pre>
| 4 | 2010-01-08T00:05:38Z | [
"python",
"http",
"urllib2",
"keep-alive"
] |
Python urllib2 with keep alive | 1,037,406 | <p>How can I make a "keep alive" HTTP request using Python's urllib2?</p>
| 38 | 2009-06-24T09:50:43Z | 4,611,327 | <p>Unfortunately keepalive.py was removed from urlgrabber on 25 Sep 2009 by the following change after urlgrabber was changed to depend on pycurl (which supports keep-alive):</p>
<p><a href="http://yum.baseurl.org/gitweb?p=urlgrabber.git;a=commit;h=f964aa8bdc52b29a2c137a917c72eecd4c4dda94" rel="nofollow">http://yum.baseurl.org/gitweb?p=urlgrabber.git;a=commit;h=f964aa8bdc52b29a2c137a917c72eecd4c4dda94</a></p>
<p>However, you can still get the last revision of keepalive.py here:</p>
<p><a href="http://yum.baseurl.org/gitweb?p=urlgrabber.git;a=blob_plain;f=urlgrabber/keepalive.py;hb=a531cb19eb162ad7e0b62039d19259341f37f3a6" rel="nofollow">http://yum.baseurl.org/gitweb?p=urlgrabber.git;a=blob_plain;f=urlgrabber/keepalive.py;hb=a531cb19eb162ad7e0b62039d19259341f37f3a6</a></p>
| 4 | 2011-01-06T02:51:07Z | [
"python",
"http",
"urllib2",
"keep-alive"
] |
Python urllib2 with keep alive | 1,037,406 | <p>How can I make a "keep alive" HTTP request using Python's urllib2?</p>
| 38 | 2009-06-24T09:50:43Z | 6,163,023 | <p>Or check out <a href="http://docs.python.org/library/httplib.html">httplib</a>'s HTTPConnection.</p>
| 7 | 2011-05-28T16:54:26Z | [
"python",
"http",
"urllib2",
"keep-alive"
] |
Python urllib2 with keep alive | 1,037,406 | <p>How can I make a "keep alive" HTTP request using Python's urllib2?</p>
| 38 | 2009-06-24T09:50:43Z | 8,086,976 | <p>Try <a href="https://github.com/shazow/urllib3">urllib3</a> which has the following features:</p>
<ul>
<li>Re-use the same socket connection for multiple requests (HTTPConnectionPool and HTTPSConnectionPool) (with optional client-side certificate verification).</li>
<li>File posting (encode_multipart_formdata).</li>
<li>Built-in redirection and retries (optional).</li>
<li>Supports gzip and deflate decoding.</li>
<li>Thread-safe and sanity-safe.</li>
<li>Small and easy to understand codebase perfect for extending and building upon. For a more comprehensive solution, have a look at Requests.</li>
</ul>
<p>or a much more comprehensive solution - <a href="https://github.com/kennethreitz/requests">Requests</a> - which supports keep-alive from <a href="https://github.com/kennethreitz/requests/blob/develop/HISTORY.rst">version</a> 0.8.0 (by using urllib3 internally) and has the following <a href="https://github.com/kennethreitz/requests/blob/develop/README.rst">features</a>:</p>
<ul>
<li>Extremely simple HEAD, GET, POST, PUT, PATCH, DELETE Requests.</li>
<li>Gevent support for Asyncronous Requests.</li>
<li>Sessions with cookie persistience.</li>
<li>Basic, Digest, and Custom Authentication support.</li>
<li>Automatic form-encoding of dictionaries</li>
<li>A simple dictionary interface for request/response cookies.</li>
<li>Multipart file uploads.</li>
<li>Automatc decoding of Unicode, gzip, and deflate responses.</li>
<li>Full support for unicode URLs and domain names.</li>
</ul>
| 11 | 2011-11-10T22:00:14Z | [
"python",
"http",
"urllib2",
"keep-alive"
] |
Python urllib2 with keep alive | 1,037,406 | <p>How can I make a "keep alive" HTTP request using Python's urllib2?</p>
| 38 | 2009-06-24T09:50:43Z | 14,282,639 | <p>Please avoid collective pain and use <a href="http://docs.python-requests.org/en/latest/" rel="nofollow">Requests</a> instead. It will do the right thing by default and use keep-alive if applicable.</p>
| 5 | 2013-01-11T16:39:05Z | [
"python",
"http",
"urllib2",
"keep-alive"
] |
Python urllib2 with keep alive | 1,037,406 | <p>How can I make a "keep alive" HTTP request using Python's urllib2?</p>
| 38 | 2009-06-24T09:50:43Z | 27,090,369 | <p>Here's a somewhat similar urlopen() that does keep-alive, though it's not threadsafe.</p>
<pre><code>try:
from http.client import HTTPConnection, HTTPSConnection
except ImportError:
from httplib import HTTPConnection, HTTPSConnection
import select
connections = {}
def request(method, url, body=None, headers={}, **kwargs):
scheme, _, host, path = url.split('/', 3)
h = connections.get((scheme, host))
if h and select.select([h.sock], [], [], 0)[0]:
h.close()
h = None
if not h:
Connection = HTTPConnection if scheme == 'http:' else HTTPSConnection
h = connections[(scheme, host)] = Connection(host, **kwargs)
h.request(method, '/' + path, body, headers)
return h.getresponse()
def urlopen(url, data=None, *args, **kwargs):
resp = request('POST' if data else 'GET', url, data, *args, **kwargs)
assert resp.status < 400, (resp.status, resp.reason, resp.read())
return resp
</code></pre>
| 0 | 2014-11-23T15:06:01Z | [
"python",
"http",
"urllib2",
"keep-alive"
] |
Are there stack based variables in Python? | 1,037,533 | <p>If I do this:</p>
<pre><code>def foo():
a = SomeObject()
</code></pre>
<p>Is 'a' destroyed immediately after leaving foo? Or does it wait for some GC to happen?</p>
| 5 | 2009-06-24T10:24:18Z | 1,037,542 | <p>Yes and no. The object will get destroyed after you leave foo (as long as nothing else has a reference to it), but whether it is immediate or not is an implementation detail, and will vary.</p>
<p>In CPython (the standard python implementation), refcounting is used, so the item will immediately be destroyed. There are some exceptions to this, such as when the object contains cyclical references, or when references are held to the enclosing frame (eg. an exception is raised that retains a reference to the frame's variables.)</p>
<p>In implmentations like Jython or IronPython however, the object won't be finalised until the garbage collector kicks in.</p>
<p>As such, you shouldn't rely on timely finalisation of objects, but should only assume that it will be destroyed at some point after the last reference goes. When you do need some cleanup to be done based on the lexical scope, either explicitely call a cleanup method, or look at the new <a href="http://www.python.org/dev/peps/pep-0343/" rel="nofollow">with statement</a> in python 2.6 (available in 2.5 with "<code>from __future__ import with_statement</code>").</p>
| 18 | 2009-06-24T10:26:42Z | [
"python"
] |
Pure python gui library? | 1,037,673 | <p>Python has a lot of GUI libraries: tkinter, wxWidgets, pyGTK etc. But all this GUI needs to be installed and quite heavyweight, so it's a bit complex to deploy end-user GUI python apps that relay on mentioned GUI libraries.</p>
<p>Recently, I have thought about python built-in ctypes. Theoretically, it's possible to create pure python GUI library that will use ctypes on windows ( windll.user32.CreateWindowEx etc ), native pyObjC on MacOS and pyGTK / pyQt on gnome / kde. Does such library exists? If not, how do you think what's wrong with an idea?</p>
| 5 | 2009-06-24T10:58:26Z | 1,037,705 | <p>I think it's about not inventig the wheel. It would work, but why should you do that? All the GUI libraries you mentioned are stable and more or less bullet proofen.</p>
<p>I could imagine that there are some experiments implementing a pure python library. But I never saw one. Everything about GUIs is hard work and a pure python library wouldn't have such a big audience.</p>
| 2 | 2009-06-24T11:08:56Z | [
"python",
"tkinter",
"pyqt",
"pygtk",
"pyobjc"
] |
Pure python gui library? | 1,037,673 | <p>Python has a lot of GUI libraries: tkinter, wxWidgets, pyGTK etc. But all this GUI needs to be installed and quite heavyweight, so it's a bit complex to deploy end-user GUI python apps that relay on mentioned GUI libraries.</p>
<p>Recently, I have thought about python built-in ctypes. Theoretically, it's possible to create pure python GUI library that will use ctypes on windows ( windll.user32.CreateWindowEx etc ), native pyObjC on MacOS and pyGTK / pyQt on gnome / kde. Does such library exists? If not, how do you think what's wrong with an idea?</p>
| 5 | 2009-06-24T10:58:26Z | 1,037,722 | <p>The path of least effort and best results would be to learn what it takes to deploy an app using those existing GUI libraries.</p>
| 9 | 2009-06-24T11:14:16Z | [
"python",
"tkinter",
"pyqt",
"pygtk",
"pyobjc"
] |
Pure python gui library? | 1,037,673 | <p>Python has a lot of GUI libraries: tkinter, wxWidgets, pyGTK etc. But all this GUI needs to be installed and quite heavyweight, so it's a bit complex to deploy end-user GUI python apps that relay on mentioned GUI libraries.</p>
<p>Recently, I have thought about python built-in ctypes. Theoretically, it's possible to create pure python GUI library that will use ctypes on windows ( windll.user32.CreateWindowEx etc ), native pyObjC on MacOS and pyGTK / pyQt on gnome / kde. Does such library exists? If not, how do you think what's wrong with an idea?</p>
| 5 | 2009-06-24T10:58:26Z | 1,037,740 | <p>For one thing, all those libraries use different abstractions, so anything that worked with all of them is likely to wind up supporting a least-common-denominator set of functionality, <em>or</em> doing a LOT of work to use each to its fullest.</p>
| 3 | 2009-06-24T11:18:35Z | [
"python",
"tkinter",
"pyqt",
"pygtk",
"pyobjc"
] |
Pure python gui library? | 1,037,673 | <p>Python has a lot of GUI libraries: tkinter, wxWidgets, pyGTK etc. But all this GUI needs to be installed and quite heavyweight, so it's a bit complex to deploy end-user GUI python apps that relay on mentioned GUI libraries.</p>
<p>Recently, I have thought about python built-in ctypes. Theoretically, it's possible to create pure python GUI library that will use ctypes on windows ( windll.user32.CreateWindowEx etc ), native pyObjC on MacOS and pyGTK / pyQt on gnome / kde. Does such library exists? If not, how do you think what's wrong with an idea?</p>
| 5 | 2009-06-24T10:58:26Z | 1,037,810 | <p>Not really sure what you mean by "heavyweight."</p>
<p>wx uses native controls on each platform, and is about as easy to use in Python as I can imagine; after all, GUI APIs are complex because GUIs can get complex.</p>
<p>I think wx, for the effort required to build a window and the quality of what shows up on screen, is great. I don't think you're likely to roll something better on your own.</p>
| 4 | 2009-06-24T11:36:05Z | [
"python",
"tkinter",
"pyqt",
"pygtk",
"pyobjc"
] |
Pure python gui library? | 1,037,673 | <p>Python has a lot of GUI libraries: tkinter, wxWidgets, pyGTK etc. But all this GUI needs to be installed and quite heavyweight, so it's a bit complex to deploy end-user GUI python apps that relay on mentioned GUI libraries.</p>
<p>Recently, I have thought about python built-in ctypes. Theoretically, it's possible to create pure python GUI library that will use ctypes on windows ( windll.user32.CreateWindowEx etc ), native pyObjC on MacOS and pyGTK / pyQt on gnome / kde. Does such library exists? If not, how do you think what's wrong with an idea?</p>
| 5 | 2009-06-24T10:58:26Z | 1,037,851 | <p>Tkinter is part of the python standard distribution and is installed by default. Expect to find this on all python installs where there is a graphical display in the first place. </p>
| 8 | 2009-06-24T11:45:45Z | [
"python",
"tkinter",
"pyqt",
"pygtk",
"pyobjc"
] |
Pure python gui library? | 1,037,673 | <p>Python has a lot of GUI libraries: tkinter, wxWidgets, pyGTK etc. But all this GUI needs to be installed and quite heavyweight, so it's a bit complex to deploy end-user GUI python apps that relay on mentioned GUI libraries.</p>
<p>Recently, I have thought about python built-in ctypes. Theoretically, it's possible to create pure python GUI library that will use ctypes on windows ( windll.user32.CreateWindowEx etc ), native pyObjC on MacOS and pyGTK / pyQt on gnome / kde. Does such library exists? If not, how do you think what's wrong with an idea?</p>
| 5 | 2009-06-24T10:58:26Z | 1,038,265 | <p>Notion of "pure python gui library" is wrong because ultimately you will be using system level calls and widgets, may be thru ctypes but that doesn't change the fact that if you start implementing your idea you will eventually become wxPython</p>
| 4 | 2009-06-24T13:15:55Z | [
"python",
"tkinter",
"pyqt",
"pygtk",
"pyobjc"
] |
Pure python gui library? | 1,037,673 | <p>Python has a lot of GUI libraries: tkinter, wxWidgets, pyGTK etc. But all this GUI needs to be installed and quite heavyweight, so it's a bit complex to deploy end-user GUI python apps that relay on mentioned GUI libraries.</p>
<p>Recently, I have thought about python built-in ctypes. Theoretically, it's possible to create pure python GUI library that will use ctypes on windows ( windll.user32.CreateWindowEx etc ), native pyObjC on MacOS and pyGTK / pyQt on gnome / kde. Does such library exists? If not, how do you think what's wrong with an idea?</p>
| 5 | 2009-06-24T10:58:26Z | 1,038,303 | <p>Principally what's wrong is that it's reinventing wheels that have already been done by the makers of GTK, Tk, Wx, QT and their ilk. While a pure python GUI is technically feasible, and projects such as <a href="http://anygui.sourceforge.net/">anygui</a> did attempt something similar, there is relatively little to gain by doing this. </p>
<p>The native toolkits will also do a better job of covering the differences between the underlying platforms (native dialogs etc.). This means that the toolkits allow you to write a portable application that needs little if any platform specific code - most of this is abstracted by the underlying toolkit.</p>
<p>Distribution mechanisms such as py2exe on windows and any of the linux methods allow you to bundle DLLs with the application, so you can make an installer that drops any native components it needs into place. However, there isn't really a generic cross-platform way to do this so you will need to maintain separate installers for each platform.</p>
| 5 | 2009-06-24T13:24:50Z | [
"python",
"tkinter",
"pyqt",
"pygtk",
"pyobjc"
] |
Pure python gui library? | 1,037,673 | <p>Python has a lot of GUI libraries: tkinter, wxWidgets, pyGTK etc. But all this GUI needs to be installed and quite heavyweight, so it's a bit complex to deploy end-user GUI python apps that relay on mentioned GUI libraries.</p>
<p>Recently, I have thought about python built-in ctypes. Theoretically, it's possible to create pure python GUI library that will use ctypes on windows ( windll.user32.CreateWindowEx etc ), native pyObjC on MacOS and pyGTK / pyQt on gnome / kde. Does such library exists? If not, how do you think what's wrong with an idea?</p>
| 5 | 2009-06-24T10:58:26Z | 1,038,494 | <p>starting in Python 2.7 and 3.1, Tk will look a lot better.</p>
<p><a href="http://docs.python.org/dev/whatsnew/2.7.html#ttk-themed-widgets-for-tk">http://docs.python.org/dev/whatsnew/2.7.html#ttk-themed-widgets-for-tk</a></p>
<p>"Tcl/Tk 8.5 includes a set of themed widgets that re-implement basic Tk widgets but have a more customizable appearance and can therefore more closely resemble the native platformâs widgets. This widget set was originally called Tile, but was renamed to Ttk (for âthemed Tkâ) on being added to Tcl/Tck release 8.5."</p>
| 9 | 2009-06-24T13:48:15Z | [
"python",
"tkinter",
"pyqt",
"pygtk",
"pyobjc"
] |
gnuplot syntax error when using python | 1,037,919 | <p>I am just about to find out how python and gnuplot work together. On </p>
<p><a href="http://wiki.aims.ac.za/mediawiki/index.php/Python:Gnuplot_module" rel="nofollow">http://wiki.aims.ac.za/mediawiki/index.php/Python:Gnuplot_module</a></p>
<p>I found an introduction and I wanted to execute it on my Ubuntu machine. </p>
<pre><code>import Gnuplot
gp = Gnuplot.Gnuplot(persist = 1)
gp('set data style lines')
# The first data set (a quadratic)
data1 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16]]
# The second data set (a straight line)
data2 = [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]]
plot1 = Gnuplot.PlotItems.Data(data1, with_="lines", title="Quadratic")
plot2 = Gnuplot.PlotItems.Data(data2, with_="points 3", title=None) # No title
gp.plot(plot1, plot2)
</code></pre>
<p>However, I get the following error message: </p>
<pre><code>./demo.py
./demo.py: line 2: syntax error near unexpected token `('
./demo.py: line 2: `gp = Gnuplot.Gnuplot(persist = 1)'
</code></pre>
<p>any idea what could be wrong here? To install gnuplot support for python I installed python-gnuplot. Do I miss another package? </p>
| 1 | 2009-06-24T12:00:34Z | 1,038,003 | <p>Well the python interpreter thinks that while parsing there was an syntax error.
Check again your quotes, make sure that for convenience sake you only use either double or single quotes in your entire script (except of course when you need to put in a literal quote like "'" or '"').</p>
<p>If you are unsure what goes wrong what you can do is open the interactive interpreter and write each line in there.</p>
| 0 | 2009-06-24T12:16:21Z | [
"python",
"gnuplot"
] |
gnuplot syntax error when using python | 1,037,919 | <p>I am just about to find out how python and gnuplot work together. On </p>
<p><a href="http://wiki.aims.ac.za/mediawiki/index.php/Python:Gnuplot_module" rel="nofollow">http://wiki.aims.ac.za/mediawiki/index.php/Python:Gnuplot_module</a></p>
<p>I found an introduction and I wanted to execute it on my Ubuntu machine. </p>
<pre><code>import Gnuplot
gp = Gnuplot.Gnuplot(persist = 1)
gp('set data style lines')
# The first data set (a quadratic)
data1 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16]]
# The second data set (a straight line)
data2 = [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]]
plot1 = Gnuplot.PlotItems.Data(data1, with_="lines", title="Quadratic")
plot2 = Gnuplot.PlotItems.Data(data2, with_="points 3", title=None) # No title
gp.plot(plot1, plot2)
</code></pre>
<p>However, I get the following error message: </p>
<pre><code>./demo.py
./demo.py: line 2: syntax error near unexpected token `('
./demo.py: line 2: `gp = Gnuplot.Gnuplot(persist = 1)'
</code></pre>
<p>any idea what could be wrong here? To install gnuplot support for python I installed python-gnuplot. Do I miss another package? </p>
| 1 | 2009-06-24T12:00:34Z | 1,038,015 | <p>I've been using pylab instead. <a href="http://www.scipy.org/PyLab" rel="nofollow">Pylab homepage</a></p>
<p>From debian repos:</p>
<pre><code>python-matplotlib - Python based plotting system in a style similar to Matlab.
</code></pre>
| -1 | 2009-06-24T12:19:09Z | [
"python",
"gnuplot"
] |
gnuplot syntax error when using python | 1,037,919 | <p>I am just about to find out how python and gnuplot work together. On </p>
<p><a href="http://wiki.aims.ac.za/mediawiki/index.php/Python:Gnuplot_module" rel="nofollow">http://wiki.aims.ac.za/mediawiki/index.php/Python:Gnuplot_module</a></p>
<p>I found an introduction and I wanted to execute it on my Ubuntu machine. </p>
<pre><code>import Gnuplot
gp = Gnuplot.Gnuplot(persist = 1)
gp('set data style lines')
# The first data set (a quadratic)
data1 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16]]
# The second data set (a straight line)
data2 = [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]]
plot1 = Gnuplot.PlotItems.Data(data1, with_="lines", title="Quadratic")
plot2 = Gnuplot.PlotItems.Data(data2, with_="points 3", title=None) # No title
gp.plot(plot1, plot2)
</code></pre>
<p>However, I get the following error message: </p>
<pre><code>./demo.py
./demo.py: line 2: syntax error near unexpected token `('
./demo.py: line 2: `gp = Gnuplot.Gnuplot(persist = 1)'
</code></pre>
<p>any idea what could be wrong here? To install gnuplot support for python I installed python-gnuplot. Do I miss another package? </p>
| 1 | 2009-06-24T12:00:34Z | 1,038,173 | <p>Your <code>demo.py</code> file is somehow corrupted - make sure that the open-parenthesis character is really that. Grub the installer from the <a href="http://gnuplot-py.sourceforge.net/" rel="nofollow">project page</a> to make sure.</p>
<p>You can access the <a href="http://gnuplot-py.svn.sourceforge.net/viewvc/gnuplot-py/trunk/demo.py?view=log" rel="nofollow">current SVN version</a> of the file (choose <em>download</em> of the HEAD revision).</p>
| 0 | 2009-06-24T12:52:00Z | [
"python",
"gnuplot"
] |
gnuplot syntax error when using python | 1,037,919 | <p>I am just about to find out how python and gnuplot work together. On </p>
<p><a href="http://wiki.aims.ac.za/mediawiki/index.php/Python:Gnuplot_module" rel="nofollow">http://wiki.aims.ac.za/mediawiki/index.php/Python:Gnuplot_module</a></p>
<p>I found an introduction and I wanted to execute it on my Ubuntu machine. </p>
<pre><code>import Gnuplot
gp = Gnuplot.Gnuplot(persist = 1)
gp('set data style lines')
# The first data set (a quadratic)
data1 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16]]
# The second data set (a straight line)
data2 = [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]]
plot1 = Gnuplot.PlotItems.Data(data1, with_="lines", title="Quadratic")
plot2 = Gnuplot.PlotItems.Data(data2, with_="points 3", title=None) # No title
gp.plot(plot1, plot2)
</code></pre>
<p>However, I get the following error message: </p>
<pre><code>./demo.py
./demo.py: line 2: syntax error near unexpected token `('
./demo.py: line 2: `gp = Gnuplot.Gnuplot(persist = 1)'
</code></pre>
<p>any idea what could be wrong here? To install gnuplot support for python I installed python-gnuplot. Do I miss another package? </p>
| 1 | 2009-06-24T12:00:34Z | 1,038,179 | <p>If I copy and paste your code into Emacs I get this:</p>
<pre><code>gp = Gnuplot.Gnuplot(persist = 1)
gp('set data style lines')
data1 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16]] # The first data set (a quadratic)
data2 = [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]] # The second data set (a straight line)
plot1 = Gnuplot.PlotItems.Data(data1, with_="lines", title="Quadratic")
plot2 = Gnuplot.PlotItems.Data(data2, with_="points 3", title=None) # No title
gp.plot(plot1, plot2)
</code></pre>
<p>If I remove the whitespaces at the beginning of the three lines it works for me.</p>
| 0 | 2009-06-24T12:53:04Z | [
"python",
"gnuplot"
] |
gnuplot syntax error when using python | 1,037,919 | <p>I am just about to find out how python and gnuplot work together. On </p>
<p><a href="http://wiki.aims.ac.za/mediawiki/index.php/Python:Gnuplot_module" rel="nofollow">http://wiki.aims.ac.za/mediawiki/index.php/Python:Gnuplot_module</a></p>
<p>I found an introduction and I wanted to execute it on my Ubuntu machine. </p>
<pre><code>import Gnuplot
gp = Gnuplot.Gnuplot(persist = 1)
gp('set data style lines')
# The first data set (a quadratic)
data1 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16]]
# The second data set (a straight line)
data2 = [[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]]
plot1 = Gnuplot.PlotItems.Data(data1, with_="lines", title="Quadratic")
plot2 = Gnuplot.PlotItems.Data(data2, with_="points 3", title=None) # No title
gp.plot(plot1, plot2)
</code></pre>
<p>However, I get the following error message: </p>
<pre><code>./demo.py
./demo.py: line 2: syntax error near unexpected token `('
./demo.py: line 2: `gp = Gnuplot.Gnuplot(persist = 1)'
</code></pre>
<p>any idea what could be wrong here? To install gnuplot support for python I installed python-gnuplot. Do I miss another package? </p>
| 1 | 2009-06-24T12:00:34Z | 3,901,680 | <p>Did you put the bangline in the first line? i.e:</p>
<pre><code>#!/usr/bin/python
</code></pre>
<p>Looks like it is not the Python interpreter who is executing the file.</p>
| 2 | 2010-10-10T18:48:00Z | [
"python",
"gnuplot"
] |
Auto-incrementing attribute with custom logic in SQLAlchemy | 1,038,126 | <p><br />
I have a simple "Invoices" class with a "Number" attribute that has to
be assigned by the application when the user saves an invoice. There
are some constraints:</p>
<p>1) the application is a (thin) client-server one, so whatever
assigns the number must look out for collisions<br />
2) Invoices has a "version" attribute too, so I can't use a simple
DBMS-level autoincrementing field</p>
<p>I'm trying to build this using a custom Type that would kick in every
time an invoice gets saved. Whenever process_bind_param is called with
a None value, it will call a singleton of some sort to determine the
number and avoid collisions. Is this a decent solution?
Anyway, I'm having a problem.. Here's my custom Type: </p>
<pre><code>class AutoIncrement(types.TypeDecorator):
impl = types.Unicode
def copy(self):
return AutoIncrement()
def process_bind_param(self, value, dialect):
if not value:
# Must find next autoincrement value
value = "1" # Test value :)
return value
</code></pre>
<p>My problem right now is that when I save an Invoice and AutoIncrement
sets "1" as value for its number, the Invoice instance <em>doesn't</em> get
updated with the new number.. Is this expected? Am I missing
something?
Many thanks for your time!</p>
<p>(SQLA 0.5.3 on Python 2.6, using postgreSQL 8.3)</p>
<p><strong>Edit:</strong> Michael Bayer told me that this behaviour is expected, since TypeDecorators don't deal with default values.</p>
| 1 | 2009-06-24T12:42:21Z | 1,038,154 | <p>Is there any particular reason you don't just use a <code>default=</code> parameter in your column definition? (This can be an arbitrary Python callable).</p>
<pre><code>def generate_invoice_number():
# special logic to generate a unique invoice number
class Invoice(DeclarativeBase):
__tablename__ = 'invoice'
number = Column(Integer, unique=True, default=generate_invoice_number)
...
</code></pre>
| 3 | 2009-06-24T12:47:25Z | [
"python",
"sqlalchemy",
"auto-increment"
] |
Data structure for maintaining tabular data in memory? | 1,038,160 | <p>My scenario is as follows: I have a table of data (handful of fields, less than a hundred rows) that I use extensively in my program. I also need this data to be persistent, so I save it as a CSV and load it on start-up. I choose not to use a database because every option (even SQLite) is an overkill for my humble requirement (also - I would like to be able to edit the values offline in a simple way, and nothing is simpler than notepad).</p>
<p>Assume my data looks as follows (in the file it's comma separated without titles, this is just an illustration):</p>
<pre><code> Row | Name | Year | Priority
------------------------------------
1 | Cat | 1998 | 1
2 | Fish | 1998 | 2
3 | Dog | 1999 | 1
4 | Aardvark | 2000 | 1
5 | Wallaby | 2000 | 1
6 | Zebra | 2001 | 3
</code></pre>
<p>Notes:</p>
<ol>
<li>Row may be a "real" value written to the file or just an auto-generated value that represents the row number. Either way it exists in memory.</li>
<li>Names are unique.</li>
</ol>
<p>Things I do with the data:</p>
<ol>
<li>Look-up a row based on either ID (iteration) or name (direct access).</li>
<li>Display the table in different orders based on multiple field: I need to sort it e.g. by Priority and then Year, or Year and then Priority, etc.</li>
<li>I need to count instances based on sets of parameters, e.g. how many rows have their year between 1997 and 2002, or how many rows are in 1998 and priority > 2, etc.</li>
</ol>
<p>I know this "cries" for SQL...</p>
<p>I'm trying to figure out what's the best choice for data structure. Following are several choices I see:</p>
<p>List of row lists:</p>
<pre><code>a = []
a.append( [1, "Cat", 1998, 1] )
a.append( [2, "Fish", 1998, 2] )
a.append( [3, "Dog", 1999, 1] )
...
</code></pre>
<p>List of column lists (there will obviously be an API for add_row etc):</p>
<pre><code>a = []
a.append( [1, 2, 3, 4, 5, 6] )
a.append( ["Cat", "Fish", "Dog", "Aardvark", "Wallaby", "Zebra"] )
a.append( [1998, 1998, 1999, 2000, 2000, 2001] )
a.append( [1, 2, 1, 1, 1, 3] )
</code></pre>
<p>Dictionary of columns lists (constants can be created to replace the string keys):</p>
<pre><code>a = {}
a['ID'] = [1, 2, 3, 4, 5, 6]
a['Name'] = ["Cat", "Fish", "Dog", "Aardvark", "Wallaby", "Zebra"]
a['Year'] = [1998, 1998, 1999, 2000, 2000, 2001]
a['Priority'] = [1, 2, 1, 1, 1, 3]
</code></pre>
<p>Dictionary with keys being tuples of (Row, Field):</p>
<pre><code>Create constants to avoid string searching
NAME=1
YEAR=2
PRIORITY=3
a={}
a[(1, NAME)] = "Cat"
a[(1, YEAR)] = 1998
a[(1, PRIORITY)] = 1
a[(2, NAME)] = "Fish"
a[(2, YEAR)] = 1998
a[(2, PRIORITY)] = 2
...
</code></pre>
<p>And I'm sure there are other ways... However each way has disadvantages when it comes to my requirements (complex ordering and counting). </p>
<p>What's the recommended approach?</p>
<p>EDIT:</p>
<p>To clarify, performance is not a major issue for me. Because the table is so small, I believe almost every operation will be in the range of milliseconds, which is not a concern for my application.</p>
| 42 | 2009-06-24T12:48:51Z | 1,038,195 | <p>I personally would use the list of row lists. Because the data for each row is always in the same order, you can easily sort by any of the columns by simply accessing that element in each of the lists. You can also easily count based on a particular column in each list, and make searches as well. It's basically as close as it gets to a 2-d array.</p>
<p>Really the only disadvantage here is that you have to know in what order the data is in, and if you change that ordering, you'll have to change your search/sorting routines to match.</p>
<p>Another thing you can do is have a list of dictionaries.</p>
<pre><code>rows = []
rows.append({"ID":"1", "name":"Cat", "year":"1998", "priority":"1"})
</code></pre>
<p>This would avoid needing to know the order of the parameters, so you can look through each "year" field in the list.</p>
| 10 | 2009-06-24T12:58:05Z | [
"python",
"data-structures"
] |
Data structure for maintaining tabular data in memory? | 1,038,160 | <p>My scenario is as follows: I have a table of data (handful of fields, less than a hundred rows) that I use extensively in my program. I also need this data to be persistent, so I save it as a CSV and load it on start-up. I choose not to use a database because every option (even SQLite) is an overkill for my humble requirement (also - I would like to be able to edit the values offline in a simple way, and nothing is simpler than notepad).</p>
<p>Assume my data looks as follows (in the file it's comma separated without titles, this is just an illustration):</p>
<pre><code> Row | Name | Year | Priority
------------------------------------
1 | Cat | 1998 | 1
2 | Fish | 1998 | 2
3 | Dog | 1999 | 1
4 | Aardvark | 2000 | 1
5 | Wallaby | 2000 | 1
6 | Zebra | 2001 | 3
</code></pre>
<p>Notes:</p>
<ol>
<li>Row may be a "real" value written to the file or just an auto-generated value that represents the row number. Either way it exists in memory.</li>
<li>Names are unique.</li>
</ol>
<p>Things I do with the data:</p>
<ol>
<li>Look-up a row based on either ID (iteration) or name (direct access).</li>
<li>Display the table in different orders based on multiple field: I need to sort it e.g. by Priority and then Year, or Year and then Priority, etc.</li>
<li>I need to count instances based on sets of parameters, e.g. how many rows have their year between 1997 and 2002, or how many rows are in 1998 and priority > 2, etc.</li>
</ol>
<p>I know this "cries" for SQL...</p>
<p>I'm trying to figure out what's the best choice for data structure. Following are several choices I see:</p>
<p>List of row lists:</p>
<pre><code>a = []
a.append( [1, "Cat", 1998, 1] )
a.append( [2, "Fish", 1998, 2] )
a.append( [3, "Dog", 1999, 1] )
...
</code></pre>
<p>List of column lists (there will obviously be an API for add_row etc):</p>
<pre><code>a = []
a.append( [1, 2, 3, 4, 5, 6] )
a.append( ["Cat", "Fish", "Dog", "Aardvark", "Wallaby", "Zebra"] )
a.append( [1998, 1998, 1999, 2000, 2000, 2001] )
a.append( [1, 2, 1, 1, 1, 3] )
</code></pre>
<p>Dictionary of columns lists (constants can be created to replace the string keys):</p>
<pre><code>a = {}
a['ID'] = [1, 2, 3, 4, 5, 6]
a['Name'] = ["Cat", "Fish", "Dog", "Aardvark", "Wallaby", "Zebra"]
a['Year'] = [1998, 1998, 1999, 2000, 2000, 2001]
a['Priority'] = [1, 2, 1, 1, 1, 3]
</code></pre>
<p>Dictionary with keys being tuples of (Row, Field):</p>
<pre><code>Create constants to avoid string searching
NAME=1
YEAR=2
PRIORITY=3
a={}
a[(1, NAME)] = "Cat"
a[(1, YEAR)] = 1998
a[(1, PRIORITY)] = 1
a[(2, NAME)] = "Fish"
a[(2, YEAR)] = 1998
a[(2, PRIORITY)] = 2
...
</code></pre>
<p>And I'm sure there are other ways... However each way has disadvantages when it comes to my requirements (complex ordering and counting). </p>
<p>What's the recommended approach?</p>
<p>EDIT:</p>
<p>To clarify, performance is not a major issue for me. Because the table is so small, I believe almost every operation will be in the range of milliseconds, which is not a concern for my application.</p>
| 42 | 2009-06-24T12:48:51Z | 1,038,203 | <p>Having a "table" in memory that needs lookups, sorting, and arbitrary aggregation really does call out for SQL. You said you tried SQLite, but did you realize that SQLite can use an in-memory-only database?</p>
<pre><code>connection = sqlite3.connect(':memory:')
</code></pre>
<p>Then you can create/drop/query/update tables in memory with all the functionality of SQLite and no files left over when you're done. And as of Python 2.5, <code>sqlite3</code> is in the standard library, so it's not really "overkill" IMO.</p>
<p>Here is a sample of how one might create and populate the database:</p>
<pre><code>import csv
import sqlite3
db = sqlite3.connect(':memory:')
def init_db(cur):
cur.execute('''CREATE TABLE foo (
Row INTEGER,
Name TEXT,
Year INTEGER,
Priority INTEGER)''')
def populate_db(cur, csv_fp):
rdr = csv.reader(csv_fp)
cur.executemany('''
INSERT INTO foo (Row, Name, Year, Priority)
VALUES (?,?,?,?)''', rdr)
cur = db.cursor()
init_db(cur)
populate_db(cur, open('my_csv_input_file.csv'))
db.commit()
</code></pre>
<p>If you'd really prefer not to use SQL, you should probably use a list of dictionaries:</p>
<pre><code>lod = [ ] # "list of dicts"
def populate_lod(lod, csv_fp):
rdr = csv.DictReader(csv_fp, ['Row', 'Name', 'Year', 'Priority'])
lod.extend(rdr)
def query_lod(lod, filter=None, sort_keys=None):
if filter is not None:
lod = (r for r in lod if filter(r))
if sort_keys is not None:
lod = sorted(lod, key=lambda r:[r[k] for k in sort_keys])
else:
lod = list(lod)
return lod
def lookup_lod(lod, **kw):
for row in lod:
for k,v in kw.iteritems():
if row[k] != str(v): break
else:
return row
return None
</code></pre>
<p>Testing then yields:</p>
<pre><code>>>> lod = []
>>> populate_lod(lod, csv_fp)
>>>
>>> pprint(lookup_lod(lod, Row=1))
{'Name': 'Cat', 'Priority': '1', 'Row': '1', 'Year': '1998'}
>>> pprint(lookup_lod(lod, Name='Aardvark'))
{'Name': 'Aardvark', 'Priority': '1', 'Row': '4', 'Year': '2000'}
>>> pprint(query_lod(lod, sort_keys=('Priority', 'Year')))
[{'Name': 'Cat', 'Priority': '1', 'Row': '1', 'Year': '1998'},
{'Name': 'Dog', 'Priority': '1', 'Row': '3', 'Year': '1999'},
{'Name': 'Aardvark', 'Priority': '1', 'Row': '4', 'Year': '2000'},
{'Name': 'Wallaby', 'Priority': '1', 'Row': '5', 'Year': '2000'},
{'Name': 'Fish', 'Priority': '2', 'Row': '2', 'Year': '1998'},
{'Name': 'Zebra', 'Priority': '3', 'Row': '6', 'Year': '2001'}]
>>> pprint(query_lod(lod, sort_keys=('Year', 'Priority')))
[{'Name': 'Cat', 'Priority': '1', 'Row': '1', 'Year': '1998'},
{'Name': 'Fish', 'Priority': '2', 'Row': '2', 'Year': '1998'},
{'Name': 'Dog', 'Priority': '1', 'Row': '3', 'Year': '1999'},
{'Name': 'Aardvark', 'Priority': '1', 'Row': '4', 'Year': '2000'},
{'Name': 'Wallaby', 'Priority': '1', 'Row': '5', 'Year': '2000'},
{'Name': 'Zebra', 'Priority': '3', 'Row': '6', 'Year': '2001'}]
>>> print len(query_lod(lod, lambda r:1997 <= int(r['Year']) <= 2002))
6
>>> print len(query_lod(lod, lambda r:int(r['Year'])==1998 and int(r['Priority']) > 2))
0
</code></pre>
<p>Personally I like the SQLite version better since it preserves your types better (without extra conversion code in Python) and easily grows to accommodate future requirements. But then again, I'm quite comfortable with SQL, so YMMV.</p>
| 48 | 2009-06-24T13:00:00Z | [
"python",
"data-structures"
] |
Data structure for maintaining tabular data in memory? | 1,038,160 | <p>My scenario is as follows: I have a table of data (handful of fields, less than a hundred rows) that I use extensively in my program. I also need this data to be persistent, so I save it as a CSV and load it on start-up. I choose not to use a database because every option (even SQLite) is an overkill for my humble requirement (also - I would like to be able to edit the values offline in a simple way, and nothing is simpler than notepad).</p>
<p>Assume my data looks as follows (in the file it's comma separated without titles, this is just an illustration):</p>
<pre><code> Row | Name | Year | Priority
------------------------------------
1 | Cat | 1998 | 1
2 | Fish | 1998 | 2
3 | Dog | 1999 | 1
4 | Aardvark | 2000 | 1
5 | Wallaby | 2000 | 1
6 | Zebra | 2001 | 3
</code></pre>
<p>Notes:</p>
<ol>
<li>Row may be a "real" value written to the file or just an auto-generated value that represents the row number. Either way it exists in memory.</li>
<li>Names are unique.</li>
</ol>
<p>Things I do with the data:</p>
<ol>
<li>Look-up a row based on either ID (iteration) or name (direct access).</li>
<li>Display the table in different orders based on multiple field: I need to sort it e.g. by Priority and then Year, or Year and then Priority, etc.</li>
<li>I need to count instances based on sets of parameters, e.g. how many rows have their year between 1997 and 2002, or how many rows are in 1998 and priority > 2, etc.</li>
</ol>
<p>I know this "cries" for SQL...</p>
<p>I'm trying to figure out what's the best choice for data structure. Following are several choices I see:</p>
<p>List of row lists:</p>
<pre><code>a = []
a.append( [1, "Cat", 1998, 1] )
a.append( [2, "Fish", 1998, 2] )
a.append( [3, "Dog", 1999, 1] )
...
</code></pre>
<p>List of column lists (there will obviously be an API for add_row etc):</p>
<pre><code>a = []
a.append( [1, 2, 3, 4, 5, 6] )
a.append( ["Cat", "Fish", "Dog", "Aardvark", "Wallaby", "Zebra"] )
a.append( [1998, 1998, 1999, 2000, 2000, 2001] )
a.append( [1, 2, 1, 1, 1, 3] )
</code></pre>
<p>Dictionary of columns lists (constants can be created to replace the string keys):</p>
<pre><code>a = {}
a['ID'] = [1, 2, 3, 4, 5, 6]
a['Name'] = ["Cat", "Fish", "Dog", "Aardvark", "Wallaby", "Zebra"]
a['Year'] = [1998, 1998, 1999, 2000, 2000, 2001]
a['Priority'] = [1, 2, 1, 1, 1, 3]
</code></pre>
<p>Dictionary with keys being tuples of (Row, Field):</p>
<pre><code>Create constants to avoid string searching
NAME=1
YEAR=2
PRIORITY=3
a={}
a[(1, NAME)] = "Cat"
a[(1, YEAR)] = 1998
a[(1, PRIORITY)] = 1
a[(2, NAME)] = "Fish"
a[(2, YEAR)] = 1998
a[(2, PRIORITY)] = 2
...
</code></pre>
<p>And I'm sure there are other ways... However each way has disadvantages when it comes to my requirements (complex ordering and counting). </p>
<p>What's the recommended approach?</p>
<p>EDIT:</p>
<p>To clarify, performance is not a major issue for me. Because the table is so small, I believe almost every operation will be in the range of milliseconds, which is not a concern for my application.</p>
| 42 | 2009-06-24T12:48:51Z | 1,038,204 | <p>First, given that you have a complex data retrieval scenario, are you sure even SQLite is overkill?</p>
<p>You'll end up having an ad hoc, informally-specified, bug-ridden, slow implementation of half of SQLite, paraphrasing <a href="http://en.wikipedia.org/wiki/Greenspun%27s%5FTenth%5FRule" rel="nofollow">Greenspun's Tenth Rule</a>.</p>
<p>That said, you are very right in saying that choosing a single data structure will impact one or more of searching, sorting or counting, so if performance is paramount and your data is constant, you could consider having more than one structure for different purposes. </p>
<p>Above all, measure what operations will be more common and decide which structure will end up costing less.</p>
| 4 | 2009-06-24T13:00:06Z | [
"python",
"data-structures"
] |
Data structure for maintaining tabular data in memory? | 1,038,160 | <p>My scenario is as follows: I have a table of data (handful of fields, less than a hundred rows) that I use extensively in my program. I also need this data to be persistent, so I save it as a CSV and load it on start-up. I choose not to use a database because every option (even SQLite) is an overkill for my humble requirement (also - I would like to be able to edit the values offline in a simple way, and nothing is simpler than notepad).</p>
<p>Assume my data looks as follows (in the file it's comma separated without titles, this is just an illustration):</p>
<pre><code> Row | Name | Year | Priority
------------------------------------
1 | Cat | 1998 | 1
2 | Fish | 1998 | 2
3 | Dog | 1999 | 1
4 | Aardvark | 2000 | 1
5 | Wallaby | 2000 | 1
6 | Zebra | 2001 | 3
</code></pre>
<p>Notes:</p>
<ol>
<li>Row may be a "real" value written to the file or just an auto-generated value that represents the row number. Either way it exists in memory.</li>
<li>Names are unique.</li>
</ol>
<p>Things I do with the data:</p>
<ol>
<li>Look-up a row based on either ID (iteration) or name (direct access).</li>
<li>Display the table in different orders based on multiple field: I need to sort it e.g. by Priority and then Year, or Year and then Priority, etc.</li>
<li>I need to count instances based on sets of parameters, e.g. how many rows have their year between 1997 and 2002, or how many rows are in 1998 and priority > 2, etc.</li>
</ol>
<p>I know this "cries" for SQL...</p>
<p>I'm trying to figure out what's the best choice for data structure. Following are several choices I see:</p>
<p>List of row lists:</p>
<pre><code>a = []
a.append( [1, "Cat", 1998, 1] )
a.append( [2, "Fish", 1998, 2] )
a.append( [3, "Dog", 1999, 1] )
...
</code></pre>
<p>List of column lists (there will obviously be an API for add_row etc):</p>
<pre><code>a = []
a.append( [1, 2, 3, 4, 5, 6] )
a.append( ["Cat", "Fish", "Dog", "Aardvark", "Wallaby", "Zebra"] )
a.append( [1998, 1998, 1999, 2000, 2000, 2001] )
a.append( [1, 2, 1, 1, 1, 3] )
</code></pre>
<p>Dictionary of columns lists (constants can be created to replace the string keys):</p>
<pre><code>a = {}
a['ID'] = [1, 2, 3, 4, 5, 6]
a['Name'] = ["Cat", "Fish", "Dog", "Aardvark", "Wallaby", "Zebra"]
a['Year'] = [1998, 1998, 1999, 2000, 2000, 2001]
a['Priority'] = [1, 2, 1, 1, 1, 3]
</code></pre>
<p>Dictionary with keys being tuples of (Row, Field):</p>
<pre><code>Create constants to avoid string searching
NAME=1
YEAR=2
PRIORITY=3
a={}
a[(1, NAME)] = "Cat"
a[(1, YEAR)] = 1998
a[(1, PRIORITY)] = 1
a[(2, NAME)] = "Fish"
a[(2, YEAR)] = 1998
a[(2, PRIORITY)] = 2
...
</code></pre>
<p>And I'm sure there are other ways... However each way has disadvantages when it comes to my requirements (complex ordering and counting). </p>
<p>What's the recommended approach?</p>
<p>EDIT:</p>
<p>To clarify, performance is not a major issue for me. Because the table is so small, I believe almost every operation will be in the range of milliseconds, which is not a concern for my application.</p>
| 42 | 2009-06-24T12:48:51Z | 1,038,249 | <p>Have a Table class whose rows is a list of dict or better row objects</p>
<p>In table do not directly add rows but have a method which update few lookup maps e.g. for name
if you are not adding rows in order or id are not consecutive you can have idMap too
e.g.</p>
<pre><code>class Table(object):
def __init__(self):
self.rows = []# list of row objects, we assume if order of id
self.nameMap = {} # for faster direct lookup for row by name
def addRow(self, row):
self.rows.append(row)
self.nameMap[row['name']] = row
def getRow(self, name):
return self.nameMap[name]
table = Table()
table.addRow({'ID':1,'name':'a'})
</code></pre>
| 6 | 2009-06-24T13:12:43Z | [
"python",
"data-structures"
] |
Data structure for maintaining tabular data in memory? | 1,038,160 | <p>My scenario is as follows: I have a table of data (handful of fields, less than a hundred rows) that I use extensively in my program. I also need this data to be persistent, so I save it as a CSV and load it on start-up. I choose not to use a database because every option (even SQLite) is an overkill for my humble requirement (also - I would like to be able to edit the values offline in a simple way, and nothing is simpler than notepad).</p>
<p>Assume my data looks as follows (in the file it's comma separated without titles, this is just an illustration):</p>
<pre><code> Row | Name | Year | Priority
------------------------------------
1 | Cat | 1998 | 1
2 | Fish | 1998 | 2
3 | Dog | 1999 | 1
4 | Aardvark | 2000 | 1
5 | Wallaby | 2000 | 1
6 | Zebra | 2001 | 3
</code></pre>
<p>Notes:</p>
<ol>
<li>Row may be a "real" value written to the file or just an auto-generated value that represents the row number. Either way it exists in memory.</li>
<li>Names are unique.</li>
</ol>
<p>Things I do with the data:</p>
<ol>
<li>Look-up a row based on either ID (iteration) or name (direct access).</li>
<li>Display the table in different orders based on multiple field: I need to sort it e.g. by Priority and then Year, or Year and then Priority, etc.</li>
<li>I need to count instances based on sets of parameters, e.g. how many rows have their year between 1997 and 2002, or how many rows are in 1998 and priority > 2, etc.</li>
</ol>
<p>I know this "cries" for SQL...</p>
<p>I'm trying to figure out what's the best choice for data structure. Following are several choices I see:</p>
<p>List of row lists:</p>
<pre><code>a = []
a.append( [1, "Cat", 1998, 1] )
a.append( [2, "Fish", 1998, 2] )
a.append( [3, "Dog", 1999, 1] )
...
</code></pre>
<p>List of column lists (there will obviously be an API for add_row etc):</p>
<pre><code>a = []
a.append( [1, 2, 3, 4, 5, 6] )
a.append( ["Cat", "Fish", "Dog", "Aardvark", "Wallaby", "Zebra"] )
a.append( [1998, 1998, 1999, 2000, 2000, 2001] )
a.append( [1, 2, 1, 1, 1, 3] )
</code></pre>
<p>Dictionary of columns lists (constants can be created to replace the string keys):</p>
<pre><code>a = {}
a['ID'] = [1, 2, 3, 4, 5, 6]
a['Name'] = ["Cat", "Fish", "Dog", "Aardvark", "Wallaby", "Zebra"]
a['Year'] = [1998, 1998, 1999, 2000, 2000, 2001]
a['Priority'] = [1, 2, 1, 1, 1, 3]
</code></pre>
<p>Dictionary with keys being tuples of (Row, Field):</p>
<pre><code>Create constants to avoid string searching
NAME=1
YEAR=2
PRIORITY=3
a={}
a[(1, NAME)] = "Cat"
a[(1, YEAR)] = 1998
a[(1, PRIORITY)] = 1
a[(2, NAME)] = "Fish"
a[(2, YEAR)] = 1998
a[(2, PRIORITY)] = 2
...
</code></pre>
<p>And I'm sure there are other ways... However each way has disadvantages when it comes to my requirements (complex ordering and counting). </p>
<p>What's the recommended approach?</p>
<p>EDIT:</p>
<p>To clarify, performance is not a major issue for me. Because the table is so small, I believe almost every operation will be in the range of milliseconds, which is not a concern for my application.</p>
| 42 | 2009-06-24T12:48:51Z | 23,554,199 | <p>A very old question I know but...</p>
<p>A pandas DataFrame seems to be the ideal option here.</p>
<p><a href="http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.DataFrame.html">http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.DataFrame.html</a></p>
<p>From the blurb</p>
<blockquote>
<p>Two-dimensional size-mutable, potentially heterogeneous tabular data
structure with labeled axes (rows and columns). Arithmetic operations
align on both row and column labels. Can be thought of as a dict-like
container for Series objects. The primary pandas data structure</p>
</blockquote>
<p><a href="http://pandas.pydata.org/">http://pandas.pydata.org/</a></p>
| 16 | 2014-05-08T23:18:39Z | [
"python",
"data-structures"
] |
Data structure for maintaining tabular data in memory? | 1,038,160 | <p>My scenario is as follows: I have a table of data (handful of fields, less than a hundred rows) that I use extensively in my program. I also need this data to be persistent, so I save it as a CSV and load it on start-up. I choose not to use a database because every option (even SQLite) is an overkill for my humble requirement (also - I would like to be able to edit the values offline in a simple way, and nothing is simpler than notepad).</p>
<p>Assume my data looks as follows (in the file it's comma separated without titles, this is just an illustration):</p>
<pre><code> Row | Name | Year | Priority
------------------------------------
1 | Cat | 1998 | 1
2 | Fish | 1998 | 2
3 | Dog | 1999 | 1
4 | Aardvark | 2000 | 1
5 | Wallaby | 2000 | 1
6 | Zebra | 2001 | 3
</code></pre>
<p>Notes:</p>
<ol>
<li>Row may be a "real" value written to the file or just an auto-generated value that represents the row number. Either way it exists in memory.</li>
<li>Names are unique.</li>
</ol>
<p>Things I do with the data:</p>
<ol>
<li>Look-up a row based on either ID (iteration) or name (direct access).</li>
<li>Display the table in different orders based on multiple field: I need to sort it e.g. by Priority and then Year, or Year and then Priority, etc.</li>
<li>I need to count instances based on sets of parameters, e.g. how many rows have their year between 1997 and 2002, or how many rows are in 1998 and priority > 2, etc.</li>
</ol>
<p>I know this "cries" for SQL...</p>
<p>I'm trying to figure out what's the best choice for data structure. Following are several choices I see:</p>
<p>List of row lists:</p>
<pre><code>a = []
a.append( [1, "Cat", 1998, 1] )
a.append( [2, "Fish", 1998, 2] )
a.append( [3, "Dog", 1999, 1] )
...
</code></pre>
<p>List of column lists (there will obviously be an API for add_row etc):</p>
<pre><code>a = []
a.append( [1, 2, 3, 4, 5, 6] )
a.append( ["Cat", "Fish", "Dog", "Aardvark", "Wallaby", "Zebra"] )
a.append( [1998, 1998, 1999, 2000, 2000, 2001] )
a.append( [1, 2, 1, 1, 1, 3] )
</code></pre>
<p>Dictionary of columns lists (constants can be created to replace the string keys):</p>
<pre><code>a = {}
a['ID'] = [1, 2, 3, 4, 5, 6]
a['Name'] = ["Cat", "Fish", "Dog", "Aardvark", "Wallaby", "Zebra"]
a['Year'] = [1998, 1998, 1999, 2000, 2000, 2001]
a['Priority'] = [1, 2, 1, 1, 1, 3]
</code></pre>
<p>Dictionary with keys being tuples of (Row, Field):</p>
<pre><code>Create constants to avoid string searching
NAME=1
YEAR=2
PRIORITY=3
a={}
a[(1, NAME)] = "Cat"
a[(1, YEAR)] = 1998
a[(1, PRIORITY)] = 1
a[(2, NAME)] = "Fish"
a[(2, YEAR)] = 1998
a[(2, PRIORITY)] = 2
...
</code></pre>
<p>And I'm sure there are other ways... However each way has disadvantages when it comes to my requirements (complex ordering and counting). </p>
<p>What's the recommended approach?</p>
<p>EDIT:</p>
<p>To clarify, performance is not a major issue for me. Because the table is so small, I believe almost every operation will be in the range of milliseconds, which is not a concern for my application.</p>
| 42 | 2009-06-24T12:48:51Z | 24,111,934 | <h1>I personally wrote a lib for pretty much that quite recently, it is called BD_XML</h1>
<p>as its most fundamental reason of existence is to serve as a way to send data back and forth between XML files and SQL databases.</p>
<p>It is written in Spanish (if that matters in a programming language) but it is very simple.</p>
<pre><code>from BD_XML import Tabla
</code></pre>
<p>It defines an object called Tabla (Table), it can be created with a name for identification an a pre-created connection object of a pep-246 compatible database interface.</p>
<pre><code>Table = Tabla('Animals')
</code></pre>
<p>Then you need to add columns with the <code>agregar_columna</code> (add_column) method, with can take various key word arguments:</p>
<ul>
<li><p><code>campo</code> (field): the name of the field</p></li>
<li><p><code>tipo</code> (type): the type of data stored, can be a things like 'varchar' and 'double' or name of python objects if you aren't interested in exporting to a data base latter.</p></li>
<li><p><code>defecto</code> (default): set a default value for the column if there is none when you add a row</p></li>
<li><p>there are other 3 but are only there for database tings and not actually functional</p></li>
</ul>
<p>like:</p>
<pre><code>Table.agregar_columna(campo='Name', tipo='str')
Table.agregar_columna(campo='Year', tipo='date')
#declaring it date, time, datetime or timestamp is important for being able to store it as a time object and not only as a number, But you can always put it as a int if you don't care for dates
Table.agregar_columna(campo='Priority', tipo='int')
</code></pre>
<p>Then you add the rows with the += operator (or + if you want to create a copy with an extra row)</p>
<pre><code>Table += ('Cat', date(1998,1,1), 1)
Table += {'Year':date(1998,1,1), 'Priority':2, Name:'Fish'}
#â¦
#The condition for adding is that is a container accessible with either the column name or the position of the column in the table
</code></pre>
<p>Then you can generate XML and write it to a file with <code>exportar_XML</code> (export_XML) and <code>escribir_XML</code> (write_XML):</p>
<pre><code>file = os.path.abspath(os.path.join(os.path.dirname(__file__), 'Animals.xml'))
Table.exportar_xml()
Table.escribir_xml(file)
</code></pre>
<p>And then import it back with <code>importar_XML</code> (import_XML) with the file name and indication that you are using a file and not an string literal:</p>
<pre><code>Table.importar_xml(file, tipo='archivo')
#archivo means file
</code></pre>
<h2>Advanced</h2>
<p>This are ways you can use a Tabla object in a SQL manner.</p>
<pre><code>#UPDATE <Table> SET Name = CONCAT(Name,' ',Priority), Priority = NULL WHERE id = 2
for row in Table:
if row['id'] == 2:
row['Name'] += ' ' + row['Priority']
row['Priority'] = None
print(Table)
#DELETE FROM <Table> WHERE MOD(id,2) = 0 LIMIT 1
n = 0
nmax = 1
for row in Table:
if row['id'] % 2 == 0:
del Table[row]
n += 1
if n >= nmax: break
print(Table)
</code></pre>
<p>this examples assume a column named 'id'
but can be replaced width row.pos for your example.</p>
<pre><code>if row.pos == 2:
</code></pre>
<h1>The file can be download from:</h1>
<p><a href="https://bitbucket.org/WolfangT/librerias" rel="nofollow">https://bitbucket.org/WolfangT/librerias</a></p>
| 2 | 2014-06-08T23:30:20Z | [
"python",
"data-structures"
] |
Custom Managers and "through" | 1,038,542 | <p>I have a many-to-many relationship in my django application where I use the "add" method of the manager pretty heavily (ie album.photos.add() ).</p>
<p>I find myself needing to store some data about the many-to-many relationship now, but I don't want to lose the add method. Can I just set a default value for all the additional fields on the "through" model and somehow re-implement the add method?</p>
<p>I don't really know much about custom managers but I suspect that might be the right place to look.</p>
<h2>update:</h2>
<p>Been reading up on <a href="http://docs.djangoproject.com/en/dev/topics/db/managers/#set-use-for-related-fields-when-you-define-the-class" rel="nofollow">custom managers</a>... maybe I can just keep the add/remove/etc from being disabled when I add the "through" argument to my Many-to-many field?</p>
<p>Does anyone know how to do that?</p>
| 1 | 2009-06-24T13:55:42Z | 1,045,085 | <p>Simplest way is to just add a method to Album (i.e. album.add_photo()) which handles the metadata and manually creates a properly-linked Photo instance.</p>
<p>If you want to get all funky, you can write a custom manager for Photos, make it the default (i.e. first assigned manager), set <a href="http://docs.djangoproject.com/en/dev/topics/db/managers/#controlling-automatic-manager-types" rel="nofollow">use_for_related_fields = True</a> on it, and give it an add() method that is able to properly set the default metadata for the relationship.</p>
<p>Aside: seems like it wouldn't be too hard for Django to make this generic; instead of removing the add() method when there's a through table, just make add() accept arbitrary kwargs and treat them as data for the through table.</p>
| 2 | 2009-06-25T17:07:40Z | [
"python",
"django",
"many-to-many",
"models",
"manager"
] |
In Python, how do I easily generate an image file from some source data? | 1,038,550 | <p>I have some some data that I would like to visualize. Each byte of the source data roughly corresponds to a pixel value of the image.</p>
<p>What is the easiest way to generate an image file (bitmap?) using Python?</p>
| 13 | 2009-06-24T13:57:05Z | 1,038,562 | <p>Have a look at <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a> and <a href="http://www.pygame.org/news.html" rel="nofollow">pyGame</a>. Both of them allow you to draw on a canvas and then save it to a file.</p>
| 3 | 2009-06-24T14:00:02Z | [
"python",
"image",
"data-visualization"
] |
In Python, how do I easily generate an image file from some source data? | 1,038,550 | <p>I have some some data that I would like to visualize. Each byte of the source data roughly corresponds to a pixel value of the image.</p>
<p>What is the easiest way to generate an image file (bitmap?) using Python?</p>
| 13 | 2009-06-24T13:57:05Z | 1,038,569 | <p>You can create images with a list of pixel values using <a href="http://python-pillow.github.io/">Pillow</a>:</p>
<pre><code>from PIL import Image
img = Image.new('RGB', (width, height))
img.putdata(my_list)
img.save('image.png')
</code></pre>
| 17 | 2009-06-24T14:00:37Z | [
"python",
"image",
"data-visualization"
] |
How should I setup the Wing IDE for use with IronPython | 1,038,695 | <p>Here is a screen where I should point the Wing IDE to my python files. I am using IronPython.</p>
<p><img src="http://i42.tinypic.com/23k6vzn.jpg" alt="alt text" /></p>
<p>Am I assuming correctly that textbox one gets filled with ipy.exe ? (proper path provided)</p>
<p>What should be in the rest of the boxes ?</p>
| 0 | 2009-06-24T14:24:23Z | 1,040,700 | <p>I do not know about your question in particular; however few weeks ago, Michael Foord published a guide for using WingIde with IronPython.<br />
You can find it here: <a href="http://www.voidspace.org.uk/ironpython/wing-how-to.shtml" rel="nofollow">http://www.voidspace.org.uk/ironpython/wing-how-to.shtml</a></p>
| 2 | 2009-06-24T20:14:05Z | [
"python",
"ironpython",
"wing-ide"
] |
How should I setup the Wing IDE for use with IronPython | 1,038,695 | <p>Here is a screen where I should point the Wing IDE to my python files. I am using IronPython.</p>
<p><img src="http://i42.tinypic.com/23k6vzn.jpg" alt="alt text" /></p>
<p>Am I assuming correctly that textbox one gets filled with ipy.exe ? (proper path provided)</p>
<p>What should be in the rest of the boxes ?</p>
| 0 | 2009-06-24T14:24:23Z | 1,070,239 | <ul>
<li>Wing IDE at the moment doesn't allow the debug mode with IronPython. You need to link the IDE to the CPython install. (Michael Foord words in the article <a href="http://www.voidspace.org.uk/ironpython/wing-how-to.shtml" rel="nofollow">http://www.voidspace.org.uk/ironpython/wing-how-to.shtml</a>][1]).</li>
<li>Wing IDE wouldn't run the shell while pointing at Python 3.1. I am unsure whether that is something I have done wrong or that the incompabilities aren't sorted out yet.</li>
</ul>
<p>I have installed CPython implementation from Python download site.<a href="http://python.org/download/" rel="nofollow">Python download</a>
I have set the Python executable path to the python.exe that gets installed to your Python Install directory.
I have modified the enviroment variables and added the Python directory to the PATH variable.</p>
| 0 | 2009-07-01T16:57:29Z | [
"python",
"ironpython",
"wing-ide"
] |
How do I remove a substring from the end of a string in Python? | 1,038,824 | <p>I have the following code:</p>
<pre><code>url = 'abcdc.com'
print(url.strip('.com'))
</code></pre>
<p>I expected: <code>abcdc</code></p>
<p>I got: <code>abcd</code></p>
<p>Now I do </p>
<pre><code>url.rsplit('.com', 1)
</code></pre>
<p>Is there a better way?</p>
| 151 | 2009-06-24T14:44:01Z | 1,038,845 | <p>You could do this:</p>
<pre><code>url = 'abcdc.com'
if url.endswith('.com'):
url = url[:-4]
</code></pre>
<p>Or using regular expressions:</p>
<pre><code>import re
url = 'abcdc.com'
url = re.sub('\.com$', '', url)
</code></pre>
| 222 | 2009-06-24T14:47:41Z | [
"python",
"string"
] |
How do I remove a substring from the end of a string in Python? | 1,038,824 | <p>I have the following code:</p>
<pre><code>url = 'abcdc.com'
print(url.strip('.com'))
</code></pre>
<p>I expected: <code>abcdc</code></p>
<p>I got: <code>abcd</code></p>
<p>Now I do </p>
<pre><code>url.rsplit('.com', 1)
</code></pre>
<p>Is there a better way?</p>
| 151 | 2009-06-24T14:44:01Z | 1,038,847 | <p>How about <code>url[:-4]</code>?</p>
| 5 | 2009-06-24T14:48:21Z | [
"python",
"string"
] |
How do I remove a substring from the end of a string in Python? | 1,038,824 | <p>I have the following code:</p>
<pre><code>url = 'abcdc.com'
print(url.strip('.com'))
</code></pre>
<p>I expected: <code>abcdc</code></p>
<p>I got: <code>abcd</code></p>
<p>Now I do </p>
<pre><code>url.rsplit('.com', 1)
</code></pre>
<p>Is there a better way?</p>
| 151 | 2009-06-24T14:44:01Z | 1,038,848 | <p><strong>strip</strong> strips the characters given from both ends of the string, in your case it strips ".", "c", "o" and "m".</p>
| 15 | 2009-06-24T14:48:49Z | [
"python",
"string"
] |
How do I remove a substring from the end of a string in Python? | 1,038,824 | <p>I have the following code:</p>
<pre><code>url = 'abcdc.com'
print(url.strip('.com'))
</code></pre>
<p>I expected: <code>abcdc</code></p>
<p>I got: <code>abcd</code></p>
<p>Now I do </p>
<pre><code>url.rsplit('.com', 1)
</code></pre>
<p>Is there a better way?</p>
| 151 | 2009-06-24T14:44:01Z | 1,038,873 | <p>This is a perfect use for regular expressions:</p>
<pre><code>>>> import re
>>> re.match(r"(.*)\.com", "hello.com").group(1)
'hello'
</code></pre>
| 0 | 2009-06-24T14:53:03Z | [
"python",
"string"
] |
How do I remove a substring from the end of a string in Python? | 1,038,824 | <p>I have the following code:</p>
<pre><code>url = 'abcdc.com'
print(url.strip('.com'))
</code></pre>
<p>I expected: <code>abcdc</code></p>
<p>I got: <code>abcd</code></p>
<p>Now I do </p>
<pre><code>url.rsplit('.com', 1)
</code></pre>
<p>Is there a better way?</p>
| 151 | 2009-06-24T14:44:01Z | 1,038,898 | <p>If you know it's an extension, then</p>
<pre>
url = 'abcdc.com'
...
url.split('.')[0]
</pre>
<p>This works equally well with abcdc.com as abcdc.[anything] and is more extensible.</p>
| 4 | 2009-06-24T14:57:24Z | [
"python",
"string"
] |
How do I remove a substring from the end of a string in Python? | 1,038,824 | <p>I have the following code:</p>
<pre><code>url = 'abcdc.com'
print(url.strip('.com'))
</code></pre>
<p>I expected: <code>abcdc</code></p>
<p>I got: <code>abcd</code></p>
<p>Now I do </p>
<pre><code>url.rsplit('.com', 1)
</code></pre>
<p>Is there a better way?</p>
| 151 | 2009-06-24T14:44:01Z | 1,038,902 | <p>I don't see anything wrong with the way you're doing it with rsplit, it does exactly what you want. It all depends on how generic you want the solution to be. Do you always want to remove .com, or will it sometimes be .org? If that is the case, use one of the other solutions, otherwise, stick with rsplit()</p>
<p>The reason that strip() does not work the way you expect is that it works on each character individually. It will scan through your string and remove all occurrences of the characters from the end AND the front. So if your string started with 'c', that would also be gone. You would use rstrip to only strip from the back.</p>
| 0 | 2009-06-24T14:58:14Z | [
"python",
"string"
] |
How do I remove a substring from the end of a string in Python? | 1,038,824 | <p>I have the following code:</p>
<pre><code>url = 'abcdc.com'
print(url.strip('.com'))
</code></pre>
<p>I expected: <code>abcdc</code></p>
<p>I got: <code>abcd</code></p>
<p>Now I do </p>
<pre><code>url.rsplit('.com', 1)
</code></pre>
<p>Is there a better way?</p>
| 151 | 2009-06-24T14:44:01Z | 1,038,909 | <p>Depends on what you know about your url and exactly what you're tryinh to do. If you know that it will always end in '.com' (or '.net' or '.org') then </p>
<pre><code> url=url[:-4]
</code></pre>
<p>is the quickest solution. If it's a more general URLs then you're probably better of looking into the urlparse library that comes with python. </p>
<p>If you on the other hand you simply want to remove everything after the final '.' in a string then </p>
<pre><code>url.rsplit('.',1)[0]
</code></pre>
<p>will work. Or if you want just want everything up to the first '.' then try</p>
<pre><code>url.split('.',1)[0]
</code></pre>
| 12 | 2009-06-24T14:59:35Z | [
"python",
"string"
] |
How do I remove a substring from the end of a string in Python? | 1,038,824 | <p>I have the following code:</p>
<pre><code>url = 'abcdc.com'
print(url.strip('.com'))
</code></pre>
<p>I expected: <code>abcdc</code></p>
<p>I got: <code>abcd</code></p>
<p>Now I do </p>
<pre><code>url.rsplit('.com', 1)
</code></pre>
<p>Is there a better way?</p>
| 151 | 2009-06-24T14:44:01Z | 1,038,999 | <pre><code>def strip_end(text, suffix):
if not text.endswith(suffix):
return text
return text[:len(text)-len(suffix)]
</code></pre>
| 24 | 2009-06-24T15:13:09Z | [
"python",
"string"
] |
How do I remove a substring from the end of a string in Python? | 1,038,824 | <p>I have the following code:</p>
<pre><code>url = 'abcdc.com'
print(url.strip('.com'))
</code></pre>
<p>I expected: <code>abcdc</code></p>
<p>I got: <code>abcd</code></p>
<p>Now I do </p>
<pre><code>url.rsplit('.com', 1)
</code></pre>
<p>Is there a better way?</p>
| 151 | 2009-06-24T14:44:01Z | 2,393,022 | <p>If you are sure that the string only appears at the end, then the simplest way would be to use 'replace':</p>
<pre><code>url = 'abcdc.com'
print url.replace('.com','')
</code></pre>
| 34 | 2010-03-06T15:41:45Z | [
"python",
"string"
] |
How do I remove a substring from the end of a string in Python? | 1,038,824 | <p>I have the following code:</p>
<pre><code>url = 'abcdc.com'
print(url.strip('.com'))
</code></pre>
<p>I expected: <code>abcdc</code></p>
<p>I got: <code>abcd</code></p>
<p>Now I do </p>
<pre><code>url.rsplit('.com', 1)
</code></pre>
<p>Is there a better way?</p>
| 151 | 2009-06-24T14:44:01Z | 13,112,628 | <p>In one line:</p>
<pre><code>text if not text.endswith(suffix) or len(suffix) == 0 else text[:-len(suffix)]
</code></pre>
| 5 | 2012-10-28T20:17:44Z | [
"python",
"string"
] |
How do I remove a substring from the end of a string in Python? | 1,038,824 | <p>I have the following code:</p>
<pre><code>url = 'abcdc.com'
print(url.strip('.com'))
</code></pre>
<p>I expected: <code>abcdc</code></p>
<p>I got: <code>abcd</code></p>
<p>Now I do </p>
<pre><code>url.rsplit('.com', 1)
</code></pre>
<p>Is there a better way?</p>
| 151 | 2009-06-24T14:44:01Z | 13,759,827 | <p>Or you can use split:</p>
<pre><code>a = 'abccomputer.com'
res = a.split('.com',1)[0]
</code></pre>
| 0 | 2012-12-07T08:57:35Z | [
"python",
"string"
] |
How do I remove a substring from the end of a string in Python? | 1,038,824 | <p>I have the following code:</p>
<pre><code>url = 'abcdc.com'
print(url.strip('.com'))
</code></pre>
<p>I expected: <code>abcdc</code></p>
<p>I got: <code>abcd</code></p>
<p>Now I do </p>
<pre><code>url.rsplit('.com', 1)
</code></pre>
<p>Is there a better way?</p>
| 151 | 2009-06-24T14:44:01Z | 16,411,412 | <p>For urls (as it seems to be a part of the topic by the given example), one can do something like this:</p>
<pre><code>import os
url = 'http://www.stackoverflow.com'
name,ext = os.path.splitext(url)
print (name, ext)
#Or:
ext = '.'+url.split('.')[-1]
name = url[:-len(ext)]
print (name, ext)
</code></pre>
<p>Both will output:
<code>('http://www.stackoverflow', '.com')</code></p>
<p>This can also be combined with <code>str.endswith(suffix)</code> if you need to just split ".com", or anything specific. </p>
| 3 | 2013-05-07T04:49:17Z | [
"python",
"string"
] |
How do I remove a substring from the end of a string in Python? | 1,038,824 | <p>I have the following code:</p>
<pre><code>url = 'abcdc.com'
print(url.strip('.com'))
</code></pre>
<p>I expected: <code>abcdc</code></p>
<p>I got: <code>abcd</code></p>
<p>Now I do </p>
<pre><code>url.rsplit('.com', 1)
</code></pre>
<p>Is there a better way?</p>
| 151 | 2009-06-24T14:44:01Z | 24,794,474 | <pre><code>def remove_file_type(infile):
import re
return(re.sub('\.[^.]*$','',infile))
remove_file_type('abc.efg')'abc'
</code></pre>
| 0 | 2014-07-17T03:32:56Z | [
"python",
"string"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.