title stringlengths 10 172 | question_id int64 469 40.1M | question_body stringlengths 22 48.2k | question_score int64 -44 5.52k | question_date stringlengths 20 20 | answer_id int64 497 40.1M | answer_body stringlengths 18 33.9k | answer_score int64 -38 8.38k | answer_date stringlengths 20 20 | tags listlengths 1 5 |
|---|---|---|---|---|---|---|---|---|---|
Can seek and tell work with UTF-8 encoded documents in Python? | 1,510,188 | <p>I have an application that generates some large log files > 500MB.</p>
<p>I have written some utilities in Python that allows me to quickly browse the log file and find data of interest. But I now get some datasets where the file is too big to load it all into memory.</p>
<p>I thus want to scan the document once, build an index and then only load the section of the document into memory that I want to look at at a time.</p>
<p>This works for me when I open a 'file' read it one line at a time and store the offset with from file.tell().
I can then come back to that section of the file later with file.seek( offset, 0 ).</p>
<p>My problem is however that I may have UTF-8 in the log files so I need to open them with the codecs module (<code>codecs.open(<filename>, 'r', 'utf-8')</code>). With the resulting object I can call seek and tell but they do not match up.</p>
<p>I assume that codecs needs to do some buffering or maybe it returns character counts instead of bytes from tell?</p>
<p>Is there a way around this?</p>
| 2 | 2009-10-02T15:17:21Z | 1,510,276 | <p>If true, this sounds like a bug or limitation of the codecs module, as it's probably confusing byte and character offsets.</p>
<p>I would use the regular <code>open()</code> function for opening the file, then <code>seek()</code>/<code>tell()</code> will give you byte offsets that are always consistent. Whenever you want to read, use <code>f.readline().decode('utf-8')</code>.</p>
<p>Beware though, that using the <code>f.read()</code> function can land you in the middle of a multi-byte character, thus producing an UTF-8 decode error. <code>readline()</code> will always work.</p>
<p>This doesn't transparently handle the byte-order mark for you, but chances are your log files do not have BOMs anyway.</p>
| 1 | 2009-10-02T15:31:09Z | [
"python",
"utf-8",
"codec",
"seek"
] |
Can seek and tell work with UTF-8 encoded documents in Python? | 1,510,188 | <p>I have an application that generates some large log files > 500MB.</p>
<p>I have written some utilities in Python that allows me to quickly browse the log file and find data of interest. But I now get some datasets where the file is too big to load it all into memory.</p>
<p>I thus want to scan the document once, build an index and then only load the section of the document into memory that I want to look at at a time.</p>
<p>This works for me when I open a 'file' read it one line at a time and store the offset with from file.tell().
I can then come back to that section of the file later with file.seek( offset, 0 ).</p>
<p>My problem is however that I may have UTF-8 in the log files so I need to open them with the codecs module (<code>codecs.open(<filename>, 'r', 'utf-8')</code>). With the resulting object I can call seek and tell but they do not match up.</p>
<p>I assume that codecs needs to do some buffering or maybe it returns character counts instead of bytes from tell?</p>
<p>Is there a way around this?</p>
| 2 | 2009-10-02T15:17:21Z | 1,510,282 | <p>For UTF-8, you don't actually need to open the file with codecs.open. Instead, it is reliable to read the file as a byte string first, and only then decode an individual section (invoking the .decode method on the string). Breaking the file at line boundaries is safe; the only unsafe way to split it would be in the middle of a multi-byte character (which you can recognize from its byte value > 128).</p>
| 1 | 2009-10-02T15:32:08Z | [
"python",
"utf-8",
"codec",
"seek"
] |
Can seek and tell work with UTF-8 encoded documents in Python? | 1,510,188 | <p>I have an application that generates some large log files > 500MB.</p>
<p>I have written some utilities in Python that allows me to quickly browse the log file and find data of interest. But I now get some datasets where the file is too big to load it all into memory.</p>
<p>I thus want to scan the document once, build an index and then only load the section of the document into memory that I want to look at at a time.</p>
<p>This works for me when I open a 'file' read it one line at a time and store the offset with from file.tell().
I can then come back to that section of the file later with file.seek( offset, 0 ).</p>
<p>My problem is however that I may have UTF-8 in the log files so I need to open them with the codecs module (<code>codecs.open(<filename>, 'r', 'utf-8')</code>). With the resulting object I can call seek and tell but they do not match up.</p>
<p>I assume that codecs needs to do some buffering or maybe it returns character counts instead of bytes from tell?</p>
<p>Is there a way around this?</p>
| 2 | 2009-10-02T15:17:21Z | 1,510,303 | <p>Update: You can't do seek/tell on the object returned by codec.open(). You need to use a normal file, and decode the strings to unicode after reading.</p>
<p>I do not know why it doesn't work but I can't make it work. The seek seems to only work once, for example. Then you need to close and reopen the file, which is of course not useful.</p>
<p>The tell does not use character positions, but doesn't show you where your position in the stream is (but probably where the underlying file object is in reading from disk).</p>
<p>So probably because of some sort of underlying buffering, you can't do it. But deocding after reading works just fine, so go for that.</p>
| 0 | 2009-10-02T15:36:01Z | [
"python",
"utf-8",
"codec",
"seek"
] |
Can seek and tell work with UTF-8 encoded documents in Python? | 1,510,188 | <p>I have an application that generates some large log files > 500MB.</p>
<p>I have written some utilities in Python that allows me to quickly browse the log file and find data of interest. But I now get some datasets where the file is too big to load it all into memory.</p>
<p>I thus want to scan the document once, build an index and then only load the section of the document into memory that I want to look at at a time.</p>
<p>This works for me when I open a 'file' read it one line at a time and store the offset with from file.tell().
I can then come back to that section of the file later with file.seek( offset, 0 ).</p>
<p>My problem is however that I may have UTF-8 in the log files so I need to open them with the codecs module (<code>codecs.open(<filename>, 'r', 'utf-8')</code>). With the resulting object I can call seek and tell but they do not match up.</p>
<p>I assume that codecs needs to do some buffering or maybe it returns character counts instead of bytes from tell?</p>
<p>Is there a way around this?</p>
| 2 | 2009-10-02T15:17:21Z | 1,510,468 | <p>Much of what goes on with UTF8 in python makes sense if you look at how it was done in Python 3. In your case, it'll make quite a bit more sense if you read the Files chapter in Dive into Python 3: <a href="http://diveintopython3.org/files.html" rel="nofollow">http://diveintopython3.org/files.html</a></p>
<p>The short of it, though, is that <code>file.seek</code> and <code>file.tell</code> work with byte positions, whereas unicode characters can take up multiple bytes. Thus, if you do:</p>
<pre><code>f.seek(10)
f.read(1)
f.tell()
</code></pre>
<p>You can easily get something other than <code>17</code>, depending on what length the one character you read was.</p>
| 0 | 2009-10-02T16:03:55Z | [
"python",
"utf-8",
"codec",
"seek"
] |
Link Checker (Spider Crawler) | 1,510,211 | <p>I am looking for a link checker to spider my website and log invalid links, the problem is that I have a Login page at the start which is required. What i want is a link checker to run through the command post login details then spider the rest of the website. </p>
<p>Any ideas guys will be appreciated.</p>
| 2 | 2009-10-02T15:20:49Z | 1,510,371 | <p>You want to look at the cookielib module: <a href="http://docs.python.org/library/cookielib.html" rel="nofollow">http://docs.python.org/library/cookielib.html</a>. It implements a full implementation of cookies, which will let you store login details. Once you're using a CookieJar, you just have to get login details from the user (say, from the console) and submit a proper POST request.</p>
| 2 | 2009-10-02T15:48:29Z | [
"python",
"hyperlink",
"web-crawler"
] |
Link Checker (Spider Crawler) | 1,510,211 | <p>I am looking for a link checker to spider my website and log invalid links, the problem is that I have a Login page at the start which is required. What i want is a link checker to run through the command post login details then spider the rest of the website. </p>
<p>Any ideas guys will be appreciated.</p>
| 2 | 2009-10-02T15:20:49Z | 1,511,607 | <p>I've just recently solved a similar problem like this:</p>
<pre><code>import urllib
import urllib2
import cookielib
login = 'user@host.com'
password = 'secret'
cookiejar = cookielib.CookieJar()
urlOpener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookiejar))
# adjust this to match the form's field names
values = {'username': login, 'password': password}
data = urllib.urlencode(values)
request = urllib2.Request('http://target.of.POST-method', data)
url = urlOpener.open(request)
# from now on, we're authenticated and we can access the rest of the site
url = urlOpener.open('http://rest.of.user.area')
</code></pre>
| 3 | 2009-10-02T20:20:23Z | [
"python",
"hyperlink",
"web-crawler"
] |
Django model refactoring and migration | 1,510,215 | <p>I'd like to refactor a number of django apps in a way which involves moving Models from one app into another where they can be more readily reused. </p>
<p>A number of these models have either ForeignKey relationships or M2M relationships to other models (such as User). For example:</p>
<pre><code>class Department(models.Model):
name = models.CharField(max_length=255)
reviewers = models.ManyToManyField(User)
</code></pre>
<p>In most cases, the models do not change, so I've currently just redefined them in the new app. This of course causes problems with related_name, since I have the same model defined in two separate apps, and <code>manage.py syncdb</code> gives the following error:</p>
<pre><code>new_app.department: Accessor for m2m field 'reviewers' clashes with related m2m field 'User.department_set'. Add a related_name argument to the definition for 'reviewers'.
old_app.department: Accessor for m2m field 'reviewers' clashes with related m2m field 'User.department_set'. Add a related_name argument to the definition for 'reviewers'.
</code></pre>
<p>When doing this, I also need to migrate the data keeping any automatically generated database ids. I'd planned on using the ORM to do the migration, thinking something like the following would work:</p>
<pre><code>from newapp.models import Department
import oldapp.models as old
for obj in old.Department.objects.all():
new_obj = Department(id=obj.id, name=obj.name)
new_obj.save()
for r in obj.reviewers.all():
new_obj.reviewers.add(r)
new_obj.save()
</code></pre>
<p>Of course, the <code>related_name</code> problem prevents me from doing this.</p>
<p>How have others made this sort of code refactor and migration possible? Thanks!</p>
| 2 | 2009-10-02T15:20:58Z | 1,510,443 | <p>Have you looked at using a migration tool such as <a href="http://south.aeracode.org/">South</a> or <a href="http://code.google.com/p/django-evolution/">django-evolution</a>?</p>
| 6 | 2009-10-02T15:59:41Z | [
"python",
"django",
"django-models"
] |
Django model refactoring and migration | 1,510,215 | <p>I'd like to refactor a number of django apps in a way which involves moving Models from one app into another where they can be more readily reused. </p>
<p>A number of these models have either ForeignKey relationships or M2M relationships to other models (such as User). For example:</p>
<pre><code>class Department(models.Model):
name = models.CharField(max_length=255)
reviewers = models.ManyToManyField(User)
</code></pre>
<p>In most cases, the models do not change, so I've currently just redefined them in the new app. This of course causes problems with related_name, since I have the same model defined in two separate apps, and <code>manage.py syncdb</code> gives the following error:</p>
<pre><code>new_app.department: Accessor for m2m field 'reviewers' clashes with related m2m field 'User.department_set'. Add a related_name argument to the definition for 'reviewers'.
old_app.department: Accessor for m2m field 'reviewers' clashes with related m2m field 'User.department_set'. Add a related_name argument to the definition for 'reviewers'.
</code></pre>
<p>When doing this, I also need to migrate the data keeping any automatically generated database ids. I'd planned on using the ORM to do the migration, thinking something like the following would work:</p>
<pre><code>from newapp.models import Department
import oldapp.models as old
for obj in old.Department.objects.all():
new_obj = Department(id=obj.id, name=obj.name)
new_obj.save()
for r in obj.reviewers.all():
new_obj.reviewers.add(r)
new_obj.save()
</code></pre>
<p>Of course, the <code>related_name</code> problem prevents me from doing this.</p>
<p>How have others made this sort of code refactor and migration possible? Thanks!</p>
| 2 | 2009-10-02T15:20:58Z | 1,510,762 | <p>You can very easily solve the immediate problem by just providing a related_name argument to the ForeignKey in either the new or old model, exactly as the error message tells you to. Not confident that will solve all your problems with this migration, but it will take you one step forward.</p>
| 0 | 2009-10-02T17:06:08Z | [
"python",
"django",
"django-models"
] |
Follow-up on iterating over a graph using XML minidom | 1,510,447 | <p>This is a follow-up to the question (<a href="http://stackoverflow.com/questions/1412004/reading-xml-using-python-minidom-and-iterating-over-each-node">Link</a>)</p>
<p>What I intend on doing is using the XML to create a graph using NetworkX. Looking at the DOM structure below, all nodes within the same node should have an edge between them, and all nodes that have attended the same conference should have a node to that conference. To summarize, all authors that worked together on a paper should be connected to each other, and all authors who have attended a particular conference should be connected to that conference. </p>
<pre><code><conference name="CONF 2009">
<paper>
<author>Yih-Chun Hu(UIUC)</author>
<author>David McGrew(Cisco Systems)</author>
<author>Adrian Perrig(CMU)</author>
<author>Brian Weis(Cisco Systems)</author>
<author>Dan Wendlandt(CMU)</author>
</paper>
<paper>
<author>Dan Wendlandt(CMU)</author>
<author>Ioannis Avramopoulos(Princeton)</author>
<author>David G. Andersen(CMU)</author>
<author>Jennifer Rexford(Princeton)</author>
</paper>
</conference>
</code></pre>
<p>I've figured out how to connect authors to conferences, but I'm unsure about how to connect authors to each other. The thing that I'm having difficulty with is how to iterate over the authors that have worked on the same paper and connect them together. </p>
<pre><code> dom = parse(filepath)
conference=dom.getElementsByTagName('conference')
for node in conference:
conf_name=node.getAttribute('name')
print conf_name
G.add_node(conf_name)
#The nodeValue is split in order to get the name of the author
#and to exclude the university they are part of
plist=node.getElementsByTagName('paper')
for p in plist:
author=str(p.childNodes[0].nodeValue)
author= author.split("(")
#Figure out a way to create edges between authors in the same <paper> </paper>
alist=node.getElementsByTagName('author')
for a in alist:
authortext= str(a.childNodes[0].nodeValue).split("(")
if authortext[0] in dict:
edgeQuantity=dict[authortext[0]]
edgeQuantity+=1
dict[authortext[0]]=edgeQuantity
G.add_edge(authortext[0],conf_name)
#Otherwise, add it to the dictionary and create an edge to the conference.
else:
dict[authortext[0]]= 1
G.add_node(authortext[0])
G.add_edge(authortext[0],conf_name)
i+=1
</code></pre>
| 0 | 2009-10-02T16:00:12Z | 1,510,710 | <blockquote>
<p>I'm unsure about how to connect authors to each other.</p>
</blockquote>
<p>You need to generate (author, otherauthor) pairs so you can add them as edges. The typical way to do that would be a nested iteration:</p>
<pre><code>for thing in things:
for otherthing in things:
add_edge(thing, otherthing)
</code></pre>
<p>This is a naïve implementation that includes self-loops (giving an author an edge connecting himself to himself), which you may or may not want; it also includes both (1,2) and (2,1), which if you're doing an undirected graph is redundant. (In Python 2.6, the built-in <a href="http://docs.python.org/library/itertools.html#itertools.permutations" rel="nofollow"><code>permutations</code></a> generator also does this.) Here's a generator that fixes these things:</p>
<pre><code>def pairs(l):
for i in range(len(l)-1):
for j in range(i+1, len(l)):
yield l[i], l[j]
</code></pre>
<p>I've not used NetworkX, but looking at the doc it seems to say you can call add_node on the same node twice (with nothing happening the second time). If so, you can discard the dict you were using to try to keep track of what nodes you'd inserted. Also, it seems to say that if you add an edge to an unknown node, it'll add that node for you automatically. So it should be possible to make the code much shorter:</p>
<pre><code>for conference in dom.getElementsByTagName('conference'):
var conf_name= node.getAttribute('name')
for paper in conference.getElementsByTagName('paper'):
authors= paper.getElementsByTagName('author')
auth_names= [author.firstChild.data.split('(')[0] for author in authors]
# Note author's conference attendance
#
for auth_name in auth_names:
G.add_edge(auth_name, conf_name)
# Note combinations of authors working on same paper
#
for auth_name, other_name in pairs(auth_names):
G.add_edge(auth_name, otherauth_name)
</code></pre>
| 0 | 2009-10-02T16:53:15Z | [
"python",
"parsing",
"xmldom"
] |
Follow-up on iterating over a graph using XML minidom | 1,510,447 | <p>This is a follow-up to the question (<a href="http://stackoverflow.com/questions/1412004/reading-xml-using-python-minidom-and-iterating-over-each-node">Link</a>)</p>
<p>What I intend on doing is using the XML to create a graph using NetworkX. Looking at the DOM structure below, all nodes within the same node should have an edge between them, and all nodes that have attended the same conference should have a node to that conference. To summarize, all authors that worked together on a paper should be connected to each other, and all authors who have attended a particular conference should be connected to that conference. </p>
<pre><code><conference name="CONF 2009">
<paper>
<author>Yih-Chun Hu(UIUC)</author>
<author>David McGrew(Cisco Systems)</author>
<author>Adrian Perrig(CMU)</author>
<author>Brian Weis(Cisco Systems)</author>
<author>Dan Wendlandt(CMU)</author>
</paper>
<paper>
<author>Dan Wendlandt(CMU)</author>
<author>Ioannis Avramopoulos(Princeton)</author>
<author>David G. Andersen(CMU)</author>
<author>Jennifer Rexford(Princeton)</author>
</paper>
</conference>
</code></pre>
<p>I've figured out how to connect authors to conferences, but I'm unsure about how to connect authors to each other. The thing that I'm having difficulty with is how to iterate over the authors that have worked on the same paper and connect them together. </p>
<pre><code> dom = parse(filepath)
conference=dom.getElementsByTagName('conference')
for node in conference:
conf_name=node.getAttribute('name')
print conf_name
G.add_node(conf_name)
#The nodeValue is split in order to get the name of the author
#and to exclude the university they are part of
plist=node.getElementsByTagName('paper')
for p in plist:
author=str(p.childNodes[0].nodeValue)
author= author.split("(")
#Figure out a way to create edges between authors in the same <paper> </paper>
alist=node.getElementsByTagName('author')
for a in alist:
authortext= str(a.childNodes[0].nodeValue).split("(")
if authortext[0] in dict:
edgeQuantity=dict[authortext[0]]
edgeQuantity+=1
dict[authortext[0]]=edgeQuantity
G.add_edge(authortext[0],conf_name)
#Otherwise, add it to the dictionary and create an edge to the conference.
else:
dict[authortext[0]]= 1
G.add_node(authortext[0])
G.add_edge(authortext[0],conf_name)
i+=1
</code></pre>
| 0 | 2009-10-02T16:00:12Z | 1,510,732 | <p>im not entirely sure what you're looking for, but based on your description i threw together a graph which I think encapsulates the relationships you describe.</p>
<p><a href="http://imgur.com/o2HvT.png" rel="nofollow">http://imgur.com/o2HvT.png</a></p>
<p>i used openfst to do this. i find it much easier to clearly layout the graphical relationships before plunging into the code for something like this.</p>
<p>also, do you actually need to generate an explicit edge between authors? this seems like a traversal issue.</p>
| 0 | 2009-10-02T16:59:43Z | [
"python",
"parsing",
"xmldom"
] |
How to make this Python program compile? | 1,510,609 | <p>I have this Python code:</p>
<pre><code>import re
s = "aa67bc54c9"
for t, n in re.findall(r"([a-z]+)([0-9]+)", s)
</code></pre>
<p>And I get this error message when I try to run it: </p>
<pre><code> File "<stdin>", line 1
for t, n in re.findall(r"([a-z]+)([0-9]+)", s)
^
SyntaxError: invalid syntax
</code></pre>
<p>How can I solve this? I am new to Python.</p>
| 4 | 2009-10-02T16:28:09Z | 1,510,616 | <p>You need a colon (<code>:</code>) on the end of the line.</p>
<p>And after that line, you will need an indented statement(s) of what to actually <em>do</em> in the loop. If you don't want to do anything in the loop (perhaps until you get more code written) you can use the statement <code>pass</code> to indicate basically a no-op.</p>
<p>In Python, you need a colon at the end of </p>
<ul>
<li>for statements</li>
<li>while statements</li>
<li>if/elif/else statements</li>
<li>try/except statements</li>
<li>class statements</li>
<li>def (function) statements</li>
</ul>
| 4 | 2009-10-02T16:29:15Z | [
"python",
"syntax-error"
] |
How to make this Python program compile? | 1,510,609 | <p>I have this Python code:</p>
<pre><code>import re
s = "aa67bc54c9"
for t, n in re.findall(r"([a-z]+)([0-9]+)", s)
</code></pre>
<p>And I get this error message when I try to run it: </p>
<pre><code> File "<stdin>", line 1
for t, n in re.findall(r"([a-z]+)([0-9]+)", s)
^
SyntaxError: invalid syntax
</code></pre>
<p>How can I solve this? I am new to Python.</p>
| 4 | 2009-10-02T16:28:09Z | 1,510,617 | <p><code>for</code> starts a loop, so you need to end the line with a <code>:</code>, and put the loop body, indented, on the following lines.</p>
<p>EDIT:</p>
<p>For further information I suggest you go to the <a href="http://docs.python.org/reference/compound%5Fstmts.html#the-for-statement" rel="nofollow">main documentation</a>.</p>
| 7 | 2009-10-02T16:29:34Z | [
"python",
"syntax-error"
] |
Retrieving tags for a specific queryset with django-tagging | 1,510,936 | <p>I'm using django-tagging, and am trying to retrieve a list of tags for a specific queryset. Here's what I've got:</p>
<pre><code>tag = Tag.objects.get(name='tag_name')
queryset = TaggedItem.objects.get_by_model(Article, tag)
tags = Tag.objects.usage_for_queryset(queryset, counts=True)
</code></pre>
<p>"queryset" appropriately returns a number of articles that have been tagged with the tag 'tag_name', but when I attempt to retrieve all of the tags for that queryset, "tags" returns a complete list of all tags for that model.</p>
<p>Anyone else run into this before, or is this a bug in django-tagging?</p>
| 2 | 2009-10-02T17:43:33Z | 1,511,015 | <p>This appears to be a bug in django-tagging. A patch has been written, but it has not yet been committed to trunk. Find the patch here:</p>
<p><a href="http://code.google.com/p/django-tagging/issues/detail?id=44" rel="nofollow">http://code.google.com/p/django-tagging/issues/detail?id=44</a></p>
| 1 | 2009-10-02T18:04:49Z | [
"python",
"django",
"django-tagging"
] |
Venn Diagram from a list of sentences | 1,510,972 | <p>I have a list of many sentences in Excel on each row in a column. I have like 3 or more columns with such sentences. There are some common sentences in these. Is it possible to create a script to create a Venn diagram and get the common ones between all. </p>
<p>Example: These are sentences in a column. Similarly there are different columns. </p>
<p>Blood lymphocytes from cancer </p>
<p>Blood lymphocytes from patients </p>
<p>Ovarian tumor_Grade III </p>
<p>Peritoneum tumor_Grade IV </p>
<p>Hormone resistant PCA </p>
<p>Is it possible to write a script in python?</p>
| 0 | 2009-10-02T17:56:22Z | 1,511,003 | <p>Your question is not fully clear, so I might be misunderstanding what you're looking for.</p>
<p>A Venn diagram is just a few simple Set operations. Python has this stuff built into the <a href="http://docs.python.org/tutorial/datastructures.html#sets" rel="nofollow">Set</a> datatype. Basically, take your two groups of items and use set operations (e.g. use <code>intersection</code> to find the common items).</p>
<p>To read in the data, your best bet is probably to save the file in CSV format and just parse it with the string <code>split</code> method.</p>
| 0 | 2009-10-02T18:02:58Z | [
"python",
"venn-diagram"
] |
Venn Diagram from a list of sentences | 1,510,972 | <p>I have a list of many sentences in Excel on each row in a column. I have like 3 or more columns with such sentences. There are some common sentences in these. Is it possible to create a script to create a Venn diagram and get the common ones between all. </p>
<p>Example: These are sentences in a column. Similarly there are different columns. </p>
<p>Blood lymphocytes from cancer </p>
<p>Blood lymphocytes from patients </p>
<p>Ovarian tumor_Grade III </p>
<p>Peritoneum tumor_Grade IV </p>
<p>Hormone resistant PCA </p>
<p>Is it possible to write a script in python?</p>
| 0 | 2009-10-02T17:56:22Z | 1,511,183 | <p>This is my interpretation of the question...</p>
<p>Give the data file z.csv (export your data from excel into a csv file)</p>
<pre><code>"Blood lymphocytes from cancer","Blood lymphocytes from sausages","Ovarian tumor_Grade III"
"Blood lymphocytes from patients","Ovarian tumor_Grade III","Peritoneum tumor_Grade IV"
"Ovarian tumor_Grade III","Peritoneum tumor_Grade IV","Hormone resistant PCA"
"Peritoneum tumor_Grade XV","Hormone resistant PCA","Blood lymphocytes from cancer"
"Hormone resistant PCA",,"Blood lymphocytes from patients"
</code></pre>
<p>This program finds the sentences common to all the columns</p>
<pre><code>import csv
# Open the csv file
rows = csv.reader(open("z.csv"))
# A list of 3 sets of sentences
results = [set(), set(), set()]
# Read the csv file into the 3 sets
for row in rows:
for i, data in enumerate(row):
results[i].add(data)
# Work out the sentences common to all rows
intersection = results[0]
for result in results[1:]:
intersection = intersection.intersection(result)
print "Common to all rows :-"
for data in intersection:
print data
</code></pre>
<p>And it prints this answer</p>
<pre><code>Common to all rows :-
Hormone resistant PCA
Ovarian tumor_Grade III
</code></pre>
<p>Not 100% sure that is what you are looking for but hopefully it gets you started!</p>
<p>It could be generalised easily to as many columns as you like, but I didn't want to make it more complicated</p>
| 2 | 2009-10-02T18:43:34Z | [
"python",
"venn-diagram"
] |
Can Django/Javascript handle conditional "Ajax" responses to HTTP POST requests? | 1,511,049 | <p>How do I design a Django/Javascript application to provide for conditional Ajax responses to conventional HTTP requests?</p>
<p>On the server, I have a custom-built Form object. When the browser POSTS the form's data, the server checks the submitted data against existing data and rules (eg, if the form adds some entity to a database, does that entity already exist in the database?). If the data passes, the server saves, generates an ID number and adds it to the form's data, and passes the form and data back to the browser. </p>
<pre><code>if request.method == 'POST':
formClass = form_code.getCustomForm()
thisForm = formClass(data=request.POST)
if thisForm.isvalid():
saveCheck = thisForm.saveData()
t = loader.get_template("CustomerForm.html")
c = Context({ 'expectedFormObj': thisForm })
</code></pre>
<p>(Note that my custom logic checking is in saveData() and is separate from the html validation done by isvalid().)</p>
<p>So far, standard Django (I hope). But if the data doesn't pass, I want to send a message to the browser. I suppose saveData() could put the message in an attribute of the form, and the template could check for that attribute, embed its data as javascript variable and include a javascript function to display the message. But passing all that form html back, just to add one message, seems inelegant (as does the standard Django form submission process, but never mind). In that case I'd like to just pass back the message.</p>
<p>Now I suppose I could tie a Javascript function to the html form's onsubmit event, and have that issue an XMLHttpRequest, and have the server respond to that based on the output of the saveData() call. But then the browser has two requests to the server outstanding (POST and XHR). Maybe a successful saveData() would rewrite the whole page and erase any potential for conflict. But I'd also have to get the server to sequence its response to the XHR to follow the response to the POST, and figure out how to communicate the saveData outcome to the response to the XHR. I suppose that is doable, even without the thread programming I don't know, but it seems messy.</p>
<p>I speculate that I might use javascript to make the browser's response conditional to something in the response to the POST request (either rewrite the whole page, or just display a message). But I suspect that the page's javascript hands control over the browser with the POST request, and that any response to the POST would just rewrite the page.</p>
<p>So can I design a process to pass back the whole form only if the server-side saveData() works, and a message that is displayed without rewriting the entire form if saveData() doesn't? If so, how?</p>
| 0 | 2009-10-02T18:11:49Z | 1,511,068 | <p>FYI, this isn't an answer...but it might help you think about it a different way</p>
<p>Here's the problem I'm running into...<a href="http://stackoverflow.com/questions/1292111/google-app-engine-jquery-ajax-405-method-not-allowed">http://stackoverflow.com/questions/1292111/google-app-engine-jquery-ajax-405-method-not-allowed</a>.</p>
<p>So basically I get the thing to work using the outlined code, then I can't make the AJAX request :(. </p>
| 0 | 2009-10-02T18:17:00Z | [
"javascript",
"python",
"ajax",
"django"
] |
Can Django/Javascript handle conditional "Ajax" responses to HTTP POST requests? | 1,511,049 | <p>How do I design a Django/Javascript application to provide for conditional Ajax responses to conventional HTTP requests?</p>
<p>On the server, I have a custom-built Form object. When the browser POSTS the form's data, the server checks the submitted data against existing data and rules (eg, if the form adds some entity to a database, does that entity already exist in the database?). If the data passes, the server saves, generates an ID number and adds it to the form's data, and passes the form and data back to the browser. </p>
<pre><code>if request.method == 'POST':
formClass = form_code.getCustomForm()
thisForm = formClass(data=request.POST)
if thisForm.isvalid():
saveCheck = thisForm.saveData()
t = loader.get_template("CustomerForm.html")
c = Context({ 'expectedFormObj': thisForm })
</code></pre>
<p>(Note that my custom logic checking is in saveData() and is separate from the html validation done by isvalid().)</p>
<p>So far, standard Django (I hope). But if the data doesn't pass, I want to send a message to the browser. I suppose saveData() could put the message in an attribute of the form, and the template could check for that attribute, embed its data as javascript variable and include a javascript function to display the message. But passing all that form html back, just to add one message, seems inelegant (as does the standard Django form submission process, but never mind). In that case I'd like to just pass back the message.</p>
<p>Now I suppose I could tie a Javascript function to the html form's onsubmit event, and have that issue an XMLHttpRequest, and have the server respond to that based on the output of the saveData() call. But then the browser has two requests to the server outstanding (POST and XHR). Maybe a successful saveData() would rewrite the whole page and erase any potential for conflict. But I'd also have to get the server to sequence its response to the XHR to follow the response to the POST, and figure out how to communicate the saveData outcome to the response to the XHR. I suppose that is doable, even without the thread programming I don't know, but it seems messy.</p>
<p>I speculate that I might use javascript to make the browser's response conditional to something in the response to the POST request (either rewrite the whole page, or just display a message). But I suspect that the page's javascript hands control over the browser with the POST request, and that any response to the POST would just rewrite the page.</p>
<p>So can I design a process to pass back the whole form only if the server-side saveData() works, and a message that is displayed without rewriting the entire form if saveData() doesn't? If so, how?</p>
| 0 | 2009-10-02T18:11:49Z | 1,511,097 | <p>Although you can arrange for your views to examine the request data to decide if the response should be an AJAXish or plain HTML, I don't really recommend it. Put AJAX request handlers in a separate URL structure, for instance all your regular html views have urls like /foo/bar and a corresponding api call for the same info would be /ajax/foo/bar.</p>
<p>Since most views will examine the request data, then do some processing, then create a python dictionary and pass that to the template engine, you can factor out the common parts to make this a little easier. the first few steps could be a generic sort of function that just returns the python dictionary, and then actual responses are composed by wrapping the handler functions in a template renderer or json encoder.</p>
<p>My usual workflow is to initially assume that the client has no javascript, (which is still a valid assumption; many mobile browsers have no JS) and implement the app as static <code>GET</code> and <code>POST</code> handlers. From there I start looking for the places where my app can benefit from a little client side scripting. For instance I'll usually redesign the forms to submit via AJAX type calls without reloading a page. These will not send their requests to the same URL/django view as the plain html form version would, since the response needs to be a simple success message in plain text or html fragment. </p>
<p>Similarly, getting data from the server is also redesigned to respond with a concise JSoN document to be processed into the page on the client. This also would be a separate URL/django view as the corresponding plain html for that resource.</p>
| 3 | 2009-10-02T18:23:09Z | [
"javascript",
"python",
"ajax",
"django"
] |
Can Django/Javascript handle conditional "Ajax" responses to HTTP POST requests? | 1,511,049 | <p>How do I design a Django/Javascript application to provide for conditional Ajax responses to conventional HTTP requests?</p>
<p>On the server, I have a custom-built Form object. When the browser POSTS the form's data, the server checks the submitted data against existing data and rules (eg, if the form adds some entity to a database, does that entity already exist in the database?). If the data passes, the server saves, generates an ID number and adds it to the form's data, and passes the form and data back to the browser. </p>
<pre><code>if request.method == 'POST':
formClass = form_code.getCustomForm()
thisForm = formClass(data=request.POST)
if thisForm.isvalid():
saveCheck = thisForm.saveData()
t = loader.get_template("CustomerForm.html")
c = Context({ 'expectedFormObj': thisForm })
</code></pre>
<p>(Note that my custom logic checking is in saveData() and is separate from the html validation done by isvalid().)</p>
<p>So far, standard Django (I hope). But if the data doesn't pass, I want to send a message to the browser. I suppose saveData() could put the message in an attribute of the form, and the template could check for that attribute, embed its data as javascript variable and include a javascript function to display the message. But passing all that form html back, just to add one message, seems inelegant (as does the standard Django form submission process, but never mind). In that case I'd like to just pass back the message.</p>
<p>Now I suppose I could tie a Javascript function to the html form's onsubmit event, and have that issue an XMLHttpRequest, and have the server respond to that based on the output of the saveData() call. But then the browser has two requests to the server outstanding (POST and XHR). Maybe a successful saveData() would rewrite the whole page and erase any potential for conflict. But I'd also have to get the server to sequence its response to the XHR to follow the response to the POST, and figure out how to communicate the saveData outcome to the response to the XHR. I suppose that is doable, even without the thread programming I don't know, but it seems messy.</p>
<p>I speculate that I might use javascript to make the browser's response conditional to something in the response to the POST request (either rewrite the whole page, or just display a message). But I suspect that the page's javascript hands control over the browser with the POST request, and that any response to the POST would just rewrite the page.</p>
<p>So can I design a process to pass back the whole form only if the server-side saveData() works, and a message that is displayed without rewriting the entire form if saveData() doesn't? If so, how?</p>
| 0 | 2009-10-02T18:11:49Z | 1,511,125 | <p>When dealing with AJAX, I use this:</p>
<pre><code>from django.utils import simplejson
...
status = simplejson.dumps({'status': "success"})
return HttpResponse(status, mimetype="application/json")
</code></pre>
<p>Then, AJAX (jQuery) can do what it wants based on the return value of 'status'.</p>
<p>I'm not sure exactly what you want with regards to forms. If you want an easier, and better form experience, I suggest checking out <a href="http://sprawsm.com/uni-form/" rel="nofollow">uni-form</a>. <a href="http://pinaxproject.com" rel="nofollow">Pinax</a> has a good implementation of this in their voting app.</p>
| 3 | 2009-10-02T18:29:59Z | [
"javascript",
"python",
"ajax",
"django"
] |
Django: How to access originating instance from a RelatedManager? | 1,511,256 | <p>I would like to access the <code>Foo</code> instance <code>foo</code> within my manager method <code>baz</code>:</p>
<pre><code>foo.bar_set.baz()
</code></pre>
<p><code>baz</code> would normally take an argument of <code>Foo</code> type:</p>
<pre><code>BarManager(models.Manager):
def baz(self, foo=None):
if foo is None:
# assume this call originates from
# a RelatedManager and set `foo`.
# Otherwise raise an exception
# do something cool with foo
</code></pre>
<p>This way both the first query above and the following one works identically:</p>
<pre><code>Bar.objects.baz(foo)
</code></pre>
<p><code>Bar</code> would have a ForeignKey to <code>Foo</code>:</p>
<pre><code>class Bar(models.Model):
foo = models.ForeignKey(Foo)
objects = BarManager()
</code></pre>
| 0 | 2009-10-02T18:56:34Z | 1,511,280 | <p>If I'm understanding what you want correctly, you need to do this:</p>
<pre><code> BarManager(models.Manager):
use_for_related_fields = True
</code></pre>
<p><strong>Edit:</strong> apparently I managed to miss the point completely. You can use something like this (maybe a bit too "magic" for my taste, but oh well):</p>
<pre><code>class BarManager(models.Manager):
use_for_related_fields = True
def bar(self, foo=None):
if foo == None:
qs = Foo.objects.all()
for field_name, field_val in self.core_filters.items():
field_name = field_name.split('__')[1]
qs = qs.filter(**{ field_name: field_val })
foo = qs.get()
# do k00l stuff with foo
</code></pre>
| 1 | 2009-10-02T19:06:10Z | [
"python",
"django",
"django-models",
"django-orm"
] |
Using lambda for a constraint function | 1,511,354 | <pre><code>import numpy
from numpy import asarray
Initial = numpy.asarray [2.0, 4.0, 5.0, 3.0, 5.0, 6.0] # Initial values to start with
bounds = [(1, 5000), (1, 6000), (2, 100000), (1, 50000), (1.0, 5000), (2, 1000000)]
# actual passed bounds
b1 = lambda x: numpy.asarray([1.4*x[0] - x[0]])
b2 = lambda x: numpy.asarray([1.4*x[1] - x[1]])
b3 = lambda x: numpy.asarray([x[2] - x[3]])
constraints = numpy.asarray([b1, b2, b3])
opt= optimize.fmin_slsqp(func,Initial,ieqcons=constraints,bounds=bounds, full_output=True,iter=200,iprint=2, acc=0.01)
</code></pre>
<p><strong>Problem:</strong>
I want to pass in inequality constraints. Consider that I have 6 parameters</p>
<pre><code>[ a, b, c, d, e, f]
</code></pre>
<p>in the <code>Initial</code> values, and my constraints are:</p>
<pre><code>a<=e<=1.4*a ('e' varies from a to 1.4*a)
b<=f<=1.4*b ('f' varies from b to 1.4*b)
c>d ('c' must always be greater than d)
</code></pre>
<p>But this is not working properly. I don't know what the mistake is.
Is there any better way to pass my constraints as a function?
Please help me.</p>
| 1 | 2009-10-02T19:25:08Z | 1,511,564 | <p>Based on the comment from Robert Kern, I have removed my previous answer. Here are the constraints as continuous functions:</p>
<pre><code>b1 = lambda x: x[4]-x[0] if x[4]<1.2*x[0] else 1.4*x[0]-x[4]
b2 = lambda x: x[5]-x[1] if x[5]<1.2*x[1] else 1.4*x[1]-x[5]
b3 = lambda x: x[2]-x[3]
</code></pre>
<p>Note: Python 2.5 or greater is required for this syntax.<sup>1</sup></p>
<p>To get the constraint <code>a<=e<=1.4*a</code>, note that <code>1.2*a</code> is the halfway point between <code>a</code> and <code>1.4*a</code>.</p>
<p>Below this point, that is, all <code>e<1.2*a</code>, we use the continuous function <code>e-a</code>. Thus the overall constraint function is negative when <code>e<a</code>, handling the lower out-of-bounds condition, zero on the lower boundary <code>e==a</code>, and then positive for <code>e>a</code> up to the halfway point.</p>
<p>Above the halfway point, that is, all <code>e>1.2*a</code>, we use instead the continuous function <code>1.4*a-e</code>. This means the overall constraint function is is negative when <code>e>1.4*a</code>, handling the upper out-of-bounds condition, zero on the upper boundary <code>e==1.4*a</code>, and then positive when <code>e<1.4*a</code>, down to the halfway point.</p>
<p>At the halfway point, where <code>e==1.2*a</code>, both functions have the same value. This means that the overall function is continuous.</p>
<p>Reference: <a href="http://projects.scipy.org/scipy/attachment/ticket/565/slsqp.py" rel="nofollow">documentation for <code>ieqcons</code></a>.</p>
<p><sup><strong>1</strong> - Here is pre-Python 2.5 syntax: <code>b1 = lambda x: (1.4*x[0]-x[4], x[4]-x[0])[x[4]<1.2*x[0]]</code></sup></p>
| 1 | 2009-10-02T20:10:46Z | [
"python",
"lambda",
"numpy",
"scipy"
] |
Queue for producers and consumers in a tree | 1,511,359 | <p>I am reading up on how to utilize Python Queues to send and receive short messages between nodes. I am simulating a set of nodes that are in a nice tree structure. I want some of these nodes to send a fixed-size data to its parent. Once this parent receives data from some of its child-nodes, it will "process" it and send a "aggregate" packet to <em>its</em> parent...and so on.</p>
<p>To do this, I was told that queues would be useful to pass messages and a quick readup on it tells me that it will suit my needs. However, I am finding it a bit difficult to implement a basic setup and test my understanding -- 1 producer (that generates a message packet) and 1 consumer (the worker thread that dequeues the task and processes it).</p>
<p>I have searched and read many posts here and elsewhere...and I understand all the queue methods. What I still do not understand is how to associate or bind a queue to 2 given nodes. </p>
<p>I want node-1 and node-2 to send messages to node-3. For this basic scenario, I have to somehow create one (or 2) queues and "associate" it with node-1 and node-2 which uses it to place messages into and node-3. And, node-3 must also be "listening"/"associated" with this queue to "get" or dequeue a task.</p>
<p>If node-1 and node-2 are to be 'producers', I should have them as 2 separate threads and node-3 being the 3rd thread. Then, I must create one queue Q. Then, I should have node-1 and node-2 create messages, 'put' them into the queue. Node-3 will have to be 'somehow' notified /waken-up to 'get' these messages from Q and process it.</p>
<p>I have seen </p>
<p><a href="http://docs.python.org/library/queue.html#module-Queue" rel="nofollow">http://docs.python.org/library/queue.html#module-Queue</a></p>
<p>Here is the (untested) code I have so far:</p>
<p>=================================================================</p>
<pre><code>import threading
import queue
q = Queue.Queue(2) # create a queue of size 2.
# worker is node-3 which received msgs from 1 and 2 and fuses them.
def worker():
while True:
msg = q.get()
fuse_msgs(msg)
q.task_done()
# generate 3 worker threads. Node-3 could be both a producer and consumer. Each
# thread represents each node that will be a potential producer/consumer or both.
# need something like t1 - thread-1 for node-1 ...
for i in range(3):
t = Thread(target=worker)
t.setDaemon(True)
t.start()
# How can I make node-1 and node-2 to put items into a specified queue???
for msg in source():
q.put(item)
q.join()
</code></pre>
<p>=========================================</p>
<p>Am I going in the right direction? Please let me know where I am wrong and what I am misunderstanding...</p>
<p>Any help is appreciated. I have hundreds of nodes and links. If I get this fundamentals straight, I will be able to move on smoothly...</p>
<p>Thanks,
B.R.Srini.</p>
| 1 | 2009-10-02T19:26:17Z | 1,511,556 | <p>I'm not commenting on the python code in particular, but as far as your queues are designed, it seems you just need one queue in the node 1,2,3 scenario you were describing. Basically, you have one queue, where you have node 1 and node 2 putting messages to, and node 3 reading from.</p>
<p>You should be able to tell node-3 to do a "blocking" get on the queue, so it will just wait until it sees a message for it to process, and leave nodes 1 and 2 to produce their output as fast as possible.</p>
<p>Depending on the processing speed of each node, and the traffic patterns you expect, you will probably want a queue deeper than 2 messages, so that the producing nodes don't have to wait for the queue to be drained.</p>
| 1 | 2009-10-02T20:09:06Z | [
"python",
"queue"
] |
py2exe and the file system | 1,511,461 | <p>I have a Python app. It loads config files (and various other files) by
doing stuff such as:</p>
<pre><code>_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CONFIG_DIR = os.path.join(_path, 'conf')
</code></pre>
<p>This works fine. However, when I package the app with py2exe, bad things happen:</p>
<pre><code> File "proj\config.pyc", line 8, in <module>
WindowsError: [Error 3] The system cannot find the path specified: 'C:\\proj\
\dist\\library.zip\\conf'
</code></pre>
<p>Obviously that's an invalid path... What's a more robust way of doing this? I don't
want to specify absolute paths in the program because it could be placed in different
folders. Should I just say "if it says the folder name is 'library.zip', then go
one more level down to the 'dist' folder"?</p>
<p>Note that I have pretty nested directory hierarchies... for example, I have
a module gui.utils.images, stored in "gui/utils/images.py", and it uses its path
to access "gui/images/ok.png", for example. Right now the py2exe version
would try to access "proj/dist/library.zip/gui/images/ok.png", or something,
which just won't work. </p>
| 3 | 2009-10-02T19:49:55Z | 1,511,555 | <p>What do you think about using relative paths for all of the included files? I guess it should be possible to use <code>sys.path.append(".." + os.path.sep + "images")</code> for your example about ok.png, then you could just <code>open("ok.png", "rb")</code>. Using relative paths should fix the issues with the library.zip file that's generated by py2exe, at least that's what it does for me.</p>
| 2 | 2009-10-02T20:08:48Z | [
"python",
"configuration",
"file",
"py2exe"
] |
py2exe and the file system | 1,511,461 | <p>I have a Python app. It loads config files (and various other files) by
doing stuff such as:</p>
<pre><code>_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CONFIG_DIR = os.path.join(_path, 'conf')
</code></pre>
<p>This works fine. However, when I package the app with py2exe, bad things happen:</p>
<pre><code> File "proj\config.pyc", line 8, in <module>
WindowsError: [Error 3] The system cannot find the path specified: 'C:\\proj\
\dist\\library.zip\\conf'
</code></pre>
<p>Obviously that's an invalid path... What's a more robust way of doing this? I don't
want to specify absolute paths in the program because it could be placed in different
folders. Should I just say "if it says the folder name is 'library.zip', then go
one more level down to the 'dist' folder"?</p>
<p>Note that I have pretty nested directory hierarchies... for example, I have
a module gui.utils.images, stored in "gui/utils/images.py", and it uses its path
to access "gui/images/ok.png", for example. Right now the py2exe version
would try to access "proj/dist/library.zip/gui/images/ok.png", or something,
which just won't work. </p>
| 3 | 2009-10-02T19:49:55Z | 1,844,634 | <p>The usual approach to doing this sort of thing (if I understand properly) is this:</p>
<ol>
<li>check sys.frozen, which py2exe contrives to set, using something like getattr(sys, 'frozen', '')</li>
<li>if that's not set, use the usual method since you're running from source</li>
<li>if it's set, check sys.executable since that will point you to where the .exe is (instead of to where python.exe is, which is what it normally points to). Use something like os.path.dirname(sys.executable) and then join that with your relative paths to find subfolders etc</li>
</ol>
<p>Example:</p>
<pre><code>frozen = getattr(sys, 'frozen', '')
if not frozen:
# not frozen: in regular python interpreter
approot = os.path.dirname(__file__)
elif frozen in ('dll', 'console_exe', 'windows_exe'):
# py2exe:
approot = os.path.dirname(sys.executable)
elif frozen in ('macosx_app',):
# py2app:
# Notes on how to find stuff on MAC, by an expert (Bob Ippolito):
# http://mail.python.org/pipermail/pythonmac-sig/2004-November/012121.html
approot = os.environ['RESOURCEPATH']
</code></pre>
<p>Or some variant thereof... the latter one handles the use of py2app. You could extend this for other builders, if needed.</p>
| 10 | 2009-12-04T03:20:38Z | [
"python",
"configuration",
"file",
"py2exe"
] |
py2exe and the file system | 1,511,461 | <p>I have a Python app. It loads config files (and various other files) by
doing stuff such as:</p>
<pre><code>_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CONFIG_DIR = os.path.join(_path, 'conf')
</code></pre>
<p>This works fine. However, when I package the app with py2exe, bad things happen:</p>
<pre><code> File "proj\config.pyc", line 8, in <module>
WindowsError: [Error 3] The system cannot find the path specified: 'C:\\proj\
\dist\\library.zip\\conf'
</code></pre>
<p>Obviously that's an invalid path... What's a more robust way of doing this? I don't
want to specify absolute paths in the program because it could be placed in different
folders. Should I just say "if it says the folder name is 'library.zip', then go
one more level down to the 'dist' folder"?</p>
<p>Note that I have pretty nested directory hierarchies... for example, I have
a module gui.utils.images, stored in "gui/utils/images.py", and it uses its path
to access "gui/images/ok.png", for example. Right now the py2exe version
would try to access "proj/dist/library.zip/gui/images/ok.png", or something,
which just won't work. </p>
| 3 | 2009-10-02T19:49:55Z | 2,859,959 | <p>Use os.path.dirname(os.path.abspath(sys.argv[0])) from a py2exe app, it'll work the same way from the python script (so you can test without creating the exe every time) and from the exe.</p>
<p>This can be much better than using relative paths because you don't have to worry about where your app (.py or .exe) is running from.</p>
| 2 | 2010-05-18T18:32:24Z | [
"python",
"configuration",
"file",
"py2exe"
] |
py2exe and the file system | 1,511,461 | <p>I have a Python app. It loads config files (and various other files) by
doing stuff such as:</p>
<pre><code>_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CONFIG_DIR = os.path.join(_path, 'conf')
</code></pre>
<p>This works fine. However, when I package the app with py2exe, bad things happen:</p>
<pre><code> File "proj\config.pyc", line 8, in <module>
WindowsError: [Error 3] The system cannot find the path specified: 'C:\\proj\
\dist\\library.zip\\conf'
</code></pre>
<p>Obviously that's an invalid path... What's a more robust way of doing this? I don't
want to specify absolute paths in the program because it could be placed in different
folders. Should I just say "if it says the folder name is 'library.zip', then go
one more level down to the 'dist' folder"?</p>
<p>Note that I have pretty nested directory hierarchies... for example, I have
a module gui.utils.images, stored in "gui/utils/images.py", and it uses its path
to access "gui/images/ok.png", for example. Right now the py2exe version
would try to access "proj/dist/library.zip/gui/images/ok.png", or something,
which just won't work. </p>
| 3 | 2009-10-02T19:49:55Z | 10,162,341 | <p>Here's my solution (tested on Windows, Linux and Mac). It also works if the application or Python script is started via a symbolic link.</p>
<pre><code># Get if frozen
is_frozen = bool( getattr(sys, 'frozen', None) )
# Get path variable
path = sys.path if is_frozen else sys.argv
# Get nonempty first element or raise error
if path and path[0]:
apppath = path[0]
elif is_frozen():
raise RuntimeError('Cannot determine app path because sys.path[0] is empty.')
else:
raise RuntimeError('Cannot determine app path in interpreter mode.')
# Make absolute (eliminate symbolic links)
apppath = os.path.abspath( os.path.realpath(apppath) )
# Split and return
appdir, appname = os.path.split(apppath)
</code></pre>
| 2 | 2012-04-15T13:12:55Z | [
"python",
"configuration",
"file",
"py2exe"
] |
py2exe and the file system | 1,511,461 | <p>I have a Python app. It loads config files (and various other files) by
doing stuff such as:</p>
<pre><code>_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CONFIG_DIR = os.path.join(_path, 'conf')
</code></pre>
<p>This works fine. However, when I package the app with py2exe, bad things happen:</p>
<pre><code> File "proj\config.pyc", line 8, in <module>
WindowsError: [Error 3] The system cannot find the path specified: 'C:\\proj\
\dist\\library.zip\\conf'
</code></pre>
<p>Obviously that's an invalid path... What's a more robust way of doing this? I don't
want to specify absolute paths in the program because it could be placed in different
folders. Should I just say "if it says the folder name is 'library.zip', then go
one more level down to the 'dist' folder"?</p>
<p>Note that I have pretty nested directory hierarchies... for example, I have
a module gui.utils.images, stored in "gui/utils/images.py", and it uses its path
to access "gui/images/ok.png", for example. Right now the py2exe version
would try to access "proj/dist/library.zip/gui/images/ok.png", or something,
which just won't work. </p>
| 3 | 2009-10-02T19:49:55Z | 25,517,547 | <p>I use the following trick in windows.<br>
When the program is frozen in a py2exe 'executable' (i.e <strong>my_application.exe</strong>), <code>dirname(__file__)</code> returns the folder where your main python script is running.
Oddly enough, that folder is not the folder containing <strong>my_application.exe</strong> but <strong>my_application.exe</strong> itself.<br>
Note that <strong>my_application.exe</strong> is not a binary file but a compressed folder (you can unzip it) that contains python libs and your compiled scripts.<br>
That's why the <code>os.path.dirname</code> of your <code>__file__</code> is in fact <strong>my_application.exe</strong>. </p>
<p>Thus, this code gives you the root directory for your configuration files or images (in case of a frozen application, the folder containing the py2exe executable, otherwise the folder from where your python script is running):</p>
<pre><code>dirname = os.path.dirname(__file__)
if dirname.endswith('.exe'):
dirname = os.path.split(dirname)[0]
</code></pre>
<p>Obviously you can use more general, portable methods to detect if the file is frozen as other answers show instead of the <code>endswith</code> method. </p>
| 0 | 2014-08-27T01:25:49Z | [
"python",
"configuration",
"file",
"py2exe"
] |
Python loop | "do-while" over a tree | 1,511,506 | <p>Is there a more Pythonic way to put this loop together?:</p>
<pre><code>while True:
children = tree.getChildren()
if not children:
break
tree = children[0]
</code></pre>
<p>UPDATE:
I think this syntax is probably what I'm going to go with:</p>
<pre><code>while tree.getChildren():
tree = tree.getChildren()[0]
</code></pre>
| 2 | 2009-10-02T19:57:51Z | 1,511,518 | <pre><code>children = tree.getChildren()
while children:
tree = children[0]
children = tree.getChildren()
</code></pre>
<p>It would be easier to suggest something if I knew what kind of collection api you're working with. In a good api, you could probably do something like</p>
<pre><code>while tree.hasChildren():
children = tree.getChildren()
tree = children[0]
</code></pre>
| 4 | 2009-10-02T20:00:51Z | [
"python"
] |
Python loop | "do-while" over a tree | 1,511,506 | <p>Is there a more Pythonic way to put this loop together?:</p>
<pre><code>while True:
children = tree.getChildren()
if not children:
break
tree = children[0]
</code></pre>
<p>UPDATE:
I think this syntax is probably what I'm going to go with:</p>
<pre><code>while tree.getChildren():
tree = tree.getChildren()[0]
</code></pre>
| 2 | 2009-10-02T19:57:51Z | 1,511,600 | <p>I think the code you have is fine. If you really wanted to, you could wrap it all up in a try/except:</p>
<pre><code>while True:
try:
tree = tree.getChildren()[0]
except (IndexError, TypeError):
break
</code></pre>
<p><code>IndexError</code> will work if <code>getChildren()</code> returns an empty list when there are no children. If it returns <code>False</code> or <code>0</code> or <code>None</code> or some other unsubscriptable false-like value, <code>TypeError</code> will handle the exception.</p>
<p>But that's just <em>another</em> way to do it. Again, I don't think the Pythonistas will hunt you down for the code you already have.</p>
| 0 | 2009-10-02T20:19:21Z | [
"python"
] |
Python loop | "do-while" over a tree | 1,511,506 | <p>Is there a more Pythonic way to put this loop together?:</p>
<pre><code>while True:
children = tree.getChildren()
if not children:
break
tree = children[0]
</code></pre>
<p>UPDATE:
I think this syntax is probably what I'm going to go with:</p>
<pre><code>while tree.getChildren():
tree = tree.getChildren()[0]
</code></pre>
| 2 | 2009-10-02T19:57:51Z | 1,511,605 | <p>Without further testing, I believe this should work:</p>
<pre><code>try: while True: tree=tree.getChildren()[0]
except: pass
</code></pre>
<p>You might also want to override the <code>__getitem__()</code> (the brackets operator) in the <code>Tree</code> class, for further neatification.</p>
<pre><code>try: while True: tree=tree[0]
except: pass
</code></pre>
| 0 | 2009-10-02T20:20:10Z | [
"python"
] |
Python loop | "do-while" over a tree | 1,511,506 | <p>Is there a more Pythonic way to put this loop together?:</p>
<pre><code>while True:
children = tree.getChildren()
if not children:
break
tree = children[0]
</code></pre>
<p>UPDATE:
I think this syntax is probably what I'm going to go with:</p>
<pre><code>while tree.getChildren():
tree = tree.getChildren()[0]
</code></pre>
| 2 | 2009-10-02T19:57:51Z | 1,511,942 | <p>(My first answer suggested to use <code>iter(tree.getChildren, None)</code> directly, but that won't work as we are not calling the same <code>tree.getChildren</code> function all the time.)</p>
<p>To fix this up I propose a solution using lambda's non-binding of its variables as a possible workaround. I think at this point this solution is not better than any other previously posted:</p>
<p>You can use <a href="http://docs.python.org/library/functions.html#iter" rel="nofollow">iter()</a> in it's second sentinel form, using lamda's strange binding:</p>
<pre><code>for children in iter((lambda : tree.getChildren()), None):
tree = children[0]
</code></pre>
<p>(Here it assumes getChildren() returns <code>None</code> when there are no children, but it has to be replaced with whatever value it returns (<code>[]</code>?).)</p>
<p><code>iter(function, sentinel)</code> calls function repeatedly until it returns the sentinel value.</p>
| 2 | 2009-10-02T21:40:28Z | [
"python"
] |
Python loop | "do-while" over a tree | 1,511,506 | <p>Is there a more Pythonic way to put this loop together?:</p>
<pre><code>while True:
children = tree.getChildren()
if not children:
break
tree = children[0]
</code></pre>
<p>UPDATE:
I think this syntax is probably what I'm going to go with:</p>
<pre><code>while tree.getChildren():
tree = tree.getChildren()[0]
</code></pre>
| 2 | 2009-10-02T19:57:51Z | 1,512,034 | <p>Do you really only want the first branch? I'm gonna assume you don't and that you want the whole tree. First I'd do this:</p>
<pre><code>def allitems(tree):
for child in tree.getChildren():
yield child
for grandchild in allitems(child):
yield grandchild
</code></pre>
<p>This will go through the whole tree. Then you can just:</p>
<pre><code>for item in allitems(tree):
do_whatever_you_want(item)
</code></pre>
<p>Pythonic, simple, clean, and since it uses generators, will not use much memory even for huge trees.</p>
| 1 | 2009-10-02T22:10:18Z | [
"python"
] |
Python distutils - copy_tree with filter | 1,511,808 | <p>I want to copy a data directory into my distribution dir. <code>copy_tree</code> does this just fine. However, the project is also an svn repository, and I don't want the distribution to have all the .svn files that the data dir has. Is there any easy way to do a <code>copy_tree</code> excluding the <code>.svn</code> files, or should I just write my own recursive dir copy? I feel someone must have had this issue before.</p>
| 1 | 2009-10-02T21:13:30Z | 1,511,907 | <p>I just used <code>shutil.copytree</code>, which takes an <code>ignore</code> kwd arg.</p>
| 2 | 2009-10-02T21:32:15Z | [
"python",
"file",
"distribution",
"py2exe",
"distutils"
] |
Parse a cron entry in Python | 1,511,854 | <p>All. I am trying to find a python module that I can use to parse a cron entry and get the next time it will run. With perl I use the Schedule::Cron::Events module but I would like to convert to python. Thanks in advance.</p>
| 4 | 2009-10-02T21:22:56Z | 1,511,891 | <p>Take a look at <a href="http://pypi.python.org/pypi/python-crontab/0.9.2" rel="nofollow">http://pypi.python.org/pypi/python-crontab/0.9.2</a></p>
| 2 | 2009-10-02T21:28:52Z | [
"python",
"module",
"cron"
] |
Parse a cron entry in Python | 1,511,854 | <p>All. I am trying to find a python module that I can use to parse a cron entry and get the next time it will run. With perl I use the Schedule::Cron::Events module but I would like to convert to python. Thanks in advance.</p>
| 4 | 2009-10-02T21:22:56Z | 1,516,146 | <p>The documentation for python-crontab is in <a href="http://en.wikipedia.org/wiki/Docstring#Python" rel="nofollow">docstrings</a> in the source code, as is usual for python. You can also explore the documentation via the python interpreter with the built-in <code>help()</code> function. The full source for python-crontab is less than 500 lines anyway and is very readable.</p>
<p>Example from the source code:</p>
<pre><code>from crontab import CronTab
tab = CronTab()
cron = tab.new(command='/usr/bin/echo')
cron.minute().during(5,50).every(5)
cron.hour().every(4)
cron2 = tab.new(command='/foo/bar',comment='SomeID')
cron2.every_reboot()
list = tab.find('bar')
cron3 = list[0]
cron3.clear()
cron3.minute().every(1)
print unicode(tab.render())
for cron4 in tab.find('echo'):
print cron4
for cron5 in tab:
print cron5
tab.remove_all('echo')
t.write()
</code></pre>
<p><strong>P.S.</strong> Please remember to add comments or edit your question, when appropriate, instead of adding an answer - your 'answer' is not technically an answer.</p>
| 7 | 2009-10-04T10:55:53Z | [
"python",
"module",
"cron"
] |
Parse a cron entry in Python | 1,511,854 | <p>All. I am trying to find a python module that I can use to parse a cron entry and get the next time it will run. With perl I use the Schedule::Cron::Events module but I would like to convert to python. Thanks in advance.</p>
| 4 | 2009-10-02T21:22:56Z | 3,256,325 | <p>I could be wrong but doesn't python crontab offer ways to read and write to crontab but nothing regarding parsing the crontab to determine the time until the next time a job will be run?</p>
| 3 | 2010-07-15T14:10:09Z | [
"python",
"module",
"cron"
] |
py2exe'd version of GTK app can't read png files | 1,511,916 | <p>I'm working on making a py2exe version of my app. Py2exe fails at copying some
modules in. My original app loads <code>.png</code> files fine, but the exe version does not:</p>
<pre><code>Traceback (most recent call last):
File "app.py", line 1, in <module>
from gui.main import run
File "gui\main.pyc", line 14, in <module>
File "gui\controllers.pyc", line 10, in <module>
File "gui\utils\images.pyc", line 78, in <module>
âº
File "gui\utils\images.pyc", line 70, in GTK_get_pixbuf
âºÂ§âºâ²â»
File "gui\utils\images.pyc", line 38, in PIL_to_pixbuf
gobject.GError: Image type 'png' is not supported
</code></pre>
<p>Any idea what I should force py2exe to include?</p>
| 0 | 2009-10-02T21:33:50Z | 1,511,932 | <p>What platform is this?
Lately I think they improved the png support on windows,
so the version of pygtk you're using is pertinent also.
<a href="http://aruiz.typepad.com/siliconisland/2008/02/goodbye-zlib-li.html" rel="nofollow">http://aruiz.typepad.com/siliconisland/2008/02/goodbye-zlib-li.html</a></p>
| 2 | 2009-10-02T21:38:45Z | [
"python",
"image",
"gtk",
"pygtk",
"py2exe"
] |
py2exe'd version of GTK app can't read png files | 1,511,916 | <p>I'm working on making a py2exe version of my app. Py2exe fails at copying some
modules in. My original app loads <code>.png</code> files fine, but the exe version does not:</p>
<pre><code>Traceback (most recent call last):
File "app.py", line 1, in <module>
from gui.main import run
File "gui\main.pyc", line 14, in <module>
File "gui\controllers.pyc", line 10, in <module>
File "gui\utils\images.pyc", line 78, in <module>
âº
File "gui\utils\images.pyc", line 70, in GTK_get_pixbuf
âºÂ§âºâ²â»
File "gui\utils\images.pyc", line 38, in PIL_to_pixbuf
gobject.GError: Image type 'png' is not supported
</code></pre>
<p>Any idea what I should force py2exe to include?</p>
| 0 | 2009-10-02T21:33:50Z | 1,512,020 | <p>This is a known problem with <a href="http://www.pythonware.com/products/pil/" rel="nofollow">PIL</a> and <a href="http://www.py2exe.org/" rel="nofollow">py2exe</a></p>
<p>PIL (python image library) imports its plugins dynamically which py2exe doesn't pick up on, so it doesn't include the plugins in the .exe file.</p>
<p>The fix (hopefully!) is to import the drivers explicitly like this in one of your .py files</p>
<pre><code>import Image
import PngImagePlugin
Image._initialized=2
</code></pre>
<p>That will mean that py2exe will definitely include the plugin. The <code>Image._initialized</code> bit stops PIL scanning for more plugins.</p>
<p><a href="http://www.py2exe.org/index.cgi/py2exeAndPIL" rel="nofollow">Here are the docs</a> from the py2exe wiki explaining this in full</p>
| 4 | 2009-10-02T22:06:56Z | [
"python",
"image",
"gtk",
"pygtk",
"py2exe"
] |
py2exe'd version of GTK app can't read png files | 1,511,916 | <p>I'm working on making a py2exe version of my app. Py2exe fails at copying some
modules in. My original app loads <code>.png</code> files fine, but the exe version does not:</p>
<pre><code>Traceback (most recent call last):
File "app.py", line 1, in <module>
from gui.main import run
File "gui\main.pyc", line 14, in <module>
File "gui\controllers.pyc", line 10, in <module>
File "gui\utils\images.pyc", line 78, in <module>
âº
File "gui\utils\images.pyc", line 70, in GTK_get_pixbuf
âºÂ§âºâ²â»
File "gui\utils\images.pyc", line 38, in PIL_to_pixbuf
gobject.GError: Image type 'png' is not supported
</code></pre>
<p>Any idea what I should force py2exe to include?</p>
| 0 | 2009-10-02T21:33:50Z | 1,579,606 | <p>Make sure you bundle the loaders when you install your application. Py2exe won't know about these, but they are a needed part of GTK, and live where the rest of the GTK "data" files live.</p>
<p>From <a href="http://unpythonic.blogspot.com/2007/07/pygtk-py2exe-and-inno-setup-for-single.html" rel="nofollow">http://unpythonic.blogspot.com/2007/07/pygtk-py2exe-and-inno-setup-for-single.html</a></p>
<blockquote>
<p>It is not sufficient to just make
py2exe pull in the GTK DLLs for
packaging (which it does pretty
successfully). GTK also requires a
number of data files which include
themes, translations etc. These will
need to be manually copied into the
dist directory so that the application
can find them when being run.</p>
<p>If you look inside your GTK runtime
directory (usually something like
c:\GTK) you will find the
directories: share, etc, lib. You will
need to copy all of these into the
dist directory after running py2exe.</p>
</blockquote>
<p>Copyright retained.</p>
| 2 | 2009-10-16T18:24:36Z | [
"python",
"image",
"gtk",
"pygtk",
"py2exe"
] |
Please help me with this program to parse a file into an XML file | 1,511,950 | <p>To parse an input text file and generate a) an XML file and b) an SVG (also XML) file.</p>
<p>The input text file (input.txt) contains the description of a number of produce distribution centers and storage centers around the country. Each line describes either a single distribution center (dcenter) or a storage center, each with a number of properties; each property name (code for example) is separated by its value with a =.</p>
<p>Example (input.txt)</p>
<pre><code>dcenter: code=d1, loc=San Jose, x=100, y=100, ctype=ct1
dcenter: code=d2, loc=San Ramon, x=300, y=200, ctype=ct2
storage: code=s1, locFrom=d1, x=50, y=50, rtype=rt1
storage: code=s2, locFrom=d1, x=-50,y=100, rtype=rt1
</code></pre>
<p>The desired Output of the program:</p>
<p>Output 1</p>
<pre><code><?xml version="1.0"?>
<dcenters>
<dcenter code="d1">
<loc> San Jose </loc>
<x> 100 </x>
<y> 100 </y>
<ctype> ct1 </ctype>
</dcenter>
<storage code="S1">
<locFrom> d1 </locFrom>
<x> 150 </x>
<y> 150 </y>
<rtype> rt1 </rtype>
</storage>
<storage code="S2">
<locFrom> d1 </locFrom>
<x> 50 </x>
<y> 200 </y>
<rtype> rt1 </rtype>
</storage>
</code></pre>
<p>Please help me with the program. I will really appreciate.</p>
| 0 | 2009-10-02T21:42:45Z | 1,511,977 | <p>Suppose the input is in string s; either from direct assignment or from file.read:</p>
<pre><code>s="""dcenter: code=d1, loc=San Jose, x=100, y=100, ctype=ct1
dcenter: code=d2, loc=San Ramon, x=300, y=200, ctype=ct2
storage: code=s1, locFrom=d1, x=50, y=50, rtype=rt1
storage: code=s2, locFrom=d1, x=-50,y=100, rtype=rt1"""
</code></pre>
<p>Then you can this:</p>
<pre><code>print '<?xml version="1.0"?>'
print "<dcenters>"
for line in s.splitlines():
type, fields = line.split(":")
params = fields.split(",")
code = params[0].split("=")[1].strip()
print '<%s code="%s">' % (type, code)
for p in params[1:]:
ptype, pvalue = p.strip().split("=")
print '<%s> %s </%s>' % (ptype, pvalue, ptype)
print '</%s>' % type
print "</dcenters>"
</code></pre>
<p>Not sure why d2 is missing from your sample output; I assume that's by mistake.</p>
| 0 | 2009-10-02T21:54:12Z | [
"python",
"xml",
"fileparsing"
] |
urlopen error 10045, 'address already in use' while downloading in Python 2.5 on Windows | 1,512,057 | <p>I'm writing code that will run on Linux, OS X, and Windows. It downloads a list of approximately 55,000 files from the server, then steps through the list of files, checking if the files are present locally. (With SHA hash verification and a few other goodies.) If the files aren't present locally or the hash doesn't match, it downloads them.</p>
<p>The server-side is plain-vanilla Apache 2 on Ubuntu over port 80.</p>
<p>The client side works perfectly on Mac and Linux, but gives me this error on Windows (XP and Vista) after downloading a number of files:</p>
<pre><code>urllib2.URLError: <urlopen error <10048, 'Address already in use'>>
</code></pre>
<p>This link: <a href="http://bytes.com/topic/python/answers/530949-client-side-tcp-socket-receiving-address-already-use-upon-connect" rel="nofollow">http://bytes.com/topic/python/answers/530949-client-side-tcp-socket-receiving-address-already-use-upon-connect</a> points me to TCP port exhaustion, but "netstat -n" never showed me more than six connections in "TIME_WAIT" status, even just before it errored out.</p>
<p>The code (called once for each of the 55,000 files it downloads) is this:</p>
<pre><code>request = urllib2.Request(file_remote_path)
opener = urllib2.build_opener()
datastream = opener.open(request)
outfileobj = open(temp_file_path, 'wb')
try:
while True:
chunk = datastream.read(CHUNK_SIZE)
if chunk == '':
break
else:
outfileobj.write(chunk)
finally:
outfileobj = outfileobj.close()
datastream.close()
</code></pre>
<p>UPDATE: I find by greping the log that it enters the download routine exactly 3998 times. I've run this multiple times and it fails at 3998 each time. Given that the linked article states that available ports are 5000-1025=3975 (and some are probably expiring and being reused) it's starting to look a lot more like the linked article describes the real issue. However, I'm still not sure how to fix this. Making registry edits is not an option.</p>
| 5 | 2009-10-02T22:15:24Z | 1,512,326 | <p>Thinking outside the box, the problem you seem to be trying to solve has already been solved by a program called rsync. You might look for a Windows implementation and see if it meets your needs.</p>
| 1 | 2009-10-02T23:44:41Z | [
"python",
"windows",
"http",
"download",
"urllib2"
] |
urlopen error 10045, 'address already in use' while downloading in Python 2.5 on Windows | 1,512,057 | <p>I'm writing code that will run on Linux, OS X, and Windows. It downloads a list of approximately 55,000 files from the server, then steps through the list of files, checking if the files are present locally. (With SHA hash verification and a few other goodies.) If the files aren't present locally or the hash doesn't match, it downloads them.</p>
<p>The server-side is plain-vanilla Apache 2 on Ubuntu over port 80.</p>
<p>The client side works perfectly on Mac and Linux, but gives me this error on Windows (XP and Vista) after downloading a number of files:</p>
<pre><code>urllib2.URLError: <urlopen error <10048, 'Address already in use'>>
</code></pre>
<p>This link: <a href="http://bytes.com/topic/python/answers/530949-client-side-tcp-socket-receiving-address-already-use-upon-connect" rel="nofollow">http://bytes.com/topic/python/answers/530949-client-side-tcp-socket-receiving-address-already-use-upon-connect</a> points me to TCP port exhaustion, but "netstat -n" never showed me more than six connections in "TIME_WAIT" status, even just before it errored out.</p>
<p>The code (called once for each of the 55,000 files it downloads) is this:</p>
<pre><code>request = urllib2.Request(file_remote_path)
opener = urllib2.build_opener()
datastream = opener.open(request)
outfileobj = open(temp_file_path, 'wb')
try:
while True:
chunk = datastream.read(CHUNK_SIZE)
if chunk == '':
break
else:
outfileobj.write(chunk)
finally:
outfileobj = outfileobj.close()
datastream.close()
</code></pre>
<p>UPDATE: I find by greping the log that it enters the download routine exactly 3998 times. I've run this multiple times and it fails at 3998 each time. Given that the linked article states that available ports are 5000-1025=3975 (and some are probably expiring and being reused) it's starting to look a lot more like the linked article describes the real issue. However, I'm still not sure how to fix this. Making registry edits is not an option.</p>
| 5 | 2009-10-02T22:15:24Z | 1,537,736 | <p>If it is really a resource problem (freeing os socket resources)</p>
<p>try this:</p>
<pre><code>request = urllib2.Request(file_remote_path)
opener = urllib2.build_opener()
retry = 3 # 3 tries
while retry :
try :
datastream = opener.open(request)
except urllib2.URLError, ue:
if ue.reason.find('10048') > -1 :
if retry :
retry -= 1
else :
raise urllib2.URLError("Address already in use / retries exhausted")
else :
retry = 0
if datastream :
retry = 0
outfileobj = open(temp_file_path, 'wb')
try:
while True:
chunk = datastream.read(CHUNK_SIZE)
if chunk == '':
break
else:
outfileobj.write(chunk)
finally:
outfileobj = outfileobj.close()
datastream.close()
</code></pre>
<p>if you want you can insert a sleep or you make it os depended</p>
<p>on my win-xp the problem doesn't show up (I reached 5000 downloads)</p>
<p>I watch my processes and network with <a href="http://processhacker.sourceforge.net/" rel="nofollow">process hacker</a>.</p>
| 5 | 2009-10-08T13:15:28Z | [
"python",
"windows",
"http",
"download",
"urllib2"
] |
urlopen error 10045, 'address already in use' while downloading in Python 2.5 on Windows | 1,512,057 | <p>I'm writing code that will run on Linux, OS X, and Windows. It downloads a list of approximately 55,000 files from the server, then steps through the list of files, checking if the files are present locally. (With SHA hash verification and a few other goodies.) If the files aren't present locally or the hash doesn't match, it downloads them.</p>
<p>The server-side is plain-vanilla Apache 2 on Ubuntu over port 80.</p>
<p>The client side works perfectly on Mac and Linux, but gives me this error on Windows (XP and Vista) after downloading a number of files:</p>
<pre><code>urllib2.URLError: <urlopen error <10048, 'Address already in use'>>
</code></pre>
<p>This link: <a href="http://bytes.com/topic/python/answers/530949-client-side-tcp-socket-receiving-address-already-use-upon-connect" rel="nofollow">http://bytes.com/topic/python/answers/530949-client-side-tcp-socket-receiving-address-already-use-upon-connect</a> points me to TCP port exhaustion, but "netstat -n" never showed me more than six connections in "TIME_WAIT" status, even just before it errored out.</p>
<p>The code (called once for each of the 55,000 files it downloads) is this:</p>
<pre><code>request = urllib2.Request(file_remote_path)
opener = urllib2.build_opener()
datastream = opener.open(request)
outfileobj = open(temp_file_path, 'wb')
try:
while True:
chunk = datastream.read(CHUNK_SIZE)
if chunk == '':
break
else:
outfileobj.write(chunk)
finally:
outfileobj = outfileobj.close()
datastream.close()
</code></pre>
<p>UPDATE: I find by greping the log that it enters the download routine exactly 3998 times. I've run this multiple times and it fails at 3998 each time. Given that the linked article states that available ports are 5000-1025=3975 (and some are probably expiring and being reused) it's starting to look a lot more like the linked article describes the real issue. However, I'm still not sure how to fix this. Making registry edits is not an option.</p>
| 5 | 2009-10-02T22:15:24Z | 1,541,415 | <p>You should seriously consider copying and modifying <a href="http://pycurl.cvs.sourceforge.net/pycurl/pycurl/examples/retriever-multi.py?view=markup" rel="nofollow">this pyCurl example</a> for efficient downloading of a large collection of files. </p>
| 1 | 2009-10-09T01:34:51Z | [
"python",
"windows",
"http",
"download",
"urllib2"
] |
urlopen error 10045, 'address already in use' while downloading in Python 2.5 on Windows | 1,512,057 | <p>I'm writing code that will run on Linux, OS X, and Windows. It downloads a list of approximately 55,000 files from the server, then steps through the list of files, checking if the files are present locally. (With SHA hash verification and a few other goodies.) If the files aren't present locally or the hash doesn't match, it downloads them.</p>
<p>The server-side is plain-vanilla Apache 2 on Ubuntu over port 80.</p>
<p>The client side works perfectly on Mac and Linux, but gives me this error on Windows (XP and Vista) after downloading a number of files:</p>
<pre><code>urllib2.URLError: <urlopen error <10048, 'Address already in use'>>
</code></pre>
<p>This link: <a href="http://bytes.com/topic/python/answers/530949-client-side-tcp-socket-receiving-address-already-use-upon-connect" rel="nofollow">http://bytes.com/topic/python/answers/530949-client-side-tcp-socket-receiving-address-already-use-upon-connect</a> points me to TCP port exhaustion, but "netstat -n" never showed me more than six connections in "TIME_WAIT" status, even just before it errored out.</p>
<p>The code (called once for each of the 55,000 files it downloads) is this:</p>
<pre><code>request = urllib2.Request(file_remote_path)
opener = urllib2.build_opener()
datastream = opener.open(request)
outfileobj = open(temp_file_path, 'wb')
try:
while True:
chunk = datastream.read(CHUNK_SIZE)
if chunk == '':
break
else:
outfileobj.write(chunk)
finally:
outfileobj = outfileobj.close()
datastream.close()
</code></pre>
<p>UPDATE: I find by greping the log that it enters the download routine exactly 3998 times. I've run this multiple times and it fails at 3998 each time. Given that the linked article states that available ports are 5000-1025=3975 (and some are probably expiring and being reused) it's starting to look a lot more like the linked article describes the real issue. However, I'm still not sure how to fix this. Making registry edits is not an option.</p>
| 5 | 2009-10-02T22:15:24Z | 1,551,171 | <p>Instead of opening a new TCP connection for each request you should really use persistent HTTP connections - have a look at <a href="http://linux.duke.edu/projects/urlgrabber/" rel="nofollow">urlgrabber</a> (or alternatively, just at <a href="http://linux.duke.edu/projects/urlgrabber/contents/urlgrabber/keepalive.py" rel="nofollow">keepalive.py</a> for how to add keep-alive connection support to urllib2).</p>
| 1 | 2009-10-11T17:03:06Z | [
"python",
"windows",
"http",
"download",
"urllib2"
] |
urlopen error 10045, 'address already in use' while downloading in Python 2.5 on Windows | 1,512,057 | <p>I'm writing code that will run on Linux, OS X, and Windows. It downloads a list of approximately 55,000 files from the server, then steps through the list of files, checking if the files are present locally. (With SHA hash verification and a few other goodies.) If the files aren't present locally or the hash doesn't match, it downloads them.</p>
<p>The server-side is plain-vanilla Apache 2 on Ubuntu over port 80.</p>
<p>The client side works perfectly on Mac and Linux, but gives me this error on Windows (XP and Vista) after downloading a number of files:</p>
<pre><code>urllib2.URLError: <urlopen error <10048, 'Address already in use'>>
</code></pre>
<p>This link: <a href="http://bytes.com/topic/python/answers/530949-client-side-tcp-socket-receiving-address-already-use-upon-connect" rel="nofollow">http://bytes.com/topic/python/answers/530949-client-side-tcp-socket-receiving-address-already-use-upon-connect</a> points me to TCP port exhaustion, but "netstat -n" never showed me more than six connections in "TIME_WAIT" status, even just before it errored out.</p>
<p>The code (called once for each of the 55,000 files it downloads) is this:</p>
<pre><code>request = urllib2.Request(file_remote_path)
opener = urllib2.build_opener()
datastream = opener.open(request)
outfileobj = open(temp_file_path, 'wb')
try:
while True:
chunk = datastream.read(CHUNK_SIZE)
if chunk == '':
break
else:
outfileobj.write(chunk)
finally:
outfileobj = outfileobj.close()
datastream.close()
</code></pre>
<p>UPDATE: I find by greping the log that it enters the download routine exactly 3998 times. I've run this multiple times and it fails at 3998 each time. Given that the linked article states that available ports are 5000-1025=3975 (and some are probably expiring and being reused) it's starting to look a lot more like the linked article describes the real issue. However, I'm still not sure how to fix this. Making registry edits is not an option.</p>
| 5 | 2009-10-02T22:15:24Z | 1,551,327 | <p>All indications point to a lack of available sockets. Are you sure that only 6 are in TIME_WAIT status? If you're running so many download operations it's very likely that netstat overruns your terminal buffer. I find that netstat stat overruns my terminal during normal useage periods.</p>
<p>The solution is to either modify the code to reuse sockets. Or introduce a timeout. It also wouldn't hurt to keep track of how many open sockets you have. To optimize waiting. The default timeout on Windows XP is 120 seconds. so you want to sleep for at least that long if you run out of sockets. Unfortunately it doesn't look like there's an easy way to check from Python when a socket has closed and left the TIME_WAIT status.</p>
<p>Given the asynchronous nature of the requests and timeouts, the best way to do this might be in a thread. Make each threat sleep for 2 minutes before it finishes. You can either use a Semaphore or limit the number of active threads to ensure that you don't run out of sockets.</p>
<p>Here's how I'd handle it. You might want to add an exception clause to the inner try block of the fetch section, to warn you about failed fetches.</p>
<pre><code>import time
import threading
import Queue
# assumes url_queue is a Queue object populated with tuples in the form of(url_to_fetch, temp_file)
# also assumes that TotalUrls is the size of the queue before any threads are started.
class urlfetcher(threading.Thread)
def __init__ (self, queue)
Thread.__init__(self)
self.queue = queue
def run(self)
try: # needed to handle empty exception raised by an empty queue.
file_remote_path, temp_file_path = self.queue.get()
request = urllib2.Request(file_remote_path)
opener = urllib2.build_opener()
datastream = opener.open(request)
outfileobj = open(temp_file_path, 'wb')
try:
while True:
chunk = datastream.read(CHUNK_SIZE)
if chunk == '':
break
else:
outfileobj.write(chunk)
finally:
outfileobj = outfileobj.close()
datastream.close()
time.sleep(120)
self.queue.task_done()
elsewhere:
while url_queue.size() < TotalUrls: # hard limit of available ports.
if threading.active_threads() < 3975: # Hard limit of available ports
t = urlFetcher(url_queue)
t.start()
else:
time.sleep(2)
url_queue.join()
</code></pre>
<p>Sorry, my python is a little rusty, so I wouldn't be surprised if I missed something.</p>
| 1 | 2009-10-11T18:11:15Z | [
"python",
"windows",
"http",
"download",
"urllib2"
] |
Django: Get an object form the DB, or 'None' if nothing matches | 1,512,059 | <p>Is there any Django function which will let me get an object form the database, or None if nothing matches?</p>
<p>Right now I'm using something like:</p>
<pre><code>foo = Foo.objects.filter(bar=baz)
foo = len(foo) > 0 and foo.get() or None
</code></pre>
<p>But that's not very clear, and it's messy to have everywhere.</p>
| 73 | 2009-10-02T22:15:33Z | 1,512,094 | <p>There are two ways to do this;</p>
<pre><code>try:
foo = Foo.objects.get(bar=baz)
except model.DoesNotExist:
foo = None
</code></pre>
<p>Or you can use a wrapper:</p>
<pre><code>def get_or_none(model, *args, **kwargs):
try:
return model.objects.get(*args, **kwargs)
except model.DoesNotExist:
return None
</code></pre>
<p>Call it like this</p>
<pre><code>foo = get_or_none(Foo, baz=bar)
</code></pre>
| 113 | 2009-10-02T22:27:49Z | [
"python",
"django"
] |
Django: Get an object form the DB, or 'None' if nothing matches | 1,512,059 | <p>Is there any Django function which will let me get an object form the database, or None if nothing matches?</p>
<p>Right now I'm using something like:</p>
<pre><code>foo = Foo.objects.filter(bar=baz)
foo = len(foo) > 0 and foo.get() or None
</code></pre>
<p>But that's not very clear, and it's messy to have everywhere.</p>
| 73 | 2009-10-02T22:15:33Z | 1,512,104 | <p>Give Foo <a href="http://www.djangoproject.com/documentation/models/custom_managers/" rel="nofollow">its custom manager</a>. It's pretty easy - just put your code into function in custom manager, set custom manager in your model and call it with <code>Foo.objects.your_new_func(...)</code>.</p>
<p>If you need generic function (to use it on any model not just that with custom manager) write your own and place it somewhere on your python path and import, not messy any more.</p>
| 9 | 2009-10-02T22:30:44Z | [
"python",
"django"
] |
Django: Get an object form the DB, or 'None' if nothing matches | 1,512,059 | <p>Is there any Django function which will let me get an object form the database, or None if nothing matches?</p>
<p>Right now I'm using something like:</p>
<pre><code>foo = Foo.objects.filter(bar=baz)
foo = len(foo) > 0 and foo.get() or None
</code></pre>
<p>But that's not very clear, and it's messy to have everywhere.</p>
| 73 | 2009-10-02T22:15:33Z | 2,021,833 | <p>To add some sample code to sorki's answer (I'd add this as a comment, but this is my first post, and I don't have enough reputation to leave comments), I implemented a get_or_none custom manager like so:</p>
<pre><code>from django.db import models
class GetOrNoneManager(models.Manager):
"""Adds get_or_none method to objects
"""
def get_or_none(self, **kwargs):
try:
return self.get(**kwargs)
except self.model.DoesNotExist:
return None
class Person(models.Model):
name = models.CharField(max_length=255)
objects = GetOrNoneManager()
</code></pre>
<p>And now I can do this:</p>
<pre><code>bob_or_none = Person.objects.get_or_none(name='Bob')
</code></pre>
| 69 | 2010-01-07T16:24:54Z | [
"python",
"django"
] |
Django: Get an object form the DB, or 'None' if nothing matches | 1,512,059 | <p>Is there any Django function which will let me get an object form the database, or None if nothing matches?</p>
<p>Right now I'm using something like:</p>
<pre><code>foo = Foo.objects.filter(bar=baz)
foo = len(foo) > 0 and foo.get() or None
</code></pre>
<p>But that's not very clear, and it's messy to have everywhere.</p>
| 73 | 2009-10-02T22:15:33Z | 13,614,419 | <p>Whether doing it via a manager or generic function, you may also want to catch 'MultipleObjectsReturned' in the TRY statement, as the get() function will raise this if your kwargs retrieve more than one object.</p>
<p>Building on the generic function:</p>
<pre><code>def get_unique_or_none(model, *args, **kwargs):
try:
return model.objects.get(*args, **kwargs)
except (model.DoesNotExist, model.MultipleObjectsReturned), err:
return None
</code></pre>
<p>and in the manager:</p>
<pre><code>class GetUniqueOrNoneManager(models.Manager):
"""Adds get_unique_or_none method to objects
"""
def get_unique_or_none(self, *args, **kwargs):
try:
return self.get(*args, **kwargs)
except (self.model.DoesNotExist, self.model.MultipleObjectsReturned), err:
return None
</code></pre>
| 4 | 2012-11-28T21:07:36Z | [
"python",
"django"
] |
Django: Get an object form the DB, or 'None' if nothing matches | 1,512,059 | <p>Is there any Django function which will let me get an object form the database, or None if nothing matches?</p>
<p>Right now I'm using something like:</p>
<pre><code>foo = Foo.objects.filter(bar=baz)
foo = len(foo) > 0 and foo.get() or None
</code></pre>
<p>But that's not very clear, and it's messy to have everywhere.</p>
| 73 | 2009-10-02T22:15:33Z | 17,938,407 | <p>In Django <strong>1.6</strong> you can use the <code>first()</code> Queryset method. It returns the first object matched by the queryset, or None if there is no matching object.</p>
<p>Usage:</p>
<pre><code>p = Article.objects.order_by('title', 'pub_date').first()
</code></pre>
| 59 | 2013-07-30T04:37:02Z | [
"python",
"django"
] |
Django: Get an object form the DB, or 'None' if nothing matches | 1,512,059 | <p>Is there any Django function which will let me get an object form the database, or None if nothing matches?</p>
<p>Right now I'm using something like:</p>
<pre><code>foo = Foo.objects.filter(bar=baz)
foo = len(foo) > 0 and foo.get() or None
</code></pre>
<p>But that's not very clear, and it's messy to have everywhere.</p>
| 73 | 2009-10-02T22:15:33Z | 23,548,184 | <p>You can also try to use django annoying (it has another useful functions!)</p>
<p>install it with:</p>
<pre><code>pip install django-annoying
from annoying.functions import get_object_or_None
get_object_or_None(Foo, bar=baz)
</code></pre>
| 10 | 2014-05-08T17:04:40Z | [
"python",
"django"
] |
Django: Get an object form the DB, or 'None' if nothing matches | 1,512,059 | <p>Is there any Django function which will let me get an object form the database, or None if nothing matches?</p>
<p>Right now I'm using something like:</p>
<pre><code>foo = Foo.objects.filter(bar=baz)
foo = len(foo) > 0 and foo.get() or None
</code></pre>
<p>But that's not very clear, and it's messy to have everywhere.</p>
| 73 | 2009-10-02T22:15:33Z | 25,025,658 | <p>Here's a variation on the helper function that allows you to optionally pass in a <code>QuerySet</code> instance, in case you want to get the unique object (if present) from a queryset other than the model's <code>all</code> objects queryset (e.g. from a subset of child items belonging to a parent instance):</p>
<pre><code>def get_unique_or_none(model, queryset=None, *args, **kwargs):
"""
Performs the query on the specified `queryset`
(defaulting to the `all` queryset of the `model`'s default manager)
and returns the unique object matching the given
keyword arguments. Returns `None` if no match is found.
Throws a `model.MultipleObjectsReturned` exception
if more than one match is found.
"""
if queryset is None:
queryset = model.objects.all()
try:
return queryset.get(*args, **kwargs)
except model.DoesNotExist:
return None
</code></pre>
<p>This can be used in two ways, e.g.:</p>
<ol>
<li><code>obj = get_unique_or_none(Model, *args, **kwargs)</code> as previosuly discussed</li>
<li><code>obj = get_unique_or_none(Model, parent.children, *args, **kwargs)</code></li>
</ol>
| 0 | 2014-07-29T21:58:00Z | [
"python",
"django"
] |
Generic Foreign Keys and get_or_create in django 1.0: Broken? | 1,512,152 | <p>As you can see, create() works, but get_or_create() doesn't. Am I missing something obvious here?</p>
<pre><code>In [7]: f = FeedItem.objects.create(source=u, dest=q, type="greata")
In [8]: f, created = FeedItem.objects.get_or_create(source=u, dest=q, type="greata")
---------------------------------------------------------------------------
FieldError Traceback (most recent call last)
/Users/andrew/clownfish/panda-repo/community-feed/<ipython console> in <module>()
/Library/Python/2.6/site-packages/django/db/models/manager.pyc in get_or_create(self, **kwargs)
/Library/Python/2.6/site-packages/django/db/models/query.pyc in get_or_create(self, **kwargs)
/Library/Python/2.6/site-packages/django/db/models/query.pyc in get(self, *args, **kwargs)
/Library/Python/2.6/site-packages/django/db/models/query.pyc in filter(self, *args, **kwargs)
/Library/Python/2.6/site-packages/django/db/models/query.pyc in _filter_or_exclude(self, negate, *args, **kwargs)
/Library/Python/2.6/site-packages/django/db/models/sql/query.pyc in add_q(self, q_object, used_aliases)
/Library/Python/2.6/site-packages/django/db/models/sql/query.pyc in add_filter(self, filter_expr, connector, negate, trim, can_reuse, process_extras)
/Library/Python/2.6/site-packages/django/db/models/sql/query.pyc in setup_joins(self, names, opts, alias, dupe_multis, allow_many, allow_explicit_fk, can_reuse, negate, process_extras)
FieldError: Cannot resolve keyword 'source' into field. Choices are: dest_content_type, dest_object_id, id, src_content_type, src_object_id, timestamp, type, weight
</code></pre>
| 1 | 2009-10-02T22:42:04Z | 1,512,228 | <p>Look like there's different logic used in <code>create</code> and <code>get_or_create</code> as in <code>get_or_create</code> there is no <code>source</code> argument but <code>src_object_id</code> and <code>src_content_type</code> but it is easy to resolve this - pass <code>scr_object_id</code> as <code>u.id</code> and <code>src_content_type</code> as <code>u.content_type</code> (same with dest).</p>
<p>Or use <code>try/except</code> & <code>create</code>.</p>
| 2 | 2009-10-02T23:07:17Z | [
"python",
"django",
"foreign-keys"
] |
What is a good reference for Server side development? | 1,512,155 | <p>I am more interested in the design of the code (i.e functional design vs object oriented design). What are the best practices and what is the communities thoughts on this subject?</p>
<p>Not that it should matter, but I am working with Apache and Python technology stack.</p>
| 1 | 2009-10-02T22:43:00Z | 1,512,239 | <p>If you are using Apache+Python, this sounds like you are using Python for dynamic web pages. In that case, I would strongly urge you to look into <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>. There are also other Python web development environments, but Django is perhaps the most popular; and it has excellent documentation such as <a href="http://www.djangobook.com/" rel="nofollow">The Django Book</a>. The Django Book describes best practices for setting up a robust web site: how to use multiple servers for redundancy, how to set up the database server, how to set up a cache to reduce the load on your database, etc.</p>
<p>Other than that tip, good Python server-side code would be just good Python code. There was a question asked recently about how to become a good Python developer, and I would suggest you read that: <a href="http://stackoverflow.com/questions/1507041/how-do-i-get-fluent-in-pythonic/1507101#1507101">http://stackoverflow.com/questions/1507041/how-do-i-get-fluent-in-pythonic/1507101#1507101</a></p>
| 1 | 2009-10-02T23:11:09Z | [
"python",
"apache",
"architecture"
] |
Python optparse defaults vs function defaults | 1,512,242 | <p>I'm writing a python script which I would like to be able to both call from the command line and import as a library function.
Ideally the command line options and the function should use the same set of default values.
What is the best way to allow me to reuse a single set of defaults in both places?</p>
<p>Here's the current code with duplicate defaults.</p>
<pre><code>from optparse import OptionParser
def do_stuff(opt1="a", opt2="b", opt3="c"):
print opt1, opt2, opt3
if __name__ == "__main__":
parser = OptionParser()
parser.add_option("--opt1", default="a")
parser.add_option("--opt2", default="b")
parser.add_option("--opt3", default="c")
#parser.set_defaults(opt1="a")
options, args = parser.parse_args()
do_stuff(*args, **vars(options))
</code></pre>
| 5 | 2009-10-02T23:11:22Z | 1,512,332 | <p>Here's the solution - it's trivial if you only need keyword arguments - just use locals.update. Following handles both, positional and key word args (key word args overrides positional).</p>
<pre><code>from optparse import OptionParser
ARGS = {'opt1': 'a',
'opt2': 'b',
'opt3': 'c'}
def do_stuff(*args, **kwargs):
locals = ARGS
keys = ARGS.keys()
keys.sort()
if args:
for key,arg in zip(keys,args):
locals.update({key: arg})
if kwargs:
locals.update(kwargs)
print locals['opt1'], locals['opt2'], locals['opt3']
if __name__ == "__main__":
parser = OptionParser()
for key,default in ARGS.items():
parser.add_option('--%s' % key, default='%s' % default)
options, args = parser.parse_args()
do_stuff(*args, **vars(options))
do_stuff()
do_stuff('d','e','f')
do_stuff('d','e','f', opt3='b')
do_stuff(opt1='c', opt2='a', opt3='b')
</code></pre>
<p>Output:</p>
<pre><code>a b c
a b c
d e f
d e b
c a b
</code></pre>
| 2 | 2009-10-02T23:48:57Z | [
"python",
"dry",
"optparse"
] |
Python optparse defaults vs function defaults | 1,512,242 | <p>I'm writing a python script which I would like to be able to both call from the command line and import as a library function.
Ideally the command line options and the function should use the same set of default values.
What is the best way to allow me to reuse a single set of defaults in both places?</p>
<p>Here's the current code with duplicate defaults.</p>
<pre><code>from optparse import OptionParser
def do_stuff(opt1="a", opt2="b", opt3="c"):
print opt1, opt2, opt3
if __name__ == "__main__":
parser = OptionParser()
parser.add_option("--opt1", default="a")
parser.add_option("--opt2", default="b")
parser.add_option("--opt3", default="c")
#parser.set_defaults(opt1="a")
options, args = parser.parse_args()
do_stuff(*args, **vars(options))
</code></pre>
| 5 | 2009-10-02T23:11:22Z | 1,512,579 | <p>I'd handle it by introspecting the function of interest to set options and defaults appropriately. For example:</p>
<pre><code>import inspect
from optparse import OptionParser
import sys
def do_stuff(opt0, opt1="a", opt2="b", opt3="c"):
print opt0, opt1, opt2, opt3
if __name__ == "__main__":
parser = OptionParser()
args, varargs, varkw, defaults = inspect.getargspec(do_stuff)
if varargs or varkw:
sys.exit("Sorry, can't make opts from a function with *a and/or **k!")
lend = len(defaults)
nodef = args[:-lend]
for a in nodef:
parser.add_option("--%s" % a)
for a, d in zip(args[-lend:], defaults):
parser.add_option("--%s" % a, default=d)
options, args = parser.parse_args()
d = vars(options)
for n, v in zip(nodef, args):
d[n] = v
do_stuff(**d)
</code></pre>
| 3 | 2009-10-03T01:59:42Z | [
"python",
"dry",
"optparse"
] |
Python optparse defaults vs function defaults | 1,512,242 | <p>I'm writing a python script which I would like to be able to both call from the command line and import as a library function.
Ideally the command line options and the function should use the same set of default values.
What is the best way to allow me to reuse a single set of defaults in both places?</p>
<p>Here's the current code with duplicate defaults.</p>
<pre><code>from optparse import OptionParser
def do_stuff(opt1="a", opt2="b", opt3="c"):
print opt1, opt2, opt3
if __name__ == "__main__":
parser = OptionParser()
parser.add_option("--opt1", default="a")
parser.add_option("--opt2", default="b")
parser.add_option("--opt3", default="c")
#parser.set_defaults(opt1="a")
options, args = parser.parse_args()
do_stuff(*args, **vars(options))
</code></pre>
| 5 | 2009-10-02T23:11:22Z | 1,513,680 | <p>The inspect solution by Alex is very powerful!</p>
<p>For lightweight programs, you could also simply use this:</p>
<pre><code>def do_stuff(opt1="a", opt2="b", opt3="c"):
print opt1, opt2, opt3
if __name__ == "__main__":
from optparse import OptionParser
opts = do_stuff.func_defaults
parser = OptionParser()
parser.add_option("--opt1", default=opts[0], help="Option 1 (%default)")
parser.add_option("--opt2", default=opts[1], help="Option 2 (%default)")
parser.add_option("--opt3", default=opts[2], help="Option 3 (%default)")
options, args = parser.parse_args()
do_stuff(*args, **vars(options))
</code></pre>
| 1 | 2009-10-03T12:58:37Z | [
"python",
"dry",
"optparse"
] |
Converting urls into lowercase? | 1,512,389 | <p>Is there any straightforward to convert all incoming urls to lowercase before they get matched against urlpatterns in <code>run_wsgi_app(webapp.WSGIApplication(urlpatterns))</code>? </p>
| 0 | 2009-10-03T00:21:15Z | 1,512,414 | <p>You'd have to wrap the instance of <code>WSGIApplication</code> with your own WSGI app that lowercases the URL in the WSGI environment -- but then the environment would just stay modified, which may have other unpleasant effects. Why not just add <code>(?i)</code> to the regex patterns you use in <code>urlpatterns</code> instead?</p>
| 3 | 2009-10-03T00:31:10Z | [
"python",
"google-app-engine",
"web-applications"
] |
Converting urls into lowercase? | 1,512,389 | <p>Is there any straightforward to convert all incoming urls to lowercase before they get matched against urlpatterns in <code>run_wsgi_app(webapp.WSGIApplication(urlpatterns))</code>? </p>
| 0 | 2009-10-03T00:21:15Z | 1,512,665 | <p>I wonder if you could modify your CGI environment variables before executing the WSGIApplication instance.</p>
<pre><code>os.putenv(os.getenv('PATH_INFO').lower())
</code></pre>
<p>Something along those lines. I've done this myself for slight URL modifications, however I 301 redirected to the new URL; I didn't continue processing with WSGI.</p>
| 0 | 2009-10-03T03:01:44Z | [
"python",
"google-app-engine",
"web-applications"
] |
Python: how to write a data struct to a file as text (not pickled) | 1,512,401 | <p>Is there a way to write python data structs to a file as text.</p>
<p>e.g. an app is running and has a variable/object: OPTIONS = ('ON', 'OFF', )</p>
<p>I need to write/merge the OPTIONS tuple into another file, not as a
pickled object, but as text, verbatim: OPTIONS = ('ON', 'OFF', )</p>
<p>I could traverse the tuple, and one by one write the elements into
the target file, but was wondering if there's an easier way.</p>
<p>note: if i do a "straight" write, i get the following:</p>
<pre><code>fout.write(OPTIONS)
...
TypeError: argument 1 must be string or read-only character buffer, not tuple
</code></pre>
| 2 | 2009-10-03T00:26:22Z | 1,512,417 | <p>You could use <a href="http://docs.python.org/library/functions.html#repr" rel="nofollow">repr</a> (repr works well with things that have a <code>__repr__()</code> method):</p>
<pre><code>>>> OPTIONS=('ON', 'OFF', )
>>> "OPTIONS="+repr(OPTIONS)
"OPTIONS=('ON', 'OFF')"
</code></pre>
| 4 | 2009-10-03T00:32:28Z | [
"python"
] |
Python: how to write a data struct to a file as text (not pickled) | 1,512,401 | <p>Is there a way to write python data structs to a file as text.</p>
<p>e.g. an app is running and has a variable/object: OPTIONS = ('ON', 'OFF', )</p>
<p>I need to write/merge the OPTIONS tuple into another file, not as a
pickled object, but as text, verbatim: OPTIONS = ('ON', 'OFF', )</p>
<p>I could traverse the tuple, and one by one write the elements into
the target file, but was wondering if there's an easier way.</p>
<p>note: if i do a "straight" write, i get the following:</p>
<pre><code>fout.write(OPTIONS)
...
TypeError: argument 1 must be string or read-only character buffer, not tuple
</code></pre>
| 2 | 2009-10-03T00:26:22Z | 1,512,419 | <p><code>fout.write(str(OPTIONS))</code> does what you want in this case, but no doubt in many others it won't; <code>repr</code> instead of <code>str</code> may be closer to your desires (but then again it might not be, as you express them so vaguely and generally, beyond that single example).</p>
| 1 | 2009-10-03T00:33:44Z | [
"python"
] |
Python: how to write a data struct to a file as text (not pickled) | 1,512,401 | <p>Is there a way to write python data structs to a file as text.</p>
<p>e.g. an app is running and has a variable/object: OPTIONS = ('ON', 'OFF', )</p>
<p>I need to write/merge the OPTIONS tuple into another file, not as a
pickled object, but as text, verbatim: OPTIONS = ('ON', 'OFF', )</p>
<p>I could traverse the tuple, and one by one write the elements into
the target file, but was wondering if there's an easier way.</p>
<p>note: if i do a "straight" write, i get the following:</p>
<pre><code>fout.write(OPTIONS)
...
TypeError: argument 1 must be string or read-only character buffer, not tuple
</code></pre>
| 2 | 2009-10-03T00:26:22Z | 1,512,490 | <p>I don't know your scope but you could use another serialisation/persistence system like <a href="http://docs.python.org/library/json.html" rel="nofollow">JSON</a>, or <a href="http://twistedmatrix.com/documents/current/api/twisted.spread.jelly.html" rel="nofollow">Twisted Jelly</a> that are more human readable (there's others like <a href="http://pyyaml.org/" rel="nofollow">YAML</a>).</p>
<p>I used jelly in some project for preferences files. It's really easy to use but you have to use repr() to save the data in human readable form and then eval() to read it back. So don't do that on everything because there's a security risk by using eval().</p>
<p>Here's a code example that prettify the representation (add indentation):</p>
<pre><code>VERSION = 'v1.1'
def read_data(filename):
return unjelly(eval(open(filename, 'r').read().replace('\n', '').replace('\t', '')))
def write_data(filename, obj):
dump = repr(jelly(obj))
level = 0
nice_dump = ['%s\n' % VERSION]
for char in dump:
if char == '[':
if level > 0:
nice_dump.append('\n' + '\t' * level)
level += 1
elif char == ']':
level -= 1
nice_dump.append(char)
open(filename, 'w').write(''.join(nice_dump))
</code></pre>
| 1 | 2009-10-03T01:08:30Z | [
"python"
] |
How do you retrieve the tags of a file in a list with Python (Windows Vista)? | 1,512,435 | <p>I want to make something of a tag cloud for various folders I have, but unfortunately, I can't seem to find a way to access the tags of a file in Windows Vista. I tried looking at the win32 module, and os.stat, but I can't seem to find a way. Can I get some help on this?</p>
| 3 | 2009-10-03T00:40:49Z | 1,512,539 | <p>Apparently, you need to use the <a href="http://msdn.microsoft.com/en-us/library/bb331575%28VS.85%29.aspx" rel="nofollow">Windows Search API</a> looking for <a href="http://msdn.microsoft.com/en-us/library/bb787519%28VS.85%29.aspx" rel="nofollow">System.Keywords</a> -- you can access the API directly via <a href="http://docs.python.org/library/ctypes.html" rel="nofollow"><code>ctypes</code></a>, or indirectly (needing <a href="http://python.net/crew/skippy/win32/Downloads.html" rel="nofollow">win32 extensions</a>) through the API's <a href="http://msdn.microsoft.com/en-us/library/bb286799%28VS.85%29.aspx" rel="nofollow">COM Interop</a> assembly. Sorry, I have no vista installation on which to check, but I hope these links are useful!</p>
| 4 | 2009-10-03T01:37:51Z | [
"python",
"windows-vista",
"tags"
] |
How do you retrieve the tags of a file in a list with Python (Windows Vista)? | 1,512,435 | <p>I want to make something of a tag cloud for various folders I have, but unfortunately, I can't seem to find a way to access the tags of a file in Windows Vista. I tried looking at the win32 module, and os.stat, but I can't seem to find a way. Can I get some help on this?</p>
| 3 | 2009-10-03T00:40:49Z | 1,512,552 | <p>It appears that Windows <strong>stores the tags in the files</strong>.
Just <strong>tag any image</strong> and <strong>open</strong> the image <strong>in notepad</strong> and <strong>look for</strong> something <strong>XML</strong>-like(<a href="http://en.wikipedia.org/wiki/Resource%5FDescription%5FFramework" rel="nofollow">RDF</a>) and you will find your tag there. Well... now we know that they are indeed stored in the files, but we still have no idea how to manipulate them.</p>
<p>But google is to the rescue. I googled: <em>windows metadata api</em></p>
<p>and found this: <a href="http://blogs.msdn.com/pix/archive/2006/12/06/photo-metadata-apis.aspx" rel="nofollow">http://blogs.msdn.com/pix/archive/2006/12/06/photo-metadata-apis.aspx</a></p>
| 2 | 2009-10-03T01:45:48Z | [
"python",
"windows-vista",
"tags"
] |
How do you retrieve the tags of a file in a list with Python (Windows Vista)? | 1,512,435 | <p>I want to make something of a tag cloud for various folders I have, but unfortunately, I can't seem to find a way to access the tags of a file in Windows Vista. I tried looking at the win32 module, and os.stat, but I can't seem to find a way. Can I get some help on this?</p>
| 3 | 2009-10-03T00:40:49Z | 5,846,091 | <p>I went about it with the win32 extensions package, along with some demo code I found. I posted a detailed explanation of the process on <a href="http://stackoverflow.com/questions/4584038/get-the-list-of-metadata-associated-to-a-file-using-python/5846021">this thread</a>. I don't want to reproduce it all here, but here is the short version (click the foregoing link for the details).</p>
<ol>
<li>Download and install the <a href="http://sourceforge.net/projects/pywin32/files/">pywin32 extension</a>.</li>
<li>Grab <a href="http://timgolden.me.uk/python/win32_how_do_i/get-document-summary-info.html">the code</a> Tim Golden wrote for this very task.</li>
<li>Save Tim's code as a module on your own computer.</li>
<li>Call the <code>property_sets</code> method of your new module (supplying the necessary filepath). The method returns a generator object, which is iterable. See the following example code and output.</li>
</ol>
<p>(This works for me in XP, at least.)</p>
<p>E.g.</p>
<pre><code>import your_new_module
propgenerator= your_new_module.property_sets('[your file path]')
for name, properties in propgenerator:
print name
for k, v in properties.items ():
print " ", k, "=>", v
</code></pre>
<p>The output of the above code will be something like the following:</p>
<pre><code>DocSummaryInformation
PIDDSI_CATEGORY => qux
SummaryInformation
PIDSI_TITLE => foo
PIDSI_COMMENTS => flam
PIDSI_AUTHOR => baz
PIDSI_KEYWORDS => flim
PIDSI_SUBJECT => bar
</code></pre>
| 5 | 2011-05-01T02:47:58Z | [
"python",
"windows-vista",
"tags"
] |
How do you retrieve the tags of a file in a list with Python (Windows Vista)? | 1,512,435 | <p>I want to make something of a tag cloud for various folders I have, but unfortunately, I can't seem to find a way to access the tags of a file in Windows Vista. I tried looking at the win32 module, and os.stat, but I can't seem to find a way. Can I get some help on this?</p>
| 3 | 2009-10-03T00:40:49Z | 11,290,737 | <p>There are actually 2 different implentations of document properties (<a href="http://mail.python.org/pipermail/python-win32/2005-June/003489.html" rel="nofollow">source</a>).</p>
<ol>
<li><p>The COM implementation embeds them directly in the file itself : this is the approach used for Office documents for example. Tim Golden's code described on this page works well for these.</p></li>
<li><p>On NTFS 5 (Win2k or later), you can add Summary info to any file, and it's stored in alternate data streams. I suppose the Windows Search API would work on these, but I have not tested it.</p></li>
</ol>
| 1 | 2012-07-02T09:08:58Z | [
"python",
"windows-vista",
"tags"
] |
Determining if stdout for a Python process is redirected | 1,512,457 | <p>I've noticed that curl can tell whether or not I'm redirecting its output (in which case it puts up a progress bar).</p>
<p>Is there a reasonable way to do this in a Python script? So: </p>
<p>$ python my_script.py<br />
Not redirected</p>
<p>$ python my_script.py > output.txt<br />
Redirected!</p>
| 10 | 2009-10-03T00:51:25Z | 1,512,466 | <p>Look at </p>
<pre><code>os.isatty(fd)
</code></pre>
<p>(I don't think this works on Windows, however)</p>
| 4 | 2009-10-03T00:55:34Z | [
"python"
] |
Determining if stdout for a Python process is redirected | 1,512,457 | <p>I've noticed that curl can tell whether or not I'm redirecting its output (in which case it puts up a progress bar).</p>
<p>Is there a reasonable way to do this in a Python script? So: </p>
<p>$ python my_script.py<br />
Not redirected</p>
<p>$ python my_script.py > output.txt<br />
Redirected!</p>
| 10 | 2009-10-03T00:51:25Z | 1,512,494 | <pre><code>import sys
if sys.stdout.isatty():
print "Not redirected"
else:
sys.stderr.write("Redirected!\n")
</code></pre>
| 26 | 2009-10-03T01:11:17Z | [
"python"
] |
Determining if stdout for a Python process is redirected | 1,512,457 | <p>I've noticed that curl can tell whether or not I'm redirecting its output (in which case it puts up a progress bar).</p>
<p>Is there a reasonable way to do this in a Python script? So: </p>
<p>$ python my_script.py<br />
Not redirected</p>
<p>$ python my_script.py > output.txt<br />
Redirected!</p>
| 10 | 2009-10-03T00:51:25Z | 1,512,526 | <p>Actually, what you want to do here is find out if <code>stdin</code> and <code>stdout</code> are the same thing.</p>
<pre><code>$ cat test.py
import os
print os.fstat(0) == os.fstat(1)
$ python test.py
True
$ python test.py > f
$ cat f
False
$
</code></pre>
<p>The longer but more traditional version of the <em>are they the same file</em> test just compares <code>st_ino</code> and <code>st_dev</code>. Typically, on windows these are faked up with a hash of something so that this exact design pattern will work.</p>
| 7 | 2009-10-03T01:31:14Z | [
"python"
] |
can't install lxml (python 2.6.3, osx 10.6 snow leopard) | 1,512,530 | <p>I try to: </p>
<blockquote>
<p>easy_install lxml</p>
</blockquote>
<p>and I get this error:</p>
<blockquote>
<p>File "build/bdist.macosx-10.3-fat/egg/setuptools/command/build_ext.py", line 85, in get_ext_filename
KeyError: 'etree'</p>
</blockquote>
<p>any hints?</p>
| 4 | 2009-10-03T01:33:26Z | 1,512,681 | <p>Due to incompatible changes in the 2.6.3 version of python's distutils, the old <code>easy_install</code> from <a href="http://pypi.python.org/pypi/setuptools" rel="nofollow">setuptools</a> no longer works. You need to replace it with <code>easy_install</code> from <a href="http://pypi.python.org/pypi/distribute" rel="nofollow">Distribute</a>. Follow the instructions there, basically:</p>
<pre><code>$ curl -O http://nightly.ziade.org/distribute_setup.py
$ python distribute_setup.py
</code></pre>
<p>assuming the 2.6.3 <code>python</code> is first on your <code>$PATH</code>.</p>
<p>EDIT: Besides the option to migrate from setuptools to Distribute, Python 2.6.4, which should be released in a couple of weeks, will contain a <a href="http://svn.python.org/view?view=rev&revision=75256" rel="nofollow">workaround</a> in distutils that will <a href="http://bugs.python.org/issue7064" rel="nofollow">unbreak setuptools</a>. Thanks, Tarek, for the fix and thanks, jbastos, for bringing this issue up.</p>
<p>FURTHER EDIT: <a href="http://pypi.python.org/pypi/setuptools" rel="nofollow">setuptools</a> itself has been updated (as of <code>0.6c10</code>) to work around the problem with 2.6.3. </p>
| 7 | 2009-10-03T03:08:05Z | [
"python",
"osx",
"port",
"osx-leopard",
"lxml"
] |
can't install lxml (python 2.6.3, osx 10.6 snow leopard) | 1,512,530 | <p>I try to: </p>
<blockquote>
<p>easy_install lxml</p>
</blockquote>
<p>and I get this error:</p>
<blockquote>
<p>File "build/bdist.macosx-10.3-fat/egg/setuptools/command/build_ext.py", line 85, in get_ext_filename
KeyError: 'etree'</p>
</blockquote>
<p>any hints?</p>
| 4 | 2009-10-03T01:33:26Z | 1,513,810 | <p>Ned :</p>
<blockquote>
<p>incompatible changes in the 2.6.3 version of python's distutil</p>
</blockquote>
<p>Not precisely. The API hasn't changed but Setuptools overrides them, and makes the assumption they are called in a particular order.</p>
<p>Lennart:</p>
<blockquote>
<p>The Distribute installation doesn't seem to trigger the bug</p>
</blockquote>
<p>Yes indeed, this precise bug was detected some time ago and fixed in Distribute (and in Ubuntu's setuptools package)</p>
| 3 | 2009-10-03T13:57:49Z | [
"python",
"osx",
"port",
"osx-leopard",
"lxml"
] |
How to access file metadata with Python? | 1,512,600 | <p>I'm trying to write a program in python that retrieves and updates file metadata on windows. I've tried searching on Google regarding what modules to use but I haven't found anything very concrete or useful.</p>
<p>Some people suggested the <a href="http://www.python.org/doc/2.5.2/lib/module-stat.html" rel="nofollow">stat module</a> which can give you info such as file access and last modification. But I'm looking to retrieve other types of metadata available on Windows. For example tags, author, rating, artists etc.</p>
<p>How can I retrieve this information for a file using Python?</p>
<p>Thanks</p>
| 3 | 2009-10-03T02:15:52Z | 1,512,611 | <p>Essentially as I said <a href="http://stackoverflow.com/questions/1512435/how-do-you-retrieve-the-tags-of-a-file-in-a-list-with-python-windows-vista">here</a> less than an hour ago,</p>
<blockquote>
<p>Apparently, you need to use the
Windows Search API looking for
System.Keywords -- you can access the
API directly via ctypes, or indirectly
(needing win32 extensions) through the
API's COM Interop assembly. Sorry, I
have no vista installation on which to
check, but I hope these links are
useful!</p>
</blockquote>
<p>Links don't preserve across copy and paste, please just visit the other SO questions for them;-).</p>
| 2 | 2009-10-03T02:25:52Z | [
"python",
"windows",
"metadata"
] |
Python Pypi: what is your process for releasing packages for different Python versions? (Linux) | 1,512,644 | <p>I've got several eggs I maintain on Pypi but up until now I've always focused on Python 2.5x.
I'd like to release my eggs under both Python 2.5 & Python 2.6 in an automated fashion i.e.</p>
<ol>
<li>running tests </li>
<li>generating doc</li>
<li>preparing eggs</li>
<li>uploading to Pypi</li>
</ol>
<p>How do you guys achieve this?</p>
<p>A related question: how do I tag an egg to be "version independent" ? works under all version of Python?</p>
| 5 | 2009-10-03T02:45:36Z | 1,513,605 | <p>I use a script to switch my Python version, run the tests, switch to the next Python version, run the tests again, and so on. I use this to test on 2.3, 2.4, 2.5, 2.6, and 3.1. In addition, I run all my tests under two different configuration scenarios (C extension available, or not), so this runs my full test suite 10 times.</p>
<p>I use a similar script to build kits, though I build windows installers for each version, then one source kit.</p>
<p>For uploading, I just do it all manually.</p>
<p>For docs, there's only one version to build, and that's done with a Makefile target.</p>
<p>This is all for coverage.py, you can see the code at <a href="http://bitbucket.org/ned/coveragepy" rel="nofollow">bitbucket</a>, though I should warn you, they are .cmd Windows scripts.</p>
| 0 | 2009-10-03T12:21:54Z | [
"python",
"release-management",
"pypi"
] |
Python Pypi: what is your process for releasing packages for different Python versions? (Linux) | 1,512,644 | <p>I've got several eggs I maintain on Pypi but up until now I've always focused on Python 2.5x.
I'd like to release my eggs under both Python 2.5 & Python 2.6 in an automated fashion i.e.</p>
<ol>
<li>running tests </li>
<li>generating doc</li>
<li>preparing eggs</li>
<li>uploading to Pypi</li>
</ol>
<p>How do you guys achieve this?</p>
<p>A related question: how do I tag an egg to be "version independent" ? works under all version of Python?</p>
| 5 | 2009-10-03T02:45:36Z | 1,513,884 | <p>You don't need to release eggs for anything else than Windows, and then only if your package uses C extensions so that they have compiled parts. Otherwise you simply release one source distribution. That will be enough for all Python versions on all platforms.</p>
<p>Running the tests for different versions automated is tricky if you don't have a buildbot. But once you have run the tests with both 2.5 and 2.6 releasing is just a question of running <code>python setup.py sdist register upload</code> and it doesn't matter what Python version you use to run that.</p>
| 1 | 2009-10-03T14:34:22Z | [
"python",
"release-management",
"pypi"
] |
Simple Facebook Connect in Google App Engine (Python) | 1,512,658 | <p>Does anyone have a simple and successful demo implementation of facebook connect in an google app engine application. I am developing an web application and want facebook connect to be the primary method for logging in.</p>
| 15 | 2009-10-03T02:56:13Z | 5,539,662 | <p>Here is the "<a href="http://stackoverflow.com/questions/2690723/facebook-graph-api-and-django/5539531#5539531">Start with Beginner guide on facebook application</a>". Hope this will help you... :)</p>
| -2 | 2011-04-04T14:07:35Z | [
"python",
"google-app-engine",
"authentication",
"facebook"
] |
Simple Facebook Connect in Google App Engine (Python) | 1,512,658 | <p>Does anyone have a simple and successful demo implementation of facebook connect in an google app engine application. I am developing an web application and want facebook connect to be the primary method for logging in.</p>
| 15 | 2009-10-03T02:56:13Z | 33,281,983 | <p>I recently used python-social-auth to use Google login, should also work with Facebook:</p>
<p><a href="https://python-social-auth.readthedocs.org/en/latest/" rel="nofollow">https://python-social-auth.readthedocs.org/en/latest/</a></p>
<p>I had some troubles with the implementation, but this tutorial really helped me:</p>
<p><a href="http://artandlogic.com/2014/04/tutorial-adding-facebooktwittergoogle-authentication-to-a-django-application/" rel="nofollow">http://artandlogic.com/2014/04/tutorial-adding-facebooktwittergoogle-authentication-to-a-django-application/</a></p>
| 1 | 2015-10-22T13:16:23Z | [
"python",
"google-app-engine",
"authentication",
"facebook"
] |
How to access YQL in Python (Django)? | 1,512,926 | <p>Hey, I need a simple example for the following task:<br />
Send a query to YQL and receive a response<br />
I am accessing public data from python backend of my Django app.</p>
<p>If I just copy/paste an example from YQL, it says "Please provide valid credentials".<br />
I guess, I need OAuth authorization to do it.<br />
So I got an API key and a shared secret. </p>
<p>Now, what should I do with them?<br />
Should I use python oauth library? This one?<br />
<a href="http://oauth.googlecode.com/svn/code/python/oauth/" rel="nofollow">http://oauth.googlecode.com/svn/code/python/oauth/</a> </p>
<p>But what is the code? How I pass my secret/API key along with my yql query?</p>
<p>I guess, many Django programmers would love to know this.</p>
| 0 | 2009-10-03T05:50:21Z | 1,514,556 | <p>Ok, I sort of resolved the problem.<br />
In YQL console example for data/html the following url was presented as an example:</p>
<p>http://query.yahooapis.com/v1/yql?q=select+*+from+html+where+url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fq%3Fs%3Dyhoo%22+and%0A++++++xpath%3D%27%2F%2Fdiv%5B%40id%3D%22yfi_headlines%22%5D%2Fdiv%5B2%5D%2Ful%2Fli%2Fa%27</p>
<p>It does not work!<br />
But if you insert "/public" after "v1/" than it magically starts working!</p>
<p>http://query.yahooapis.com/v1/public/yql?q=select+*+from+html+where+url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fq%3Fs%3Dyhoo%22+and%0A++++++xpath%3D%27%2F%2Fdiv%5B%40id%3D%22yfi_headlines%22%5D%2Fdiv%5B2%5D%2Ful%2Fli%2Fa%27</p>
<p>But the question of how to pass my API key (for v1/yql access) is still open. Any advice?</p>
| 0 | 2009-10-03T19:07:01Z | [
"python",
"django",
"api",
"oauth",
"yql"
] |
How to access YQL in Python (Django)? | 1,512,926 | <p>Hey, I need a simple example for the following task:<br />
Send a query to YQL and receive a response<br />
I am accessing public data from python backend of my Django app.</p>
<p>If I just copy/paste an example from YQL, it says "Please provide valid credentials".<br />
I guess, I need OAuth authorization to do it.<br />
So I got an API key and a shared secret. </p>
<p>Now, what should I do with them?<br />
Should I use python oauth library? This one?<br />
<a href="http://oauth.googlecode.com/svn/code/python/oauth/" rel="nofollow">http://oauth.googlecode.com/svn/code/python/oauth/</a> </p>
<p>But what is the code? How I pass my secret/API key along with my yql query?</p>
<p>I guess, many Django programmers would love to know this.</p>
| 0 | 2009-10-03T05:50:21Z | 1,665,320 | <p>If you only are accessing public data you can just make a direct rest call from python.</p>
<pre><code>>>> import urllib2
>>> result = urllib2.urlopen("http://query.yahooapis.com/v1/public/yql?q=select%20title%2Cabstract%20from%20search.web%20where%20query%3D%22paul%20tarjan%22&format=json").read()
>>> print result[:100]
{"query":{"count":"10","created":"2009-11-03T04:47:01Z","lang":"en-US","updated":"2009-11-03T04:47:0
</code></pre>
<p>And then you can parse the result with simplejson.</p>
<pre><code>>>> import simplejson
>>> data = simplejson.loads(result)
>>> data['query']['results']['result'][0]['title']
u'<b>Paul</b> <b>Tarjan</b> - Silicon Valley, CA | Facebook'
</code></pre>
| 2 | 2009-11-03T04:53:10Z | [
"python",
"django",
"api",
"oauth",
"yql"
] |
How to access YQL in Python (Django)? | 1,512,926 | <p>Hey, I need a simple example for the following task:<br />
Send a query to YQL and receive a response<br />
I am accessing public data from python backend of my Django app.</p>
<p>If I just copy/paste an example from YQL, it says "Please provide valid credentials".<br />
I guess, I need OAuth authorization to do it.<br />
So I got an API key and a shared secret. </p>
<p>Now, what should I do with them?<br />
Should I use python oauth library? This one?<br />
<a href="http://oauth.googlecode.com/svn/code/python/oauth/" rel="nofollow">http://oauth.googlecode.com/svn/code/python/oauth/</a> </p>
<p>But what is the code? How I pass my secret/API key along with my yql query?</p>
<p>I guess, many Django programmers would love to know this.</p>
| 0 | 2009-10-03T05:50:21Z | 1,734,456 | <p>I've just released <a href="https://launchpad.net/python-yql" rel="nofollow">python-yql</a> also available on pypi. It can do public, two-legged oauth a.k.a signed requests and facilitate 3-legged outh too.</p>
<p>It's brand new so there may be some bugs whilst I work on improving the test coverage but should hopefully do what you need. See the source for some idea on how to use it.</p>
<p>Installing to try it is as follows:</p>
<pre><code>sudo easy_install yql
</code></pre>
<p>Bug/Feature requests can be filed here: <a href="https://bugs.launchpad.net/python-yql" rel="nofollow">https://bugs.launchpad.net/python-yql</a></p>
| 3 | 2009-11-14T14:59:11Z | [
"python",
"django",
"api",
"oauth",
"yql"
] |
text diff on django/google appengine | 1,512,966 | <p>I am developing a wiki using django which i plan to deploy later in google appengine. Is it possible to deploy textdiff like system in appengine?</p>
| 0 | 2009-10-03T06:16:59Z | 1,513,067 | <p>The <a href="http://docs.python.org/library/difflib.html" rel="nofollow">difflib</a> package can be useful for generating diffs. It's written in pure Python and it's in the standard Python library, so I'd expect it to be available in Google App Engine.</p>
| 2 | 2009-10-03T07:19:01Z | [
"python",
"django"
] |
Deploying a web service to my Google App Engine application | 1,513,038 | <p>We made a simple application and using GoogleAppEngineLauncher (GAEL) ran that locally. Then we deployed, using GAEL again, to our appid. It works fine. </p>
<p>Now, we made a web service. We ran that locally using GAEL and a very thin local python client. It works fine.</p>
<p>We deployed that, and we get this message when we try to visit our default page:</p>
<p>"Move along people, there is nothing to see here"</p>
<p>We modified our local client and tried to run that against our google site and we got an error that looked like:</p>
<p>Response is "text/plain", not "text/xml"</p>
<p>Any ideas where we are falling down in our deployment or config for using a web service with google app engine?</p>
<p>Any help appreciated!</p>
<p>Thanks // :)</p>
| 0 | 2009-10-03T07:04:43Z | 1,514,062 | <p>Looks like you're not setting the Content-Type header correctly in your service (assuming you ARE actually trying to send XML -- e.g. SOAP, XML-RPC, &c). What code are you using to set that header? Without some indication about what protocol you're implementing and via what framework, it's impossible to help in detail...!</p>
| 1 | 2009-10-03T15:32:32Z | [
"iphone",
"python",
"web-services",
"google-app-engine"
] |
Deploying a web service to my Google App Engine application | 1,513,038 | <p>We made a simple application and using GoogleAppEngineLauncher (GAEL) ran that locally. Then we deployed, using GAEL again, to our appid. It works fine. </p>
<p>Now, we made a web service. We ran that locally using GAEL and a very thin local python client. It works fine.</p>
<p>We deployed that, and we get this message when we try to visit our default page:</p>
<p>"Move along people, there is nothing to see here"</p>
<p>We modified our local client and tried to run that against our google site and we got an error that looked like:</p>
<p>Response is "text/plain", not "text/xml"</p>
<p>Any ideas where we are falling down in our deployment or config for using a web service with google app engine?</p>
<p>Any help appreciated!</p>
<p>Thanks // :)</p>
| 0 | 2009-10-03T07:04:43Z | 1,604,138 | <p>Looks like we aren't going to get to the bottom of this one. Just not enough information available at debug time. We've managed to affect a fix on the service, although I hate ot admit it we never found out what was causing this bug.</p>
| 0 | 2009-10-21T23:02:49Z | [
"iphone",
"python",
"web-services",
"google-app-engine"
] |
Is there a portable way of finding if a path is absolute, using Python? | 1,513,155 | <p>Is there some built-in function that tells me if a path is absolute or not? I'd like something that is platform independent.</p>
| 2 | 2009-10-03T08:06:23Z | 1,513,159 | <p>The <a href="http://docs.python.org/library/os.path.html#os.path.isabs" rel="nofollow"><code>os.path.isabs</code></a> function does this.</p>
| 13 | 2009-10-03T08:08:20Z | [
"python",
"absolute-path"
] |
What should I use instead of assignment-in-an-expression in Python? | 1,513,436 | <p>according to <a href="http://pyfaq.infogami.com/why-can-t-i-use-an-assignment-in-an-expression" rel="nofollow">this page</a> one can't use code like</p>
<pre><code>if variable = something():
#do something with variable, whose value is the result of something() and is true
</code></pre>
<p>So in case I want to have the following code structure:</p>
<pre><code>if a = something():
#do something with a
elif a = somethingelse():
#...
#5 more elifs
</code></pre>
<p>where something() functions are compute-intensive (I mean that using the function and then doing it again to assign value to a variable in case the first one was true can't be done), what should I write instead in Python? Add 7 more variables instead of 1?</p>
| 3 | 2009-10-03T10:33:33Z | 1,513,456 | <p>You could do this:</p>
<pre><code>a = something()
if a:
#do something with a
else:
a = somethingelse()
if a:
#...
else:
#5 more nested ifs
</code></pre>
<p>Or, inside a function you can limit the nesting level with a <code>return</code> in each matching case:</p>
<pre><code>def f():
a = something()
if a:
#do something with a
return
a = somethingelse()
if a:
#...
return
#5 more ifs
</code></pre>
| 3 | 2009-10-03T10:42:24Z | [
"python"
] |
What should I use instead of assignment-in-an-expression in Python? | 1,513,436 | <p>according to <a href="http://pyfaq.infogami.com/why-can-t-i-use-an-assignment-in-an-expression" rel="nofollow">this page</a> one can't use code like</p>
<pre><code>if variable = something():
#do something with variable, whose value is the result of something() and is true
</code></pre>
<p>So in case I want to have the following code structure:</p>
<pre><code>if a = something():
#do something with a
elif a = somethingelse():
#...
#5 more elifs
</code></pre>
<p>where something() functions are compute-intensive (I mean that using the function and then doing it again to assign value to a variable in case the first one was true can't be done), what should I write instead in Python? Add 7 more variables instead of 1?</p>
| 3 | 2009-10-03T10:33:33Z | 1,513,627 | <p>Another alternative which offers some flexibility:</p>
<pre><code># Functions to be tested (can be expanded):
tests = [something, somethingelse, yetsomethingelse, anotherfunction, another]
for i, f in enumerate(tests):
a = f()
if a:
if i == 0:
# do something with a
elif 1 <= i <= 3:
# do something else with a
else:
# ...
break
</code></pre>
<p>Or you can explicitly compare to the function:</p>
<pre><code>tests = [something, somethingelse, yetsomethingelse, anotherfunction, another]
for i, f in enumerate(tests):
a = f()
if a: break
if not a:
# no result
elif f == something:
# ...
elif f == somethingelse:
# ...
</code></pre>
<p>If some of the functions take arguments, you can use lambda to keep the function paradigm:</p>
<pre><code>tests = [lambda: something(args), somethingelse, lambda: something(otherargs)]
for i, f in enumerate(tests):
a = f()
if a: break
if not a:
# no result
elif i == 0:
# ...
elif i == 1:
# ...
</code></pre>
| 3 | 2009-10-03T12:34:43Z | [
"python"
] |
What should I use instead of assignment-in-an-expression in Python? | 1,513,436 | <p>according to <a href="http://pyfaq.infogami.com/why-can-t-i-use-an-assignment-in-an-expression" rel="nofollow">this page</a> one can't use code like</p>
<pre><code>if variable = something():
#do something with variable, whose value is the result of something() and is true
</code></pre>
<p>So in case I want to have the following code structure:</p>
<pre><code>if a = something():
#do something with a
elif a = somethingelse():
#...
#5 more elifs
</code></pre>
<p>where something() functions are compute-intensive (I mean that using the function and then doing it again to assign value to a variable in case the first one was true can't be done), what should I write instead in Python? Add 7 more variables instead of 1?</p>
| 3 | 2009-10-03T10:33:33Z | 1,513,629 | <p>You could use a decorator like this memorise for those functions - assuming they always return the same value. Notice that you can call expensive_foo and expensive_bar as many times as you like and the function body only ever gets executed once</p>
<pre><code>def memoize(f):
mem = {}
def inner(*args):
if args not in mem:
mem[args] = f(*args)
return mem[args]
return inner
@memoize
def expensive_foo():
print "expensive_foo"
return False
@memoize
def expensive_bar():
print "expensive_bar"
return True
if expensive_foo():
a=expensive_foo()
print "FOO"
elif expensive_bar():
a=expensive_bar()
print "BAR"
</code></pre>
| 1 | 2009-10-03T12:35:14Z | [
"python"
] |
What should I use instead of assignment-in-an-expression in Python? | 1,513,436 | <p>according to <a href="http://pyfaq.infogami.com/why-can-t-i-use-an-assignment-in-an-expression" rel="nofollow">this page</a> one can't use code like</p>
<pre><code>if variable = something():
#do something with variable, whose value is the result of something() and is true
</code></pre>
<p>So in case I want to have the following code structure:</p>
<pre><code>if a = something():
#do something with a
elif a = somethingelse():
#...
#5 more elifs
</code></pre>
<p>where something() functions are compute-intensive (I mean that using the function and then doing it again to assign value to a variable in case the first one was true can't be done), what should I write instead in Python? Add 7 more variables instead of 1?</p>
| 3 | 2009-10-03T10:33:33Z | 1,513,894 | <p>I might be missing something, but couldn't you factor each of the branches in your top-level <code>if</code> statement into separate functions, create a list of <em>test</em> to <em>action</em> tuples and loop over them? You should be able to apply this pattern to mimic <code>if (value=condition()) {} else if (value=other_condition()) {}</code> style logic.</p>
<p>This is really an extension of <a href="http://stackoverflow.com/questions/1513436/what-should-i-use-instead-of-assignment-in-an-expression-in-python/1513627#1513627">redglyph's response</a> and can probably be compressed down to a <a href="http://docs.python.org/tutorial/classes.html#iterators" rel="nofollow">iterator</a> that raises <code>StopIteration</code> once it has hit a truth value.</p>
<pre><code>#
# These are the "tests" from your original if statements. No
# changes should be necessary.
#
def something():
print('doing something()')
# expensive stuff here
def something_else():
print('doing something_else()')
# expensive stuff here too... but this returns True for some reason
return True
def something_weird():
print('doing something_weird()')
# other expensive stuff
#
# Factor each branch of your if statement into a separate function.
# Each function will receive the output of the test if the test
# was selected.
#
def something_action(value):
print("doing something's action")
def something_else_action(value):
print("doing something_else's action")
def something_weird_action(value):
print("doing something_weird's action")
#
# A simple iteration function that takes tuples of (test,action). The
# test is called. If it returns a truth value, then the value is passed
# onto the associated action and the iteration is stopped.
#
def do_actions(*action_tuples):
for (test,action) in action_tuples:
value = test()
if value:
return action(value)
#
# ... and here is how you would use it:
#
result = do_actions(
(something, something_action),
(something_else, something_else_action),
(something_weird, something_weird_action)
)
</code></pre>
| 1 | 2009-10-03T14:38:01Z | [
"python"
] |
What should I use instead of assignment-in-an-expression in Python? | 1,513,436 | <p>according to <a href="http://pyfaq.infogami.com/why-can-t-i-use-an-assignment-in-an-expression" rel="nofollow">this page</a> one can't use code like</p>
<pre><code>if variable = something():
#do something with variable, whose value is the result of something() and is true
</code></pre>
<p>So in case I want to have the following code structure:</p>
<pre><code>if a = something():
#do something with a
elif a = somethingelse():
#...
#5 more elifs
</code></pre>
<p>where something() functions are compute-intensive (I mean that using the function and then doing it again to assign value to a variable in case the first one was true can't be done), what should I write instead in Python? Add 7 more variables instead of 1?</p>
| 3 | 2009-10-03T10:33:33Z | 1,513,987 | <p>Make yourself a simple callable object that saves its returned value:</p>
<pre><code>class ConditionValue(object):
def __call__(self, x):
self.value = x
return bool(x)
</code></pre>
<p>Now use it like this:</p>
<pre><code># example code
makelower = lambda c : c.isalpha() and c.lower()
add10 = lambda c : c.isdigit() and int(c) + 10
test = "ABC123.DEF456"
val = ConditionValue()
for t in test:
if val(makelower(t)):
print t, "is now lower case ->", val.value
elif val(add10(t)):
print t, "+10 ->", val.value
else:
print "unknown char", t
</code></pre>
<p>Prints:</p>
<pre><code>A is now lower case -> a
B is now lower case -> b
C is now lower case -> c
1 +10 -> 11
2 +10 -> 12
3 +10 -> 13
unknown char .
D is now lower case -> d
E is now lower case -> e
F is now lower case -> f
4 +10 -> 14
5 +10 -> 15
6 +10 -> 16
</code></pre>
| 1 | 2009-10-03T15:07:11Z | [
"python"
] |
What should I use instead of assignment-in-an-expression in Python? | 1,513,436 | <p>according to <a href="http://pyfaq.infogami.com/why-can-t-i-use-an-assignment-in-an-expression" rel="nofollow">this page</a> one can't use code like</p>
<pre><code>if variable = something():
#do something with variable, whose value is the result of something() and is true
</code></pre>
<p>So in case I want to have the following code structure:</p>
<pre><code>if a = something():
#do something with a
elif a = somethingelse():
#...
#5 more elifs
</code></pre>
<p>where something() functions are compute-intensive (I mean that using the function and then doing it again to assign value to a variable in case the first one was true can't be done), what should I write instead in Python? Add 7 more variables instead of 1?</p>
| 3 | 2009-10-03T10:33:33Z | 1,514,109 | <p>I had this problem years ago, in 2001 -- since I was transliterating to Python from a reference-algorithm in C which used assign-and-test heavily, I was keen to keep a similar structure for the first draft (then refactor later once correctness was well tested). So I wrote a <a href="http://books.google.com/books?id=1Shx%5FVXS6ioC&lpg=PA181&ots=BB607IWaL1&dq=martelli%20cookbook%20test%20assign&pg=PA181#v=onepage&q=&f=false" rel="nofollow">recipe</a> in the Cookbook (see also <a href="http://code.activestate.com/recipes/66061/" rel="nofollow">here</a>), which boils down to...:</p>
<pre><code>class DataHolder(object):
def set(self, value): self.value = value; return value
</code></pre>
<p>so the <code>if</code>/<code>elif</code> tree can become:</p>
<pre><code>dh = DataHolder()
if dh.set(something()):
# do something with dh.value
elif dh.set(somethingelse()):
# ...
</code></pre>
<p>the <code>DataHolder</code> class can clearly be embellished in various ways (and is so embellished in both the online and book versions), but this is the gist of it, and quite sufficient to answer your question.</p>
| 10 | 2009-10-03T15:49:48Z | [
"python"
] |
What should I use instead of assignment-in-an-expression in Python? | 1,513,436 | <p>according to <a href="http://pyfaq.infogami.com/why-can-t-i-use-an-assignment-in-an-expression" rel="nofollow">this page</a> one can't use code like</p>
<pre><code>if variable = something():
#do something with variable, whose value is the result of something() and is true
</code></pre>
<p>So in case I want to have the following code structure:</p>
<pre><code>if a = something():
#do something with a
elif a = somethingelse():
#...
#5 more elifs
</code></pre>
<p>where something() functions are compute-intensive (I mean that using the function and then doing it again to assign value to a variable in case the first one was true can't be done), what should I write instead in Python? Add 7 more variables instead of 1?</p>
| 3 | 2009-10-03T10:33:33Z | 1,515,430 | <p>I would solve this the same way I solve several other problems of tricky flow control: move the tricky bit into a function, and then use <code>return</code> to cause an early exit from the function. Like so:</p>
<pre><code>def do_correct_something():
a = something()
if a:
# do something with a
return a
a = somethingelse()
if a:
# do something else with a
return a
# 5 more function calls, if statements, do somethings, and returns
# then, at the very end:
return None
a = do_correct_something()
</code></pre>
<p>The major other "tricky problem of flow control" for which I do this is breaking out of multiple nested loops:</p>
<pre><code>def find_in_3d_matrix(matrix, x):
for plane in matrix:
for row in plane:
for item in row:
if test_function(x, item):
return item
return None
</code></pre>
<p>You can also solve the stated question by writing a for loop that will iterate only once, and use "break" for the early exit, but I prefer the function-with-return version. It's less tricky, and clearer what is going on; and the function-with-return is the only clean way to break out of multiple loops in Python. (Putting "<code>if break_flag: break</code>" in each of the for loops, and setting break_flag when you want to break, is not IMHO clean.)</p>
| 1 | 2009-10-04T02:24:02Z | [
"python"
] |
What should I use instead of assignment-in-an-expression in Python? | 1,513,436 | <p>according to <a href="http://pyfaq.infogami.com/why-can-t-i-use-an-assignment-in-an-expression" rel="nofollow">this page</a> one can't use code like</p>
<pre><code>if variable = something():
#do something with variable, whose value is the result of something() and is true
</code></pre>
<p>So in case I want to have the following code structure:</p>
<pre><code>if a = something():
#do something with a
elif a = somethingelse():
#...
#5 more elifs
</code></pre>
<p>where something() functions are compute-intensive (I mean that using the function and then doing it again to assign value to a variable in case the first one was true can't be done), what should I write instead in Python? Add 7 more variables instead of 1?</p>
| 3 | 2009-10-03T10:33:33Z | 39,776,949 | <p>This is possible if we working with strings - because we can convert string to list and use method <code>extends</code> for list that logically make inline appending one string to another (in list format):</p>
<pre><code>>>> my_str = list('xxx')
>>> if not my_str.extend(list('yyy')) and 'yyy' in ''.join(my_str):
... print(True)
True
</code></pre>
<p>Here we inside <code>if</code> 'added to the original string' new data and trying to find it. Maybe this is ugly but this is assignment in an expression like:</p>
<pre><code>if my_str += 'yyy' and 'yyy' in my_str:
</code></pre>
| 0 | 2016-09-29T17:53:32Z | [
"python"
] |
verifiedEmail AOL OpenID | 1,513,543 | <p>I can't seem to fetch the verifiedEmail field when trying to login to AOLs OpenID on my site. Every other provider that I know of provides this property, but not AOL.</p>
<p>I realize that AOL somehow uses an old OpenID version, although is it feasible to just assume that their e-mail ends in @aol.com? I'm using the RPXNow library with Python.</p>
| 0 | 2009-10-03T11:40:18Z | 1,513,794 | <p>I believe that OpenID lets the user decide how much information to "share" during the login process. I can't say that I am an expert on the subject, but I know that my identity at myopenid.com lets me specify precisely what information to make available.</p>
<p>Is it possible that the AOL default is to share nothing? If this is the case, then you may want to do an email authorization directly with the user if the OpenID provider doesn't seem to have the information. OpenID doesn't mandate that this information is available so I would assume that you will have to handle the case of it not being there in application code.</p>
| 0 | 2009-10-03T13:47:49Z | [
"python",
"openid",
"rpxnow"
] |
python: is there an XML parser implemented as a generator? | 1,513,592 | <p>I'd like to parse a big XML file "on the fly". I'd like to use a python generator to perform this. I've tried "iterparse" of "xml.etree.cElementTree" (which is really nice) but still not a generator.</p>
<p>Other suggestions?</p>
| 8 | 2009-10-03T12:14:31Z | 1,513,604 | <p>"On the fly" parsing and document trees are not really compatible. SAX-style parsers are usually used for that (for example, Python's standard <a href="http://docs.python.org/library/xml.sax.html">xml.sax</a>). You basically have to define a class with handlers for various events like startElement, endElement, etc. and the parser will call the methods as it parses the XML file.</p>
| 6 | 2009-10-03T12:20:44Z | [
"python",
"xml",
"parsing",
"generator"
] |
python: is there an XML parser implemented as a generator? | 1,513,592 | <p>I'd like to parse a big XML file "on the fly". I'd like to use a python generator to perform this. I've tried "iterparse" of "xml.etree.cElementTree" (which is really nice) but still not a generator.</p>
<p>Other suggestions?</p>
| 8 | 2009-10-03T12:14:31Z | 1,513,621 | <p><a href="http://docs.python.org/3/library/xml.dom.pulldom.html" rel="nofollow">PullDom</a> does what you want. It reads XML from a stream, like SAX, but then builds a DOM for a selected piece of it.</p>
<p><em>"PullDOM is a really simple API for working with DOM objects in a streaming (efficient!) manner rather than as a monolithic tree."</em></p>
| 4 | 2009-10-03T12:30:57Z | [
"python",
"xml",
"parsing",
"generator"
] |
python: is there an XML parser implemented as a generator? | 1,513,592 | <p>I'd like to parse a big XML file "on the fly". I'd like to use a python generator to perform this. I've tried "iterparse" of "xml.etree.cElementTree" (which is really nice) but still not a generator.</p>
<p>Other suggestions?</p>
| 8 | 2009-10-03T12:14:31Z | 1,513,640 | <p><code>xml.etree.cElementTree</code> comes close to a generator with correct usage; by default you receive each element after its 'end' event, at which point you can process it. You should use element.clear() on the element if you don't need it after processing; thereby you save the memory.</p>
<p><hr /></p>
<p>Here is a complete example what I mean, where I parse Rhythmbox's (Music Player) Library. I use (c)ElementTree's iterparse and for each processed element I call element.clear() so that I save quite a lot of memory. (Btw, the code below is a successor to some sax code to do the same thing; the cElementTree solution was a relief since 1) The code is concise and expresses what I need and nothing more 2) It is 3x as fast, 3) it uses less memory.)</p>
<pre><code>import os
import xml.etree.cElementTree as ElementTree
NEEDED_KEYS= set(("title", "artist", "album", "track-number", "location", ))
def _lookup_string(string, strmap):
"""Look up @string in the string map,
and return the copy in the map.
If not found, update the map with the string.
"""
string = string or ""
try:
return strmap[string]
except KeyError:
strmap[string] = string
return string
def get_rhythmbox_songs(dbfile, typ="song", keys=NEEDED_KEYS):
"""Return a list of info dictionaries for all songs
in a Rhythmbox library database file, with dictionary
keys as given in @keys.
"""
rhythmbox_dbfile = os.path.expanduser(dbfile)
lSongs = []
strmap = {}
# Parse with iterparse; we get the elements when
# they are finished, and can remove them directly after use.
for event, entry in ElementTree.iterparse(rhythmbox_dbfile):
if not (entry.tag == ("entry") and entry.get("type") == typ):
continue
info = {}
for child in entry.getchildren():
if child.tag in keys:
tag = _lookup_string(child.tag, strmap)
text = _lookup_string(child.text, strmap)
info[tag] = text
lSongs.append(info)
entry.clear()
return lSongs
</code></pre>
<p><hr /></p>
<p>Now, I don't understand your expectations, do you have the following expectation?</p>
<pre><code># take one
for event, entry in ElementTree.iterparse(rhythmbox_dbfile):
# parse some entries, then exit loop
# take two
for event, entry in ElementTree.iterparse(rhythmbox_dbfile):
# parse the rest of entries
</code></pre>
<p>Each time you call iterparse you get a new iterator object, reading the file anew! If you want a persistent object with iterator semantics, you have to refer to the same object in both loops (untried code):</p>
<pre><code>#setup
parseiter = iter(ElementTree.iterparse(rhythmbox_dbfile))
# take one
for event, entry in parseiter:
# parse some entries, then exit loop
# take two
for event, entry in parseiter:
# parse the rest of entries
</code></pre>
<p><hr /></p>
<p>I think it can be confusing since different objects have different semantics. A file object will always have an internal state and advance in the file, however you iterate on it. An ElementTree iterparse object apparently not. The crux is to think that when you use a for loop, the for always calls iter() on the thing you iterate over. Here is an experiment comparing ElementTree.iterparse with a file object:</p>
<pre><code>>>> import xml.etree.cElementTree as ElementTree
>>> pth = "/home/ulrik/.local/share/rhythmbox/rhythmdb.xml"
>>> iterparse = ElementTree.iterparse(pth)
>>> iterparse
<iterparse object at 0x483a0890>
>>> iter(iterparse)
<generator object at 0x483a2f08>
>>> iter(iterparse)
<generator object at 0x483a6468>
>>> f = open(pth, "r")
>>> f
<open file '/home/ulrik/.local/share/rhythmbox/rhythmdb.xml', mode 'r' at 0x4809af98>
>>> iter(f)
<open file '/home/ulrik/.local/share/rhythmbox/rhythmdb.xml', mode 'r' at 0x4809af98>
>>> iter(f)
<open file '/home/ulrik/.local/share/rhythmbox/rhythmdb.xml', mode 'r' at 0x4809af98>
</code></pre>
<p>What you see is that each call to iter() on an iterparse object returns a new generator. The file object however, has an internal Operating System state that must be conserved and it its own iterator.</p>
| 14 | 2009-10-03T12:40:25Z | [
"python",
"xml",
"parsing",
"generator"
] |
python: is there an XML parser implemented as a generator? | 1,513,592 | <p>I'd like to parse a big XML file "on the fly". I'd like to use a python generator to perform this. I've tried "iterparse" of "xml.etree.cElementTree" (which is really nice) but still not a generator.</p>
<p>Other suggestions?</p>
| 8 | 2009-10-03T12:14:31Z | 8,693,481 | <p>This is possible with elementtree and incremental parsing:
<a href="http://effbot.org/zone/element-iterparse.htm#incremental-parsing" rel="nofollow">http://effbot.org/zone/element-iterparse.htm#incremental-parsing</a></p>
<pre><code>import xml.etree.cElementTree as etree
for event, elem in etree.iterparse(source):
...
</code></pre>
<p>Easier to use than sax.</p>
| 0 | 2012-01-01T14:10:47Z | [
"python",
"xml",
"parsing",
"generator"
] |
python: is there an XML parser implemented as a generator? | 1,513,592 | <p>I'd like to parse a big XML file "on the fly". I'd like to use a python generator to perform this. I've tried "iterparse" of "xml.etree.cElementTree" (which is really nice) but still not a generator.</p>
<p>Other suggestions?</p>
| 8 | 2009-10-03T12:14:31Z | 11,354,614 | <p>BeautifulSoup is an excellent XML/HTML parser / generator</p>
<p>Check out: <a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">http://www.crummy.com/software/BeautifulSoup/</a></p>
| 0 | 2012-07-06T01:05:05Z | [
"python",
"xml",
"parsing",
"generator"
] |
Python .sort() not working as expected | 1,513,727 | <p>Tackling a few puzzle problems on a quiet Saturday night (wooohoo... not) and am struggling with sort(). The results aren't quite what I expect. The program iterates through every combination from 100 - 999 and checks if the product is a palindome. If it is, append to the list. I need the list sorted :D Here's my program:</p>
<pre><code>list = [] #list of numbers
for x in xrange(100,1000): #loops for first value of combination
for y in xrange(x,1000): #and 2nd value
mult = x*y
reversed = str(mult)[::-1] #reverses the number
if (reversed == str(mult)):
list.append(reversed)
list.sort()
print list[:10]
</code></pre>
<p>which nets:</p>
<pre><code>['101101', '10201', '102201', '102201', '105501', '105501', '106601', '108801',
'108801', '110011']
</code></pre>
<p>Clearly index 0 is larger then 1. Any idea what's going on? I have a feeling it's got something to do with trailing/leading zeroes, but I had a quick look and I can't see the problem.</p>
<p>Bonus points if you know where the puzzle comes from :P</p>
| 3 | 2009-10-03T13:22:03Z | 1,513,735 | <p>You are sorting strings, not numbers. <code>'101101' < '10201'</code> because <code>'1' < '2'</code>. Change <code>list.append(reversed)</code> to <code>list.append(int(reversed))</code> and it will work (or use a different sorting function).</p>
| 16 | 2009-10-03T13:25:20Z | [
"python",
"list",
"sorting"
] |
Python .sort() not working as expected | 1,513,727 | <p>Tackling a few puzzle problems on a quiet Saturday night (wooohoo... not) and am struggling with sort(). The results aren't quite what I expect. The program iterates through every combination from 100 - 999 and checks if the product is a palindome. If it is, append to the list. I need the list sorted :D Here's my program:</p>
<pre><code>list = [] #list of numbers
for x in xrange(100,1000): #loops for first value of combination
for y in xrange(x,1000): #and 2nd value
mult = x*y
reversed = str(mult)[::-1] #reverses the number
if (reversed == str(mult)):
list.append(reversed)
list.sort()
print list[:10]
</code></pre>
<p>which nets:</p>
<pre><code>['101101', '10201', '102201', '102201', '105501', '105501', '106601', '108801',
'108801', '110011']
</code></pre>
<p>Clearly index 0 is larger then 1. Any idea what's going on? I have a feeling it's got something to do with trailing/leading zeroes, but I had a quick look and I can't see the problem.</p>
<p>Bonus points if you know where the puzzle comes from :P</p>
| 3 | 2009-10-03T13:22:03Z | 1,513,736 | <p>You have your numbers stored as strings, so python is sorting them accordingly. So: '101x' comes before '102x' (the same way that 'abcd' will come before 'az').</p>
| 0 | 2009-10-03T13:26:17Z | [
"python",
"list",
"sorting"
] |
Python .sort() not working as expected | 1,513,727 | <p>Tackling a few puzzle problems on a quiet Saturday night (wooohoo... not) and am struggling with sort(). The results aren't quite what I expect. The program iterates through every combination from 100 - 999 and checks if the product is a palindome. If it is, append to the list. I need the list sorted :D Here's my program:</p>
<pre><code>list = [] #list of numbers
for x in xrange(100,1000): #loops for first value of combination
for y in xrange(x,1000): #and 2nd value
mult = x*y
reversed = str(mult)[::-1] #reverses the number
if (reversed == str(mult)):
list.append(reversed)
list.sort()
print list[:10]
</code></pre>
<p>which nets:</p>
<pre><code>['101101', '10201', '102201', '102201', '105501', '105501', '106601', '108801',
'108801', '110011']
</code></pre>
<p>Clearly index 0 is larger then 1. Any idea what's going on? I have a feeling it's got something to do with trailing/leading zeroes, but I had a quick look and I can't see the problem.</p>
<p>Bonus points if you know where the puzzle comes from :P</p>
| 3 | 2009-10-03T13:22:03Z | 1,513,737 | <p>No, it is sorting properly, just that it is sorting <strong>lexographically</strong> and you want <strong>numeric</strong> sorting... so remove the "str()"</p>
| 0 | 2009-10-03T13:26:30Z | [
"python",
"list",
"sorting"
] |
Python .sort() not working as expected | 1,513,727 | <p>Tackling a few puzzle problems on a quiet Saturday night (wooohoo... not) and am struggling with sort(). The results aren't quite what I expect. The program iterates through every combination from 100 - 999 and checks if the product is a palindome. If it is, append to the list. I need the list sorted :D Here's my program:</p>
<pre><code>list = [] #list of numbers
for x in xrange(100,1000): #loops for first value of combination
for y in xrange(x,1000): #and 2nd value
mult = x*y
reversed = str(mult)[::-1] #reverses the number
if (reversed == str(mult)):
list.append(reversed)
list.sort()
print list[:10]
</code></pre>
<p>which nets:</p>
<pre><code>['101101', '10201', '102201', '102201', '105501', '105501', '106601', '108801',
'108801', '110011']
</code></pre>
<p>Clearly index 0 is larger then 1. Any idea what's going on? I have a feeling it's got something to do with trailing/leading zeroes, but I had a quick look and I can't see the problem.</p>
<p>Bonus points if you know where the puzzle comes from :P</p>
| 3 | 2009-10-03T13:22:03Z | 1,513,744 | <p>You're sorting strings, not numbers. Strings compare left-to-right.</p>
| 1 | 2009-10-03T13:28:01Z | [
"python",
"list",
"sorting"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.