title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
list
where does django install in ubuntu
1,095,725
<p>I am looking for the <strong>init</strong>.py file for django. I tried whereis and find, but I get a lot of dirs.</p>
29
2009-07-08T01:38:33Z
14,089,054
<p>Its now at </p> <pre><code>/usr/lib/python2.7/dist-packages/django/.... </code></pre> <p>circa 2012</p>
3
2012-12-30T07:29:48Z
[ "python", "django", "ubuntu" ]
what next after 'dive into python'
1,095,768
<p>I've been meaning to learn another language than java. So I started to poke around with python. I've gone over 'dive into python' so I have a decent knowledge about python now. </p> <p>where do you suggest I go from here? I dont want to go through another advanced book again and would like to use the python knowledge towards building 'something'. </p> <p>I've heard that python is good for web crawling, however, I did not see that in dive into python. Can the community suggest how to use my pythong knowledge towards web crawlers or spiders?</p>
10
2009-07-08T01:50:19Z
1,095,784
<p>Is web crawling something you want to do or just something you think you can accomplish? Python is a good tool for web crawling(see <a href="http://www.drewconway.com/zia/?p=1037" rel="nofollow">here</a> and <a href="http://www.drewconway.com/zia/?p=1096" rel="nofollow">here</a>), but if you really just want ANY project to work on to get more familiar to the language/APIs I'd suggest you pick a project that you have a general interest in regardless. That way it'll be easier to stick with to fruition as you already have an interest in the project in addition to an interest in the language.</p>
3
2009-07-08T01:56:40Z
[ "python" ]
what next after 'dive into python'
1,095,768
<p>I've been meaning to learn another language than java. So I started to poke around with python. I've gone over 'dive into python' so I have a decent knowledge about python now. </p> <p>where do you suggest I go from here? I dont want to go through another advanced book again and would like to use the python knowledge towards building 'something'. </p> <p>I've heard that python is good for web crawling, however, I did not see that in dive into python. Can the community suggest how to use my pythong knowledge towards web crawlers or spiders?</p>
10
2009-07-08T01:50:19Z
1,095,787
<p>You can try my <a href="http://homepage.mac.com/s%5Flott/books/oodesign.html" rel="nofollow">Building Skills in OO Design</a>.</p> <p><a href="http://homepage.mac.com/s_lott/books/oodesign.html" rel="nofollow">http://homepage.mac.com/s_lott/books/oodesign.html</a></p>
7
2009-07-08T01:57:04Z
[ "python" ]
what next after 'dive into python'
1,095,768
<p>I've been meaning to learn another language than java. So I started to poke around with python. I've gone over 'dive into python' so I have a decent knowledge about python now. </p> <p>where do you suggest I go from here? I dont want to go through another advanced book again and would like to use the python knowledge towards building 'something'. </p> <p>I've heard that python is good for web crawling, however, I did not see that in dive into python. Can the community suggest how to use my pythong knowledge towards web crawlers or spiders?</p>
10
2009-07-08T01:50:19Z
1,095,803
<p>I always find making a small game is a nice way to learn a language <a href="http://www.pygame.org/" rel="nofollow">PyGame</a> makes it simple and could help learn more about python. I suggest giving it ago if your that way inclined. </p>
4
2009-07-08T02:02:55Z
[ "python" ]
what next after 'dive into python'
1,095,768
<p>I've been meaning to learn another language than java. So I started to poke around with python. I've gone over 'dive into python' so I have a decent knowledge about python now. </p> <p>where do you suggest I go from here? I dont want to go through another advanced book again and would like to use the python knowledge towards building 'something'. </p> <p>I've heard that python is good for web crawling, however, I did not see that in dive into python. Can the community suggest how to use my pythong knowledge towards web crawlers or spiders?</p>
10
2009-07-08T01:50:19Z
1,095,809
<p>That really kind of depends on what you enjoy, or would like to build. Since you haven't said, I'll recommend something I enjoyed instead. <a href="http://rads.stackoverflow.com/amzn/click/0596529325" rel="nofollow" title="Programming Collective Intelligence">Programming Collective Intelligence</a> by Toby Segaran is a fun book, and the examples are all in Python. It might be more interesting to you -- if nothing else, it would give your web crawler something to do with the pages it gathers.</p> <p>Edit: Fusspawn's suggestion of PyGame is very good, if don't want any more books and just want to "dive in" to something.</p>
12
2009-07-08T02:05:48Z
[ "python" ]
what next after 'dive into python'
1,095,768
<p>I've been meaning to learn another language than java. So I started to poke around with python. I've gone over 'dive into python' so I have a decent knowledge about python now. </p> <p>where do you suggest I go from here? I dont want to go through another advanced book again and would like to use the python knowledge towards building 'something'. </p> <p>I've heard that python is good for web crawling, however, I did not see that in dive into python. Can the community suggest how to use my pythong knowledge towards web crawlers or spiders?</p>
10
2009-07-08T01:50:19Z
1,095,814
<p>Find an interesting open source project to participate in. You could start looking on <a href="http://pythonsource.com/" rel="nofollow">pythonsource</a> or <a href="http://sourceforge.net/" rel="nofollow">sourceforge</a>.</p>
3
2009-07-08T02:06:45Z
[ "python" ]
what next after 'dive into python'
1,095,768
<p>I've been meaning to learn another language than java. So I started to poke around with python. I've gone over 'dive into python' so I have a decent knowledge about python now. </p> <p>where do you suggest I go from here? I dont want to go through another advanced book again and would like to use the python knowledge towards building 'something'. </p> <p>I've heard that python is good for web crawling, however, I did not see that in dive into python. Can the community suggest how to use my pythong knowledge towards web crawlers or spiders?</p>
10
2009-07-08T01:50:19Z
1,095,821
<p>The <a href="http://svn.python.org/view/python/trunk/Tools/webchecker/" rel="nofollow">Tools/webchecker/</a> directory, which should be in your Python distribution (otherwise you can get it via the link I gave), is a start -- with lots of limitations (no threading except in <code>wsgui.py</code>, no async operation, ...), but removing some of them would be a great learning experience!</p> <p>A vastly superior spidering system could be built on top of Twisted, e.g. starting with the snippet at the bottom of <a href="http://twistedmatrix.com/pipermail/twisted-python/2003-July/005063.html" rel="nofollow">this mail</a> (which only gets one page, but in the proper asynchronous way!) and adding the other functionality you see exemplified in webchecker (parse and respect robots.txt, get links from pages, etc, etc).</p>
1
2009-07-08T02:09:40Z
[ "python" ]
what next after 'dive into python'
1,095,768
<p>I've been meaning to learn another language than java. So I started to poke around with python. I've gone over 'dive into python' so I have a decent knowledge about python now. </p> <p>where do you suggest I go from here? I dont want to go through another advanced book again and would like to use the python knowledge towards building 'something'. </p> <p>I've heard that python is good for web crawling, however, I did not see that in dive into python. Can the community suggest how to use my pythong knowledge towards web crawlers or spiders?</p>
10
2009-07-08T01:50:19Z
1,096,016
<p>To get started with web crawling, consider the Scrapy framework.</p> <p><a href="http://scrapy.org/" rel="nofollow">http://scrapy.org/</a></p> <p>"Scrapy is a high level scraping and web crawling framework for writing spiders to crawl and parse web pages for all kinds of purposes, from information retrieval to monitoring or testing web sites."</p> <p>It's still edging towards a first release, but is usable and has decent documentation. </p> <p>For very basic web scraping, check out Mechanize (for basic web "browsing") and BeautifulSoup (for parsing "html soup"):</p> <p><a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">http://wwwsearch.sourceforge.net/mechanize/</a></p> <p><a href="http://www.crummy.com/software/BeautifulSoup/" rel="nofollow">http://www.crummy.com/software/BeautifulSoup/</a></p> <p>One fun thing to do would be to combine these interests with some natural language processing projects. The NLTK book recently published by O'Reilly is available online as well:</p> <p><a href="http://www.nltk.org/book" rel="nofollow">http://www.nltk.org/book</a></p> <p>Lots of fun to be had combining these interests. :-)</p>
4
2009-07-08T03:31:40Z
[ "python" ]
what next after 'dive into python'
1,095,768
<p>I've been meaning to learn another language than java. So I started to poke around with python. I've gone over 'dive into python' so I have a decent knowledge about python now. </p> <p>where do you suggest I go from here? I dont want to go through another advanced book again and would like to use the python knowledge towards building 'something'. </p> <p>I've heard that python is good for web crawling, however, I did not see that in dive into python. Can the community suggest how to use my pythong knowledge towards web crawlers or spiders?</p>
10
2009-07-08T01:50:19Z
1,096,045
<p>If you like math try learning Python by solving <a href="http://projecteuler.net/" rel="nofollow">Project Euler problems</a> using python. Each problem is not too much code and it helped me increase my python skills.</p>
5
2009-07-08T03:49:17Z
[ "python" ]
what next after 'dive into python'
1,095,768
<p>I've been meaning to learn another language than java. So I started to poke around with python. I've gone over 'dive into python' so I have a decent knowledge about python now. </p> <p>where do you suggest I go from here? I dont want to go through another advanced book again and would like to use the python knowledge towards building 'something'. </p> <p>I've heard that python is good for web crawling, however, I did not see that in dive into python. Can the community suggest how to use my pythong knowledge towards web crawlers or spiders?</p>
10
2009-07-08T01:50:19Z
1,096,106
<p>If you wanna "advanced book", I recommend Alex's <a href="http://oreilly.com/catalog/9780596100469/" rel="nofollow">Python in a Nutshell, Second Edition</a>, learn quite a lot from the book, and Tarek's <a href="http://www.packtpub.com/expert-python-programming/book" rel="nofollow">Expert Python Programming</a>,we all know it's a advanced book for it's title:) .<br /> For read some open source project, recommend <a href="http://www.sqlalchemy.org/" rel="nofollow">SQLAlchemy</a> and <a href="http://www.djangoproject.com/" rel="nofollow">Django</a>.<br /> Maybe try to start you own project is the best way.</p>
0
2009-07-08T04:19:19Z
[ "python" ]
what next after 'dive into python'
1,095,768
<p>I've been meaning to learn another language than java. So I started to poke around with python. I've gone over 'dive into python' so I have a decent knowledge about python now. </p> <p>where do you suggest I go from here? I dont want to go through another advanced book again and would like to use the python knowledge towards building 'something'. </p> <p>I've heard that python is good for web crawling, however, I did not see that in dive into python. Can the community suggest how to use my pythong knowledge towards web crawlers or spiders?</p>
10
2009-07-08T01:50:19Z
1,096,469
<p>If you want to expand beyond web crawling and don't want to start a your own project (or don't know what to do), check out <a href="http://www.pythonchallenge.com/" rel="nofollow">The Python Challenge</a>. It's a game where you have to solve puzzles with a bit of python code. I really enjoyed it.</p>
4
2009-07-08T06:50:53Z
[ "python" ]
what next after 'dive into python'
1,095,768
<p>I've been meaning to learn another language than java. So I started to poke around with python. I've gone over 'dive into python' so I have a decent knowledge about python now. </p> <p>where do you suggest I go from here? I dont want to go through another advanced book again and would like to use the python knowledge towards building 'something'. </p> <p>I've heard that python is good for web crawling, however, I did not see that in dive into python. Can the community suggest how to use my pythong knowledge towards web crawlers or spiders?</p>
10
2009-07-08T01:50:19Z
1,098,152
<p>Others have said it but I'll repeat: work on something you are interested in or it won't be fun. </p> <p>If you do decide that a crawler would be fun, take a look at <a href="http://code.google.com/p/google-kongulo/" rel="nofollow"><code>google-kongulo</code></a>, web spider plugin for Google desktop search. The code is quite short and well-written, so this might make a good base for when you decide what you want to crawl. </p>
0
2009-07-08T13:41:27Z
[ "python" ]
what next after 'dive into python'
1,095,768
<p>I've been meaning to learn another language than java. So I started to poke around with python. I've gone over 'dive into python' so I have a decent knowledge about python now. </p> <p>where do you suggest I go from here? I dont want to go through another advanced book again and would like to use the python knowledge towards building 'something'. </p> <p>I've heard that python is good for web crawling, however, I did not see that in dive into python. Can the community suggest how to use my pythong knowledge towards web crawlers or spiders?</p>
10
2009-07-08T01:50:19Z
1,099,195
<p>If you're specifically interested in crawling the Web, check out the three-part talk called "Scrape the Web" given at PyCon 2009. It's part of this <a href="http://advocacy.python.org/podcasts/pycon.rss" rel="nofollow">RSS feed</a>.</p>
0
2009-07-08T16:34:03Z
[ "python" ]
what next after 'dive into python'
1,095,768
<p>I've been meaning to learn another language than java. So I started to poke around with python. I've gone over 'dive into python' so I have a decent knowledge about python now. </p> <p>where do you suggest I go from here? I dont want to go through another advanced book again and would like to use the python knowledge towards building 'something'. </p> <p>I've heard that python is good for web crawling, however, I did not see that in dive into python. Can the community suggest how to use my pythong knowledge towards web crawlers or spiders?</p>
10
2009-07-08T01:50:19Z
12,092,279
<p>Read <em>Dive Into Python</em> again, it discusses <a href="http://www.diveintopython.net/html_processing/index.html" rel="nofollow">HTML processing</a> and <a href="http://www.diveintopython.net/http_web_services/index.html" rel="nofollow">HTTP web services</a> in chapters 8 and 11.</p>
0
2012-08-23T13:06:12Z
[ "python" ]
Comparing and updating array values in Python
1,096,003
<p>I'm developing a Sirius XM radio desktop player in Python, in which I want the ability to display a table of all the channels and what is currently playing on each of them. This channel data is obtained from their website as a JSON string. </p> <p>I'm looking for the best data structure that would allow the cleanest way to compare and update the channel data. </p> <p>Arrays are problematic because I would want to be able to refer to an item by its channel number, but if I manually set each index I lose the ability to sort the array, as it would remap the index sequentially (while the channels aren't in a perfect sequence).</p> <p>The other possibility (I can see) is using Sqlite, however I'm not sure if this is overkill.</p> <p>is there a cleaner approach for referring and maintaining this data?</p>
1
2009-07-08T03:26:44Z
1,096,014
<p>Why not a dict, with channel number as the key and "what's playing" as the value? Easy to make from JSON, easy to sort (<code>sorted(thedict)</code> sorts by channel, <code>sorted(thedict, key=thedict.get)</code> sorts by value -- all operations are pretty easy (if you specify better exactly what operations you want to do I'll be happy to show corresponding code samples).</p>
4
2009-07-08T03:30:44Z
[ "python", "arrays", "list", "data-structures" ]
Comparing and updating array values in Python
1,096,003
<p>I'm developing a Sirius XM radio desktop player in Python, in which I want the ability to display a table of all the channels and what is currently playing on each of them. This channel data is obtained from their website as a JSON string. </p> <p>I'm looking for the best data structure that would allow the cleanest way to compare and update the channel data. </p> <p>Arrays are problematic because I would want to be able to refer to an item by its channel number, but if I manually set each index I lose the ability to sort the array, as it would remap the index sequentially (while the channels aren't in a perfect sequence).</p> <p>The other possibility (I can see) is using Sqlite, however I'm not sure if this is overkill.</p> <p>is there a cleaner approach for referring and maintaining this data?</p>
1
2009-07-08T03:26:44Z
1,096,290
<p>In this kind of situation, I often use a dict. It looks to me as the simplest solution. </p> <p>I think that Sqlite will cause some unecessary overhead. However it would give you persistence of data. But I guess that your app needs to be online so you don't really need persistence</p>
2
2009-07-08T05:46:11Z
[ "python", "arrays", "list", "data-structures" ]
Override namespace in Python
1,096,216
<p>Say there is a folder, '/home/user/temp/a40bd22344'. The name is completely random and changes in every iteration. I need to be able to import this folder in Python using a fixed name, say 'project'. I know I can add this folder to sys.path to enable import lookup, but is there a way to replace 'a40bd22344' with 'project'?</p> <p>Maybe some clever hacks in <strong>init</strong>.py?</p> <p>Added: </p> <p>It needs to be global - that is, other scripts loading 'project' via the standard:</p> <pre><code>import project </code></pre> <p>Have to work properly, loading a40bd22344 instead.</p>
13
2009-07-08T05:20:31Z
1,096,220
<p>Sure, <code>project = __import__('a40bd22344')</code> after <code>sys.path</code> is set properly will just work.</p> <p>Suppose you want to do it in a function taking the full path as an argument and setting the <em>global</em> import of <code>project</code> properly (as well as magically making <code>import project</code> work afterwards in other modules). Piece of cake:</p> <pre><code>def weirdimport(fullpath): global project import os import sys sys.path.append(os.path.dirname(fullpath)) try: project = __import__(os.path.basename(fullpath)) sys.modules['project'] = project finally: del sys.path[-1] </code></pre> <p>this also leaves sys.path as it found it.</p>
17
2009-07-08T05:22:28Z
[ "python", "python-import" ]
Override namespace in Python
1,096,216
<p>Say there is a folder, '/home/user/temp/a40bd22344'. The name is completely random and changes in every iteration. I need to be able to import this folder in Python using a fixed name, say 'project'. I know I can add this folder to sys.path to enable import lookup, but is there a way to replace 'a40bd22344' with 'project'?</p> <p>Maybe some clever hacks in <strong>init</strong>.py?</p> <p>Added: </p> <p>It needs to be global - that is, other scripts loading 'project' via the standard:</p> <pre><code>import project </code></pre> <p>Have to work properly, loading a40bd22344 instead.</p>
13
2009-07-08T05:20:31Z
1,096,247
<p>Here's one way to do it, without touching sys.path, using the <code>imp</code> module in Python:</p> <pre><code>import imp f, filename, desc = imp.find_module('a40bd22344', ['/home/user/temp/']) project = imp.load_module('a40bd22344', f, filename, desc) project.some_func() </code></pre> <p>Here is a link to some good documentation on the <code>imp</code> module:</p> <ul> <li><em><a href="http://docs.python.org/library/imp.html" rel="nofollow">imp — Access the import internals</a></em></li> </ul>
21
2009-07-08T05:33:14Z
[ "python", "python-import" ]
Override namespace in Python
1,096,216
<p>Say there is a folder, '/home/user/temp/a40bd22344'. The name is completely random and changes in every iteration. I need to be able to import this folder in Python using a fixed name, say 'project'. I know I can add this folder to sys.path to enable import lookup, but is there a way to replace 'a40bd22344' with 'project'?</p> <p>Maybe some clever hacks in <strong>init</strong>.py?</p> <p>Added: </p> <p>It needs to be global - that is, other scripts loading 'project' via the standard:</p> <pre><code>import project </code></pre> <p>Have to work properly, loading a40bd22344 instead.</p>
13
2009-07-08T05:20:31Z
1,097,237
<p>You first import it with <strong>import</strong>:</p> <pre><code>&gt;&gt;&gt; __import__('temp/a40bd22344') &lt;module 'temp/a40bd22344' from 'temp/a40bd22344/__init__.py'&gt; </code></pre> <p>Then you make sure that this module gets known to Python as <code>project</code>:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; sys.modules['project'] = sys.modules.pop('temp/a40bd22344') </code></pre> <p>After this, anything importing project in the current Python session will get the original module</p> <pre><code>&gt;&gt;&gt; import project &gt;&gt;&gt; project &lt;module 'temp/a40bd22344' from 'temp/a40bd22344/__init__.py'&gt; </code></pre> <p>This will work also for sub-modules: if you have a foobar.py in the same location you'll get</p> <pre><code>&gt;&gt;&gt; import project.foobar &gt;&gt;&gt; project.foobar &lt;module 'project.foobar' from 'temp/a40bd22344/foobar.py'&gt; </code></pre> <p><strong>Addendum.</strong> Here's what I'm running:</p> <pre><code>&gt;&gt;&gt; print sys.version 2.5.2 (r252:60911, Jul 31 2008, 17:28:52) [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] </code></pre>
19
2009-07-08T10:21:15Z
[ "python", "python-import" ]
Pylons/Routes rewrite POST or GET to fancy URL
1,096,300
<p><strong>The behavior I propose:</strong></p> <p>A user loads up my "search" page, www.site.com/search, types their query into a form, clicks submit, and then ends up at www.site.com/search/the+query instead of www.site.com/search?q=the+query. I've gone through a lot of the Pylons documentation already and just finished reading the Routes documentation and am wondering if this can/should happen at the Routes layer. I have already set up my application to perform a search when given www.site.com/search/the+query, but can not figure out how to send a form to this destination.</p> <p>Or is this something that should happen inside a controller with a redirect_to()?</p> <p>Or somewhere else?</p> <p><strong>Followup:</strong></p> <p>This is less an actual "set in stone" desire right now and more a curiosity for brainstorming future features. I'm designing an application which uses a Wikipedia dump and have observed that when a user performs a search on Wikipedia and the search isn't too ambiguous it redirects directly to an article link: en.wikipedia.org/wiki/Apple. It is actually performing an in-between HTTP 302 redirect step, and I am just curious if there's a more elegant/cute way of doing this in Pylons.</p>
2
2009-07-08T05:49:59Z
1,096,315
<p>HTML forms are designed to go to a specific URL with a query string (<code>?q=</code>) or an equivalent body in a <code>POST</code> -- either you write clever and subtle Javascript to intercept the form submission and rewrite it in your preferred weird way, or use <code>redirect_to</code> (and the latter will take some doing).</p> <p>But why do you need such weird behavior rather than just following the standard?! Please explain your use case in terms of application-level needs...!</p>
2
2009-07-08T05:56:42Z
[ "python", "routes", "pylons" ]
Pylons/Routes rewrite POST or GET to fancy URL
1,096,300
<p><strong>The behavior I propose:</strong></p> <p>A user loads up my "search" page, www.site.com/search, types their query into a form, clicks submit, and then ends up at www.site.com/search/the+query instead of www.site.com/search?q=the+query. I've gone through a lot of the Pylons documentation already and just finished reading the Routes documentation and am wondering if this can/should happen at the Routes layer. I have already set up my application to perform a search when given www.site.com/search/the+query, but can not figure out how to send a form to this destination.</p> <p>Or is this something that should happen inside a controller with a redirect_to()?</p> <p>Or somewhere else?</p> <p><strong>Followup:</strong></p> <p>This is less an actual "set in stone" desire right now and more a curiosity for brainstorming future features. I'm designing an application which uses a Wikipedia dump and have observed that when a user performs a search on Wikipedia and the search isn't too ambiguous it redirects directly to an article link: en.wikipedia.org/wiki/Apple. It is actually performing an in-between HTTP 302 redirect step, and I am just curious if there's a more elegant/cute way of doing this in Pylons.</p>
2
2009-07-08T05:49:59Z
1,097,943
<p>You can send whatever content you want for any URL, but if you want a particular URL to appear in the browser's address bar, you have to use a redirect. This is independent of whether you use Pylons, Django or Rails on the server side.</p> <p>In the handling for <code>/search</code> (whether <code>POST</code> or <code>GET</code>), one would normally run the query in the back end, and if there was only one search result (or one overwhelmingly relevant result) you would redirect to that result, otherwise to a page showing links to the top N results. That's just normal practice, AFAIK.</p>
2
2009-07-08T13:03:58Z
[ "python", "routes", "pylons" ]
How to make urllib2 requests through Tor in Python?
1,096,379
<p>I'm trying to crawl websites using a crawler written in Python. I want to integrate Tor with Python meaning I want to crawl the site anonymously using Tor.</p> <p>I tried doing this. It doesn't seem to work. I checked my IP it is still the same as the one before I used tor. I checked it via python.</p> <pre><code>import urllib2 proxy_handler = urllib2.ProxyHandler({"tcp":"http://127.0.0.1:9050"}) opener = urllib2.build_opener(proxy_handler) urllib2.install_opener(opener) </code></pre>
41
2009-07-08T06:22:08Z
1,096,419
<p>Perhaps you're having some network connectivity issues? The above script worked for me (I substituted a different URL - I used <code>http://stackoverflow.com/</code> - and I get the page as expected:</p> <pre><code>&lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd" &gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Stack Overflow&lt;/title&gt; &lt;link rel="stylesheet" href="/content/all.css?v=3856"&gt; </code></pre> <p>(etc.)</p>
1
2009-07-08T06:34:44Z
[ "python", "tor" ]
How to make urllib2 requests through Tor in Python?
1,096,379
<p>I'm trying to crawl websites using a crawler written in Python. I want to integrate Tor with Python meaning I want to crawl the site anonymously using Tor.</p> <p>I tried doing this. It doesn't seem to work. I checked my IP it is still the same as the one before I used tor. I checked it via python.</p> <pre><code>import urllib2 proxy_handler = urllib2.ProxyHandler({"tcp":"http://127.0.0.1:9050"}) opener = urllib2.build_opener(proxy_handler) urllib2.install_opener(opener) </code></pre>
41
2009-07-08T06:22:08Z
1,097,697
<p>Using privoxy as http-proxy in front of tor works for me - here's a crawler-template:</p> <pre><code> import urllib2 import httplib from BeautifulSoup import BeautifulSoup from time import sleep class Scraper(object): def __init__(self, options, args): if options.proxy is None: options.proxy = "http://localhost:8118/" self._open = self._get_opener(options.proxy) def _get_opener(self, proxy): proxy_handler = urllib2.ProxyHandler({'http': proxy}) opener = urllib2.build_opener(proxy_handler) return opener.open def get_soup(self, url): soup = None while soup is None: try: request = urllib2.Request(url) request.add_header('User-Agent', 'foo bar useragent') soup = BeautifulSoup(self._open(request)) except (httplib.IncompleteRead, httplib.BadStatusLine, urllib2.HTTPError, ValueError, urllib2.URLError), err: sleep(1) return soup class PageType(Scraper): _URL_TEMPL = "http://foobar.com/baz/%s" def items_from_page(self, url): nextpage = None soup = self.get_soup(url) items = [] for item in soup.findAll("foo"): items.append(item["bar"]) nexpage = item["href"] return nextpage, items def get_items(self): nextpage, items = self._categories_from_page(self._START_URL % "start.html") while nextpage is not None: nextpage, newitems = self.items_from_page(self._URL_TEMPL % nextpage) items.extend(newitems) return items() pt = PageType() print pt.get_items() </code></pre>
2
2009-07-08T12:13:35Z
[ "python", "tor" ]
How to make urllib2 requests through Tor in Python?
1,096,379
<p>I'm trying to crawl websites using a crawler written in Python. I want to integrate Tor with Python meaning I want to crawl the site anonymously using Tor.</p> <p>I tried doing this. It doesn't seem to work. I checked my IP it is still the same as the one before I used tor. I checked it via python.</p> <pre><code>import urllib2 proxy_handler = urllib2.ProxyHandler({"tcp":"http://127.0.0.1:9050"}) opener = urllib2.build_opener(proxy_handler) urllib2.install_opener(opener) </code></pre>
41
2009-07-08T06:22:08Z
2,015,649
<p>You are trying to connect to a SOCKS port - Tor rejects any non-SOCKS traffic. You can connect through a middleman - Privoxy - using Port 8118.</p> <p>Example:</p> <pre><code>proxy_support = urllib2.ProxyHandler({"http" : "127.0.0.1:8118"}) opener = urllib2.build_opener(proxy_support) opener.addheaders = [('User-agent', 'Mozilla/5.0')] print opener.open('http://www.google.com').read() </code></pre> <p>Also please note properties passed to ProxyHandler, no http prefixing the ip:port</p>
19
2010-01-06T19:37:37Z
[ "python", "tor" ]
How to make urllib2 requests through Tor in Python?
1,096,379
<p>I'm trying to crawl websites using a crawler written in Python. I want to integrate Tor with Python meaning I want to crawl the site anonymously using Tor.</p> <p>I tried doing this. It doesn't seem to work. I checked my IP it is still the same as the one before I used tor. I checked it via python.</p> <pre><code>import urllib2 proxy_handler = urllib2.ProxyHandler({"tcp":"http://127.0.0.1:9050"}) opener = urllib2.build_opener(proxy_handler) urllib2.install_opener(opener) </code></pre>
41
2009-07-08T06:22:08Z
9,037,155
<p>Here is a code for downloading files using tor proxy in python: (update url)</p> <pre><code>import urllib2 url = "http://www.disneypicture.net/data/media/17/Donald_Duck2.gif" proxy = urllib2.ProxyHandler({'http': '127.0.0.1:8118'}) opener = urllib2.build_opener(proxy) urllib2.install_opener(opener) file_name = url.split('/')[-1] u = urllib2.urlopen(url) f = open(file_name, 'wb') meta = u.info() file_size = int(meta.getheaders("Content-Length")[0]) print "Downloading: %s Bytes: %s" % (file_name, file_size) file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break file_size_dl += len(buffer) f.write(buffer) status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size) status = status + chr(8)*(len(status)+1) print status, f.close() </code></pre>
2
2012-01-27T17:02:29Z
[ "python", "tor" ]
How to make urllib2 requests through Tor in Python?
1,096,379
<p>I'm trying to crawl websites using a crawler written in Python. I want to integrate Tor with Python meaning I want to crawl the site anonymously using Tor.</p> <p>I tried doing this. It doesn't seem to work. I checked my IP it is still the same as the one before I used tor. I checked it via python.</p> <pre><code>import urllib2 proxy_handler = urllib2.ProxyHandler({"tcp":"http://127.0.0.1:9050"}) opener = urllib2.build_opener(proxy_handler) urllib2.install_opener(opener) </code></pre>
41
2009-07-08T06:22:08Z
30,404,083
<p>The following code is 100% working on Python 3.4</p> <p>(you need to keep TOR Browser open wil using this code)</p> <p>This script connects to TOR through socks5 get the IP from checkip.dyn.com, change identity and resend the request to get a the new IP (loops 10 times)</p> <p>You need to install the appropriate libraries to get this working. (Enjoy and don't abuse)</p> <pre><code>import socks import socket import time from stem.control import Controller from stem import Signal import requests from bs4 import BeautifulSoup err = 0 counter = 0 url = "checkip.dyn.com" with Controller.from_port(port = 9151) as controller: try: controller.authenticate() socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9150) socket.socket = socks.socksocket while counter &lt; 10: r = requests.get("http://checkip.dyn.com") soup = BeautifulSoup(r.content) print(soup.find("body").text) counter = counter + 1 #wait till next identity will be available controller.signal(Signal.NEWNYM) time.sleep(controller.get_newnym_wait()) except requests.HTTPError: print("Could not reach URL") err = err + 1 print("Used " + str(counter) + " IPs and got " + str(err) + " errors") </code></pre>
2
2015-05-22T19:01:22Z
[ "python", "tor" ]
How to make urllib2 requests through Tor in Python?
1,096,379
<p>I'm trying to crawl websites using a crawler written in Python. I want to integrate Tor with Python meaning I want to crawl the site anonymously using Tor.</p> <p>I tried doing this. It doesn't seem to work. I checked my IP it is still the same as the one before I used tor. I checked it via python.</p> <pre><code>import urllib2 proxy_handler = urllib2.ProxyHandler({"tcp":"http://127.0.0.1:9050"}) opener = urllib2.build_opener(proxy_handler) urllib2.install_opener(opener) </code></pre>
41
2009-07-08T06:22:08Z
30,649,544
<p>Tor is a socks proxy. Connecting to it directly with <a href="http://sacharya.com/crawling-anonymously-with-tor-in-python/" rel="nofollow">the example you cite</a> fails with "urlopen error Tunnel connection failed: 501 Tor is not an HTTP Proxy". As others have mentioned you can get around this with Privoxy.</p> <p>Alternatively you can also use PycURL or SocksiPy. For examples of using both with tor see...</p> <p><a href="https://stem.torproject.org/tutorials/to_russia_with_love.html" rel="nofollow">https://stem.torproject.org/tutorials/to_russia_with_love.html</a></p>
0
2015-06-04T16:41:28Z
[ "python", "tor" ]
How to make urllib2 requests through Tor in Python?
1,096,379
<p>I'm trying to crawl websites using a crawler written in Python. I want to integrate Tor with Python meaning I want to crawl the site anonymously using Tor.</p> <p>I tried doing this. It doesn't seem to work. I checked my IP it is still the same as the one before I used tor. I checked it via python.</p> <pre><code>import urllib2 proxy_handler = urllib2.ProxyHandler({"tcp":"http://127.0.0.1:9050"}) opener = urllib2.build_opener(proxy_handler) urllib2.install_opener(opener) </code></pre>
41
2009-07-08T06:22:08Z
33,875,868
<p>Even though this is an old post, answering because no one seems to have mentioned the <a href="https://pypi.python.org/pypi/requesocks" rel="nofollow"><code>requesocks</code></a> library.</p> <p>It is basically a port of the <a href="http://docs.python-requests.org/en/latest/" rel="nofollow"><code>requests</code></a> library. Please note that the library is an old fork (last updated 2013-03-25) and may not have the same functionalities as the latest requests library.</p> <p><strong>Installation</strong> -</p> <pre><code>pip install requesocks </code></pre> <p><strong>Basic usage</strong> -</p> <pre><code># Assuming that Tor is up &amp; running import requesocks session = requesocks.session() # Tor uses the 9050 port as the default socks port session.proxies = {'http': 'socks5://127.0.0.1:9050', 'https': 'socks5://127.0.0.1:9050'} # Make a request through the Tor connection # IP visible through Tor print session.get("http://httpbin.org/ip").text # Above should print an IP different than your public IP # Following prints your normal public IP import requests print requests.get("http://httpbin.org/ip").text </code></pre>
2
2015-11-23T16:28:09Z
[ "python", "tor" ]
How to make urllib2 requests through Tor in Python?
1,096,379
<p>I'm trying to crawl websites using a crawler written in Python. I want to integrate Tor with Python meaning I want to crawl the site anonymously using Tor.</p> <p>I tried doing this. It doesn't seem to work. I checked my IP it is still the same as the one before I used tor. I checked it via python.</p> <pre><code>import urllib2 proxy_handler = urllib2.ProxyHandler({"tcp":"http://127.0.0.1:9050"}) opener = urllib2.build_opener(proxy_handler) urllib2.install_opener(opener) </code></pre>
41
2009-07-08T06:22:08Z
34,493,721
<pre><code>pip install PySocks </code></pre> <p>Then:</p> <pre><code>import socket import socks import urllib2 ipcheck_url = 'http://checkip.amazonaws.com/' # Actual IP. print(urllib2.urlopen(ipcheck_url).read()) # Tor IP. socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 9050) socket.socket = socks.socksocket print(urllib2.urlopen(ipcheck_url).read()) </code></pre> <p>Using just <code>urllib2.ProxyHandler</code> as in <a href="http://stackoverflow.com/a/2015649/895245">http://stackoverflow.com/a/2015649/895245</a> fails with:</p> <pre><code>Tor is not an HTTP Proxy </code></pre> <p>Mentioned at: <a href="http://stackoverflow.com/questions/2317849/how-can-i-use-a-socks-4-5-proxy-with-urllib2">How can I use a SOCKS 4/5 proxy with urllib2?</a></p> <p>Tested on Ubuntu 15.10, Tor 0.2.6.10, Python 2.7.10.</p>
3
2015-12-28T12:40:16Z
[ "python", "tor" ]
What is the easiest way to handle dates/times in Python?
1,096,396
<p>My use case is that I'm just making a website that I want people all over the world to be able to use, and I want to be able to say things like "This happened at 5:33pm on October 5" and also "This happened 5 minutes ago," etc.</p> <p>Should I use the datetime module? Or just strftime? Or something fancier that isn't part of the std distro of Python?</p>
1
2009-07-08T06:29:03Z
1,096,409
<p>Take a look at the dateutil module:</p> <p><a href="http://labix.org/python-dateutil" rel="nofollow">http://labix.org/python-dateutil</a></p> <p>It's good at doing the types of things you're looking for - see some of the examples in the documentation.</p>
2
2009-07-08T06:32:55Z
[ "python", "datetime" ]
What is the easiest way to handle dates/times in Python?
1,096,396
<p>My use case is that I'm just making a website that I want people all over the world to be able to use, and I want to be able to say things like "This happened at 5:33pm on October 5" and also "This happened 5 minutes ago," etc.</p> <p>Should I use the datetime module? Or just strftime? Or something fancier that isn't part of the std distro of Python?</p>
1
2009-07-08T06:29:03Z
1,096,413
<p>If you're going to use <code>datetime</code>, make sure you read this recent and most excellent article: <a href="http://www.enricozini.org/2009/debian/using-python-datetime/" rel="nofollow">Tips on using python's datetime module</a>. <code>datetime</code> will take care of most of the niceties of handling time arithmetic, but it won't give you the English-language pretty printing you're looking for.</p>
1
2009-07-08T06:33:22Z
[ "python", "datetime" ]
What is the easiest way to handle dates/times in Python?
1,096,396
<p>My use case is that I'm just making a website that I want people all over the world to be able to use, and I want to be able to say things like "This happened at 5:33pm on October 5" and also "This happened 5 minutes ago," etc.</p> <p>Should I use the datetime module? Or just strftime? Or something fancier that isn't part of the std distro of Python?</p>
1
2009-07-08T06:29:03Z
1,096,415
<p>I have always been very happy using the datetime package. You get a lot of stuff for free, and it's pretty easy to create datetime objects as well, calculate duration ect.</p>
0
2009-07-08T06:33:46Z
[ "python", "datetime" ]
What is the easiest way to handle dates/times in Python?
1,096,396
<p>My use case is that I'm just making a website that I want people all over the world to be able to use, and I want to be able to say things like "This happened at 5:33pm on October 5" and also "This happened 5 minutes ago," etc.</p> <p>Should I use the datetime module? Or just strftime? Or something fancier that isn't part of the std distro of Python?</p>
1
2009-07-08T06:29:03Z
1,096,445
<p>There is also the <a href="http://docs.python.org/library/time.html" rel="nofollow">Time module</a>.</p>
0
2009-07-08T06:42:28Z
[ "python", "datetime" ]
What is the easiest way to handle dates/times in Python?
1,096,396
<p>My use case is that I'm just making a website that I want people all over the world to be able to use, and I want to be able to say things like "This happened at 5:33pm on October 5" and also "This happened 5 minutes ago," etc.</p> <p>Should I use the datetime module? Or just strftime? Or something fancier that isn't part of the std distro of Python?</p>
1
2009-07-08T06:29:03Z
1,096,455
<p>The datetime module in Python will allow you to get/set/manipulate dates and times. A question about relative date formatting in Python has already been asked: <a href="http://stackoverflow.com/questions/410221/natural-relative-days-in-python">Stack Overflow Post</a> but with very little responce. </p>
1
2009-07-08T06:47:06Z
[ "python", "datetime" ]
What is the easiest way to handle dates/times in Python?
1,096,396
<p>My use case is that I'm just making a website that I want people all over the world to be able to use, and I want to be able to say things like "This happened at 5:33pm on October 5" and also "This happened 5 minutes ago," etc.</p> <p>Should I use the datetime module? Or just strftime? Or something fancier that isn't part of the std distro of Python?</p>
1
2009-07-08T06:29:03Z
1,096,495
<p>You may have a look at Django's <a href="http://docs.djangoproject.com/en/dev/ref/contrib/humanize/#ref-contrib-humanize" rel="nofollow">humanize module</a>.<br /> It is part of Django, but I think it would be quite easy to adapt it to your needs.</p>
2
2009-07-08T06:58:00Z
[ "python", "datetime" ]
What is the easiest way to handle dates/times in Python?
1,096,396
<p>My use case is that I'm just making a website that I want people all over the world to be able to use, and I want to be able to say things like "This happened at 5:33pm on October 5" and also "This happened 5 minutes ago," etc.</p> <p>Should I use the datetime module? Or just strftime? Or something fancier that isn't part of the std distro of Python?</p>
1
2009-07-08T06:29:03Z
1,096,688
<p>Try <a href="http://jehiah.cz/archive/printing-relative-dates-in-python" rel="nofollow">relativeDates Module</a> module. It exactly brings you the stuff you wanted.</p>
1
2009-07-08T07:57:58Z
[ "python", "datetime" ]
Display triangles in 3D using Python
1,096,476
<p>Disclaimer: The context is a project I'm working on as part of my Master's degree. I guess it qualifies as homework.</p> <p><hr /></p> <h2>Introduction</h2> <p>(feel free to skip to the bottom line)</p> <p>Curved 3D surfaces are commonly displayed as a large set of very small triangles. Each triangle has the following properties:</p> <ul> <li>3 corners</li> <li>uniform color</li> </ul> <p>Such that when they're all displayed together, you get the illusion of a smooth surface. This is similar to the way pixels of a uniform color are used to get the illusion of a smooth image.</p> <p>My project involves generating and displaying all the triangles that make up a given surfaces. Assuming that I have code that generates a set of triangles, how can I display them?</p> <p>The code that generates the set of triangles is in Python. I'd prefer to use Python to display the triangles, but I'm not picky.</p> <p><hr /></p> <h2>Bottom line</h2> <p>How can I display a triangle in 3D using Python, when the input is the coordinates of the 3 corners of the triangle.</p>
1
2009-07-08T06:52:18Z
1,096,521
<p>Well, that depends, very much, like which OS you are using, do you need to be portable, etc.</p> <p>But a generic answer is probably to use something like OpenGL, which is a portable API, and has Python bindings. <a href="http://pyopengl.sourceforge.net/" rel="nofollow">http://pyopengl.sourceforge.net/</a></p> <p>On Windows you can use Direct3D, but that isn't particularily portable, and I wouldn't be surprised if there is something special for OS X too.</p>
7
2009-07-08T07:05:35Z
[ "python", "3d", "geometry" ]
Display triangles in 3D using Python
1,096,476
<p>Disclaimer: The context is a project I'm working on as part of my Master's degree. I guess it qualifies as homework.</p> <p><hr /></p> <h2>Introduction</h2> <p>(feel free to skip to the bottom line)</p> <p>Curved 3D surfaces are commonly displayed as a large set of very small triangles. Each triangle has the following properties:</p> <ul> <li>3 corners</li> <li>uniform color</li> </ul> <p>Such that when they're all displayed together, you get the illusion of a smooth surface. This is similar to the way pixels of a uniform color are used to get the illusion of a smooth image.</p> <p>My project involves generating and displaying all the triangles that make up a given surfaces. Assuming that I have code that generates a set of triangles, how can I display them?</p> <p>The code that generates the set of triangles is in Python. I'd prefer to use Python to display the triangles, but I'm not picky.</p> <p><hr /></p> <h2>Bottom line</h2> <p>How can I display a triangle in 3D using Python, when the input is the coordinates of the 3 corners of the triangle.</p>
1
2009-07-08T06:52:18Z
1,096,539
<p>EDIT: I misread your question. This is only for 2D:</p> <p>You can use a wx.Canvas of <a href="http://www.wxpython.org/" rel="nofollow">wxpython</a> or implement your application using <a href="http://www.pygame.org/" rel="nofollow">pygame</a>. </p>
0
2009-07-08T07:10:48Z
[ "python", "3d", "geometry" ]
Display triangles in 3D using Python
1,096,476
<p>Disclaimer: The context is a project I'm working on as part of my Master's degree. I guess it qualifies as homework.</p> <p><hr /></p> <h2>Introduction</h2> <p>(feel free to skip to the bottom line)</p> <p>Curved 3D surfaces are commonly displayed as a large set of very small triangles. Each triangle has the following properties:</p> <ul> <li>3 corners</li> <li>uniform color</li> </ul> <p>Such that when they're all displayed together, you get the illusion of a smooth surface. This is similar to the way pixels of a uniform color are used to get the illusion of a smooth image.</p> <p>My project involves generating and displaying all the triangles that make up a given surfaces. Assuming that I have code that generates a set of triangles, how can I display them?</p> <p>The code that generates the set of triangles is in Python. I'd prefer to use Python to display the triangles, but I'm not picky.</p> <p><hr /></p> <h2>Bottom line</h2> <p>How can I display a triangle in 3D using Python, when the input is the coordinates of the 3 corners of the triangle.</p>
1
2009-07-08T06:52:18Z
1,097,876
<p>Here's an example integrating OpenGL with wxPython.</p> <p><a href="http://code.activestate.com/recipes/325392/" rel="nofollow">http://code.activestate.com/recipes/325392/</a></p>
2
2009-07-08T12:52:47Z
[ "python", "3d", "geometry" ]
Combining two JSON objects in to one
1,096,554
<p>I have two JSON objects. One is python array which is converted using json,dumps() and other contains records from database and is serialized using json serializer. I want to combine them into a single JSON object. </p> <p>For eg: </p> <pre><code>obj1 = ["a1", "a2", "a3"] obj2 = [ { "pk": "e1", "model": "AB.abc", "fields": { "e_desc": "abcd" } }, { "pk": "e1", "model": "AB.abc", "fields": { "e_desc": "hij" } }, ] </code></pre> <p>I want to merge them into single object as below:</p> <pre><code>finalObj = { obj1:["a1", "a2", "a3"], obj2: [ { "pk": "e1", "model": "AB.abc", "fields": { "e_desc": "abcd" } }, { "pk": "e1", "model": "AB.abc", "fields": { "e_desc": "hij" } }, ] } </code></pre> <p>How can i do this?</p>
6
2009-07-08T07:13:13Z
1,096,575
<p>You can't do it once they're in JSON format - JSON is just text. You need to combine them in Python first:</p> <pre><code>data = { 'obj1' : obj1, 'obj2' : obj2 } json.dumps(data) </code></pre>
13
2009-07-08T07:19:26Z
[ "python", "json" ]
Combining two JSON objects in to one
1,096,554
<p>I have two JSON objects. One is python array which is converted using json,dumps() and other contains records from database and is serialized using json serializer. I want to combine them into a single JSON object. </p> <p>For eg: </p> <pre><code>obj1 = ["a1", "a2", "a3"] obj2 = [ { "pk": "e1", "model": "AB.abc", "fields": { "e_desc": "abcd" } }, { "pk": "e1", "model": "AB.abc", "fields": { "e_desc": "hij" } }, ] </code></pre> <p>I want to merge them into single object as below:</p> <pre><code>finalObj = { obj1:["a1", "a2", "a3"], obj2: [ { "pk": "e1", "model": "AB.abc", "fields": { "e_desc": "abcd" } }, { "pk": "e1", "model": "AB.abc", "fields": { "e_desc": "hij" } }, ] } </code></pre> <p>How can i do this?</p>
6
2009-07-08T07:13:13Z
1,096,580
<p>Not sure if I'm missing something, but I think this works (tested in python 2.5) with the output you specify:</p> <pre><code>import simplejson finalObj = { 'obj1': obj1, 'obj2': obj2 } simplejson.dumps(finalObj) </code></pre>
6
2009-07-08T07:20:48Z
[ "python", "json" ]
Combining two JSON objects in to one
1,096,554
<p>I have two JSON objects. One is python array which is converted using json,dumps() and other contains records from database and is serialized using json serializer. I want to combine them into a single JSON object. </p> <p>For eg: </p> <pre><code>obj1 = ["a1", "a2", "a3"] obj2 = [ { "pk": "e1", "model": "AB.abc", "fields": { "e_desc": "abcd" } }, { "pk": "e1", "model": "AB.abc", "fields": { "e_desc": "hij" } }, ] </code></pre> <p>I want to merge them into single object as below:</p> <pre><code>finalObj = { obj1:["a1", "a2", "a3"], obj2: [ { "pk": "e1", "model": "AB.abc", "fields": { "e_desc": "abcd" } }, { "pk": "e1", "model": "AB.abc", "fields": { "e_desc": "hij" } }, ] } </code></pre> <p>How can i do this?</p>
6
2009-07-08T07:13:13Z
1,097,257
<p>You have two techniques. The list version suffers from the limitation that the order matters. However, the JSON is slightly simpler-looking. The dictionary version has nested data, which looks more complex.</p> <pre><code>data = { 'obj1' : obj1, 'obj2' : obj2 } json.dumps(data,indent=2) data = [ obj1, obj2 ] json.dumps(data,indent=2) </code></pre>
1
2009-07-08T10:25:51Z
[ "python", "json" ]
Incorporate custom template into the django admin interface and session
1,096,607
<p>I have made a custom formwizard and incorporated it into my admin interface.</p> <p>Basically I have taken the change_form.html and left it under the admin interface url:</p> <pre><code> (r'^admin/compilation/evaluation/add/$', EvaluationWizard([EvaluationForm1, EvaluationForm2])), </code></pre> <p>It works, but the admin "session" is not kept. I can access the page without being logged in to the admin interface, and the admin variables like the breadcrumbs are not working.</p> <p>How do I incorporate it under the "admin interface session" so to speak?</p> <p>Thanks, John</p>
0
2009-07-08T07:29:52Z
1,097,055
<p>If you need to make sure only authorised users access the page, you need to check for an admin user in your request handler. This will be the <code>__call__</code> method in your EvaluationWizard class.</p> <p>Basically, the logic used by the admin is available for viewing <a href="http://code.djangoproject.com/browser/django/trunk/django/contrib/admin/sites.py" rel="nofollow">here</a>. Look for this in the <code>AdminSite</code> class:</p> <pre><code>if not self.has_permission(request): return self.login(request) </code></pre> <p>and use similar logic, or whatever you need. You'll need a similar statement at the top of your <code>__call__</code> method. The <code>has_permission</code> method of <code>AdminSite</code> is a one-liner, which you can use as-is, but you'll need to adapt the <code>login</code> method to your specific needs.</p>
1
2009-07-08T09:27:23Z
[ "python", "django", "django-admin", "django-templates" ]
Can I view the doc string of a function in Python using VIM?
1,096,912
<p>Is there any way to view a function's doc string when writing Python in VIM?</p> <p>For instance:</p> <pre><code>def MyFunction(spam): """A function that foobars the spam returns eggs""" return foobar(spam).eggs() </code></pre> <p>I'd like to be able to type <code>MyFunction(spam0)</code> and see the doc string, either as a tooltip or in the status bar or any other way that VIM allows.</p>
8
2009-07-08T08:50:39Z
1,096,952
<p>The <a href="http://www.vim.org/scripts/script.php?script%5Fid=1542" rel="nofollow">pythoncomplete script</a> is probably what you are looking for.</p>
2
2009-07-08T08:58:44Z
[ "python", "vim", "docstring" ]
Can python mechanize handle HTTP auth?
1,097,380
<p>Mechanize (Python) is failing with 401 for me to open http digest URLs. I googled and tried debugging but no success. </p> <p>My code looks like this.</p> <pre><code>import mechanize project = "test" baseurl = "http://trac.somewhere.net" loginurl = "%s/%s/login" % (baseurl, project) b = mechanize.Browser() b.add_password(baseurl, "user", "secret", "some Realm") b.open(loginurl) </code></pre>
4
2009-07-08T11:03:27Z
1,097,614
<p>Mechanize claims that the parameters should be uri, username and password as parameters, but you have four parameters. Four parameters are correct for urllib2.add_password, but then the first parameter should be the realm, not the uri.</p> <p><a href="http://wwwsearch.sourceforge.net/mechanize/" rel="nofollow">http://wwwsearch.sourceforge.net/mechanize/</a></p> <p>I'd try to change that first.</p> <p>Does trac require digest? if not a next step could be to try using basic auth, as a test to see if that works, since you can add that with just addHeader:</p> <pre><code>import base64 from mechanize import Browser browser = Browser() browser.addheaders.append(('Authorization', 'Basic %s' % base64.encodestring('%s:%s' % (user, pwd)))) </code></pre>
6
2009-07-08T11:57:21Z
[ "python", "mechanize" ]
Can python mechanize handle HTTP auth?
1,097,380
<p>Mechanize (Python) is failing with 401 for me to open http digest URLs. I googled and tried debugging but no success. </p> <p>My code looks like this.</p> <pre><code>import mechanize project = "test" baseurl = "http://trac.somewhere.net" loginurl = "%s/%s/login" % (baseurl, project) b = mechanize.Browser() b.add_password(baseurl, "user", "secret", "some Realm") b.open(loginurl) </code></pre>
4
2009-07-08T11:03:27Z
1,097,732
<p>Depending on how complex your web automation project is, consider using iMacros. Unlike Mechanize it runs in the web browser, so it works with most websites out of the box.</p> <p>I use both the free Firefox addon via a command line (on our Linux server) and the iMacros Scripting Edition via COM object (on a Windows VMware for sites with Flash and Java).</p> <p>Command line (freeware &amp; open source): <a href="http://wiki.imacros.net/iMacros_for_Firefox#Command_Line_Support" rel="nofollow">http://wiki.imacros.net/iMacros_for_Firefox#Command_Line_Support</a></p> <p>COM object (paid version required): wiki.imacros.net/Python</p> <p>Tim</p>
0
2009-07-08T12:22:37Z
[ "python", "mechanize" ]
Can python mechanize handle HTTP auth?
1,097,380
<p>Mechanize (Python) is failing with 401 for me to open http digest URLs. I googled and tried debugging but no success. </p> <p>My code looks like this.</p> <pre><code>import mechanize project = "test" baseurl = "http://trac.somewhere.net" loginurl = "%s/%s/login" % (baseurl, project) b = mechanize.Browser() b.add_password(baseurl, "user", "secret", "some Realm") b.open(loginurl) </code></pre>
4
2009-07-08T11:03:27Z
2,659,135
<p>#!/usr/bin/env python # -<em>- coding: utf-8 -</em>- </p> <pre><code>import mechanize a=mechanize.Browser() a.open("http://www.facebook.com/login.php") a.select_form(nr=0) #form number. a["email"]="mailaddress" a["pass"]="password" a.submit() print a </code></pre>
1
2010-04-17T16:35:43Z
[ "python", "mechanize" ]
Can python mechanize handle HTTP auth?
1,097,380
<p>Mechanize (Python) is failing with 401 for me to open http digest URLs. I googled and tried debugging but no success. </p> <p>My code looks like this.</p> <pre><code>import mechanize project = "test" baseurl = "http://trac.somewhere.net" loginurl = "%s/%s/login" % (baseurl, project) b = mechanize.Browser() b.add_password(baseurl, "user", "secret", "some Realm") b.open(loginurl) </code></pre>
4
2009-07-08T11:03:27Z
4,089,075
<p>For http authentication with mechanize you need to provide the complete url to the <code>add_password</code> method and not just the host base address.</p> <pre><code>import mechanize project = "test" baseurl = "http://trac.somewhere.net" loginurl = "%s/%s/login" % (baseurl, project) b = mechanize.Browser() b.add_password(loginurl, "user", "secret", "some Realm") b.open(loginurl) </code></pre>
3
2010-11-03T16:08:49Z
[ "python", "mechanize" ]
How to get repository for core-plot
1,097,711
<p>I am not able to get the repository for core-plot. What I am doing is that I am typing this in the terminal:</p> <pre><code>hg clone https://core-plot.googlecode.com/hg/ core-plot </code></pre> <p>and this is what I get:</p> <pre> Traceback (most recent call last): File "/usr/local/bin/hg", line 25, in mercurial.util.set_binary(fp) File "/Library/Python/2.5/site-packages/mercurial/demandimport.py", line 75, in __getattribute__ self._load() File "/Library/Python/2.5/site-packages/mercurial/demandimport.py", line 47, in _load mod = _origimport(head, globals, locals) File "/Library/Python/2.5/site-packages/mercurial/util.py", line 93, in _encoding = locale.getlocale()[1] File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/locale.py", line 460, in getlocale return _parse_localename(localename) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/locale.py", line 373, in _parse_localename raise ValueError, 'unknown locale: %s' % localename ValueError: unknown locale: UTF-8 </pre> <p>I can't seem to get it to install. Please give me guidance on how to install the repository.</p>
0
2009-07-08T12:16:56Z
1,098,101
<p>Have you installed Mercurial on your computer? If not, you can download an installer here: <a href="http://mercurial.berkwood.com/" rel="nofollow">http://mercurial.berkwood.com/</a></p>
1
2009-07-08T13:30:42Z
[ "python", "osx", "mercurial", "terminal", "core-plot" ]
How to get repository for core-plot
1,097,711
<p>I am not able to get the repository for core-plot. What I am doing is that I am typing this in the terminal:</p> <pre><code>hg clone https://core-plot.googlecode.com/hg/ core-plot </code></pre> <p>and this is what I get:</p> <pre> Traceback (most recent call last): File "/usr/local/bin/hg", line 25, in mercurial.util.set_binary(fp) File "/Library/Python/2.5/site-packages/mercurial/demandimport.py", line 75, in __getattribute__ self._load() File "/Library/Python/2.5/site-packages/mercurial/demandimport.py", line 47, in _load mod = _origimport(head, globals, locals) File "/Library/Python/2.5/site-packages/mercurial/util.py", line 93, in _encoding = locale.getlocale()[1] File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/locale.py", line 460, in getlocale return _parse_localename(localename) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/locale.py", line 373, in _parse_localename raise ValueError, 'unknown locale: %s' % localename ValueError: unknown locale: UTF-8 </pre> <p>I can't seem to get it to install. Please give me guidance on how to install the repository.</p>
0
2009-07-08T12:16:56Z
1,098,304
<p>The repository works perfectly fine:</p> <pre><code>↪ hg clone https://core-plot.googlecode.com/hg/ core-plot requesting all changes adding changesets adding manifests adding file changes added 406 changesets with 3444 changes to 1861 files updating working directory 1018 files updated, 0 files merged, 0 files removed, 0 files unresolved </code></pre> <p>So I suspect your problem is that <code>hg</code> isn't in your path, or you've not installed Mercurial. You should <a href="http://mercurial.berkwood.com/" rel="nofollow">grab a copy of the installer</a>, or install via your package management system (MacPorts, Apt, YUM etc.)</p>
0
2009-07-08T14:06:06Z
[ "python", "osx", "mercurial", "terminal", "core-plot" ]
How to get repository for core-plot
1,097,711
<p>I am not able to get the repository for core-plot. What I am doing is that I am typing this in the terminal:</p> <pre><code>hg clone https://core-plot.googlecode.com/hg/ core-plot </code></pre> <p>and this is what I get:</p> <pre> Traceback (most recent call last): File "/usr/local/bin/hg", line 25, in mercurial.util.set_binary(fp) File "/Library/Python/2.5/site-packages/mercurial/demandimport.py", line 75, in __getattribute__ self._load() File "/Library/Python/2.5/site-packages/mercurial/demandimport.py", line 47, in _load mod = _origimport(head, globals, locals) File "/Library/Python/2.5/site-packages/mercurial/util.py", line 93, in _encoding = locale.getlocale()[1] File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/locale.py", line 460, in getlocale return _parse_localename(localename) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/locale.py", line 373, in _parse_localename raise ValueError, 'unknown locale: %s' % localename ValueError: unknown locale: UTF-8 </pre> <p>I can't seem to get it to install. Please give me guidance on how to install the repository.</p>
0
2009-07-08T12:16:56Z
1,104,685
<p>It looks like you're having a problem with your locale. Are you using Leopard? If so, check your Terminal preferences. In the Terminal prefs, open up the Settings pane, and click the Advanced tab. The "Character Encoding" menu should be set to "Unicode (UTF-8)". Also make sure that "Set LANG variable on startup" is checked.</p> <p>You can check your locale setting by opening up the Terminal and typing <code>echo $LANG</code>. Mine returns <code>en_US.UTF-8</code> (US English, UTF-8). Not sure what your preferred language is, but it should be <code>&lt;langcode&gt;.UTF-8</code> -- make sure it ends with <code>UTF-8</code>.</p>
1
2009-07-09T15:35:23Z
[ "python", "osx", "mercurial", "terminal", "core-plot" ]
How to get repository for core-plot
1,097,711
<p>I am not able to get the repository for core-plot. What I am doing is that I am typing this in the terminal:</p> <pre><code>hg clone https://core-plot.googlecode.com/hg/ core-plot </code></pre> <p>and this is what I get:</p> <pre> Traceback (most recent call last): File "/usr/local/bin/hg", line 25, in mercurial.util.set_binary(fp) File "/Library/Python/2.5/site-packages/mercurial/demandimport.py", line 75, in __getattribute__ self._load() File "/Library/Python/2.5/site-packages/mercurial/demandimport.py", line 47, in _load mod = _origimport(head, globals, locals) File "/Library/Python/2.5/site-packages/mercurial/util.py", line 93, in _encoding = locale.getlocale()[1] File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/locale.py", line 460, in getlocale return _parse_localename(localename) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/locale.py", line 373, in _parse_localename raise ValueError, 'unknown locale: %s' % localename ValueError: unknown locale: UTF-8 </pre> <p>I can't seem to get it to install. Please give me guidance on how to install the repository.</p>
0
2009-07-08T12:16:56Z
1,106,587
<p>It looks to me like you have a broken Python installation. However, since you're trying to get Mercurial working, please contact the Mercurial team through the correct channels. Use the</p> <ul> <li><strong><a href="http://mercurial.selenic.com/wiki/MailingLists" rel="nofollow">Mercurial mailinglist</a></strong> or the</li> <li><strong><a href="http://mercurial.selenic.com/bts/" rel="nofollow">Mercurial bug tracker</a></strong>.</li> </ul> <p>Doing so means that many more people see your problem and hopefully there will be someone who is using Mac who can help you (I'm using Debian and don't know what Apple has done to your Python installation...).</p>
0
2009-07-09T21:34:51Z
[ "python", "osx", "mercurial", "terminal", "core-plot" ]
How to get repository for core-plot
1,097,711
<p>I am not able to get the repository for core-plot. What I am doing is that I am typing this in the terminal:</p> <pre><code>hg clone https://core-plot.googlecode.com/hg/ core-plot </code></pre> <p>and this is what I get:</p> <pre> Traceback (most recent call last): File "/usr/local/bin/hg", line 25, in mercurial.util.set_binary(fp) File "/Library/Python/2.5/site-packages/mercurial/demandimport.py", line 75, in __getattribute__ self._load() File "/Library/Python/2.5/site-packages/mercurial/demandimport.py", line 47, in _load mod = _origimport(head, globals, locals) File "/Library/Python/2.5/site-packages/mercurial/util.py", line 93, in _encoding = locale.getlocale()[1] File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/locale.py", line 460, in getlocale return _parse_localename(localename) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/locale.py", line 373, in _parse_localename raise ValueError, 'unknown locale: %s' % localename ValueError: unknown locale: UTF-8 </pre> <p>I can't seem to get it to install. Please give me guidance on how to install the repository.</p>
0
2009-07-08T12:16:56Z
1,141,724
<p>LANG can be overridden by HGENCODING. If "echo $HGENCODING" produces "UTF-8" that's your culprit. Unset it or set it to en_US.UTF-8 (or whatever language you prefer, but it should end in .UTF-8). You could also try setting HGENCODING or LANG to "C" if you have no need for non-ascii characters, or just as a test.</p>
0
2009-07-17T06:45:16Z
[ "python", "osx", "mercurial", "terminal", "core-plot" ]
How to get repository for core-plot
1,097,711
<p>I am not able to get the repository for core-plot. What I am doing is that I am typing this in the terminal:</p> <pre><code>hg clone https://core-plot.googlecode.com/hg/ core-plot </code></pre> <p>and this is what I get:</p> <pre> Traceback (most recent call last): File "/usr/local/bin/hg", line 25, in mercurial.util.set_binary(fp) File "/Library/Python/2.5/site-packages/mercurial/demandimport.py", line 75, in __getattribute__ self._load() File "/Library/Python/2.5/site-packages/mercurial/demandimport.py", line 47, in _load mod = _origimport(head, globals, locals) File "/Library/Python/2.5/site-packages/mercurial/util.py", line 93, in _encoding = locale.getlocale()[1] File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/locale.py", line 460, in getlocale return _parse_localename(localename) File "/System/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/locale.py", line 373, in _parse_localename raise ValueError, 'unknown locale: %s' % localename ValueError: unknown locale: UTF-8 </pre> <p>I can't seem to get it to install. Please give me guidance on how to install the repository.</p>
0
2009-07-08T12:16:56Z
1,717,970
<p>See following question here,</p> <p><a href="http://stackoverflow.com/questions/1694539/how-to-create-line-chart-in-iphone-application/1717734#1717734">http://stackoverflow.com/questions/1694539/how-to-create-line-chart-in-iphone-application/1717734#1717734</a></p> <p>I have added my answer there for the same one.</p>
0
2009-11-11T20:49:33Z
[ "python", "osx", "mercurial", "terminal", "core-plot" ]
How do I sort unicode strings alphabetically in Python?
1,097,908
<p>Python sorts by byte value by default, which means é comes after z and other equally funny things. What is the best way to sort alphabetically in Python?</p> <p>Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that åäö should be sorted after z in Swedish, but that ü should be sorted by u, etc. Unicode support is thereby pretty much a requirement.</p> <p>If there is no library for it, what is the best way to do this? Just make a mapping from letter to a integer value and map the string to a integer list with that?</p>
78
2009-07-08T12:59:09Z
1,097,961
<p>Try James Tauber's <a href="http://jtauber.com/blog/2006/01/27/python%5Funicode%5Fcollation%5Falgorithm/">Python Unicode Collation Algorithm</a>. It may not do exactly as you want, but seems well worth a look. For a bit more information about the issues, see <a href="http://www.cmlenz.net/archives/2008/07/the-truth-about-unicode-in-python">this post</a> by Christopher Lenz.</p>
9
2009-07-08T13:08:24Z
[ "python", "sorting", "unicode", "internationalization", "collation" ]
How do I sort unicode strings alphabetically in Python?
1,097,908
<p>Python sorts by byte value by default, which means é comes after z and other equally funny things. What is the best way to sort alphabetically in Python?</p> <p>Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that åäö should be sorted after z in Swedish, but that ü should be sorted by u, etc. Unicode support is thereby pretty much a requirement.</p> <p>If there is no library for it, what is the best way to do this? Just make a mapping from letter to a integer value and map the string to a integer list with that?</p>
78
2009-07-08T12:59:09Z
1,097,980
<p>Jeff Atwood wrote a good post on <a href="http://www.codinghorror.com/blog/archives/001018.html" rel="nofollow">Natural Sort Order</a>, in it he linked to a script which does <a href="http://personal.inet.fi/cool/operator/Human%20Sort.py" rel="nofollow">pretty much what you ask</a>.</p> <p>It's not a trivial script, by any means, but it does the trick.</p>
1
2009-07-08T13:11:58Z
[ "python", "sorting", "unicode", "internationalization", "collation" ]
How do I sort unicode strings alphabetically in Python?
1,097,908
<p>Python sorts by byte value by default, which means é comes after z and other equally funny things. What is the best way to sort alphabetically in Python?</p> <p>Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that åäö should be sorted after z in Swedish, but that ü should be sorted by u, etc. Unicode support is thereby pretty much a requirement.</p> <p>If there is no library for it, what is the best way to do this? Just make a mapping from letter to a integer value and map the string to a integer list with that?</p>
78
2009-07-08T12:59:09Z
1,097,994
<p>To implement it you will need to read about "Unicode collation algorithm" see <a href="http://en.wikipedia.org/wiki/Unicode_collation_algorithm" rel="nofollow">http://en.wikipedia.org/wiki/Unicode_collation_algorithm</a></p> <p><a href="http://www.unicode.org/unicode/reports/tr10/" rel="nofollow">http://www.unicode.org/unicode/reports/tr10/</a></p> <p>a sample implementation is here</p> <p><a href="http://jtauber.com/blog/2006/01/27/python_unicode_collation_algorithm/" rel="nofollow">http://jtauber.com/blog/2006/01/27/python_unicode_collation_algorithm/</a></p>
2
2009-07-08T13:13:38Z
[ "python", "sorting", "unicode", "internationalization", "collation" ]
How do I sort unicode strings alphabetically in Python?
1,097,908
<p>Python sorts by byte value by default, which means é comes after z and other equally funny things. What is the best way to sort alphabetically in Python?</p> <p>Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that åäö should be sorted after z in Swedish, but that ü should be sorted by u, etc. Unicode support is thereby pretty much a requirement.</p> <p>If there is no library for it, what is the best way to do this? Just make a mapping from letter to a integer value and map the string to a integer list with that?</p>
78
2009-07-08T12:59:09Z
1,098,160
<p>IBM's <a href="http://site.icu-project.org/">ICU</a> library does that (and a lot more). It has Python bindings: <a href="http://pypi.python.org/pypi/PyICU">PyICU</a>. </p> <p><strong>Update</strong>: The core difference in sorting between ICU and <code>locale.strcoll</code> is that ICU uses the full <a href="http://unicode.org/reports/tr10/">Unicode Collation Algorithm</a> while <code>strcoll</code> uses <a href="http://en.wikipedia.org/wiki/ISO_14651">ISO 14651</a>.</p> <p>The differences between those two algorithms are briefly summarized here: <a href="http://unicode.org/faq/collation.html#13">http://unicode.org/faq/collation.html#13</a>. These are rather exotic special cases, which should rarely matter in practice.</p> <pre><code>&gt;&gt;&gt; import icu # pip install PyICU &gt;&gt;&gt; sorted(['a','b','c','ä']) ['a', 'b', 'c', 'ä'] &gt;&gt;&gt; collator = icu.Collator.createInstance(icu.Locale('de_DE.UTF-8')) &gt;&gt;&gt; sorted(['a','b','c','ä'], key=collator.getSortKey) ['a', 'ä', 'b', 'c'] </code></pre>
57
2009-07-08T13:42:40Z
[ "python", "sorting", "unicode", "internationalization", "collation" ]
How do I sort unicode strings alphabetically in Python?
1,097,908
<p>Python sorts by byte value by default, which means é comes after z and other equally funny things. What is the best way to sort alphabetically in Python?</p> <p>Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that åäö should be sorted after z in Swedish, but that ü should be sorted by u, etc. Unicode support is thereby pretty much a requirement.</p> <p>If there is no library for it, what is the best way to do this? Just make a mapping from letter to a integer value and map the string to a integer list with that?</p>
78
2009-07-08T12:59:09Z
1,098,616
<p>I see the answers have already done an excellent job, just wanted to point out one coding inefficiency in <a href="http://personal.inet.fi/cool/operator/Human%20Sort.py" rel="nofollow">Human Sort</a>. To apply a selective char-by-char translation to a unicode string s, it uses the code:</p> <pre><code>spec_dict = {'Å':'A', 'Ä':'A'} def spec_order(s): return ''.join([spec_dict.get(ch, ch) for ch in s]) </code></pre> <p>Python has a much better, faster and more concise way to perform this auxiliary task (on Unicode strings -- the analogous method for byte strings has a different and somewhat less helpful specification!-):</p> <pre><code>spec_dict = dict((ord(k), spec_dict[k]) for k in spec_dict) def spec_order(s): return s.translate(spec_dict) </code></pre> <p>The dict you pass to the <code>translate</code> method has Unicode ordinals (not strings) as keys, which is why we need that rebuilding step from the original char-to-char <code>spec_dict</code>. (Values in the dict you pass to translate [as opposed to keys, which must be ordinals] can be Unicode ordinals, arbitrary Unicode strings, or None to remove the corresponding character as part of the translation, so it's easy to specify "ignore a certain character for sorting purposes", "map ä to ae for sorting purposes", and the like).</p> <p>In Python 3, you can get the "rebuilding" step more simply, e.g.:</p> <pre><code>spec_dict = ''.maketrans(spec_dict) </code></pre> <p>See <a href="http://docs.python.org/3.1/library/stdtypes.html?highlight=maketrans#str.maketrans" rel="nofollow">the docs</a> for other ways you can use this <code>maketrans</code> static method in Python 3.</p>
6
2009-07-08T14:57:16Z
[ "python", "sorting", "unicode", "internationalization", "collation" ]
How do I sort unicode strings alphabetically in Python?
1,097,908
<p>Python sorts by byte value by default, which means é comes after z and other equally funny things. What is the best way to sort alphabetically in Python?</p> <p>Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that åäö should be sorted after z in Swedish, but that ü should be sorted by u, etc. Unicode support is thereby pretty much a requirement.</p> <p>If there is no library for it, what is the best way to do this? Just make a mapping from letter to a integer value and map the string to a integer list with that?</p>
78
2009-07-08T12:59:09Z
1,098,751
<p>It is far from a complete solution for your use case, but you could take a look at the <a href="http://svn.effbot.org/public/stuff/sandbox/text/unaccent.py" rel="nofollow">unaccent.py</a> script from effbot.org. What it basically does is remove all accents from a text. You can use that 'sanitized' text to sort alphabetically. (For a better description see <a href="http://effbot.org/zone/unicode-convert.htm" rel="nofollow">this</a> page.)</p>
0
2009-07-08T15:18:03Z
[ "python", "sorting", "unicode", "internationalization", "collation" ]
How do I sort unicode strings alphabetically in Python?
1,097,908
<p>Python sorts by byte value by default, which means é comes after z and other equally funny things. What is the best way to sort alphabetically in Python?</p> <p>Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that åäö should be sorted after z in Swedish, but that ü should be sorted by u, etc. Unicode support is thereby pretty much a requirement.</p> <p>If there is no library for it, what is the best way to do this? Just make a mapping from letter to a integer value and map the string to a integer list with that?</p>
78
2009-07-08T12:59:09Z
1,318,709
<p>I don't see this in the answers. My Application sorts according to the locale using python's standard library. It is pretty easy.</p> <pre><code># python2.5 code below # corpus is our unicode() strings collection as a list corpus = [u"Art", u"Älg", u"Ved", u"Wasa"] import locale # this reads the environment and inits the right locale locale.setlocale(locale.LC_ALL, "") # alternatively, (but it's bad to hardcode) # locale.setlocale(locale.LC_ALL, "sv_SE.UTF-8") corpus.sort(cmp=locale.strcoll) # in python2.x, locale.strxfrm is broken and does not work for unicode strings # in python3.x however: # corpus.sort(key=locale.strxfrm) </code></pre> <p><hr /></p> <p>Question to Lennart and other answerers: Doesn't anyone know 'locale' or is it not up to this task?</p>
41
2009-08-23T14:32:43Z
[ "python", "sorting", "unicode", "internationalization", "collation" ]
How do I sort unicode strings alphabetically in Python?
1,097,908
<p>Python sorts by byte value by default, which means é comes after z and other equally funny things. What is the best way to sort alphabetically in Python?</p> <p>Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that åäö should be sorted after z in Swedish, but that ü should be sorted by u, etc. Unicode support is thereby pretty much a requirement.</p> <p>If there is no library for it, what is the best way to do this? Just make a mapping from letter to a integer value and map the string to a integer list with that?</p>
78
2009-07-08T12:59:09Z
5,013,415
<p>A summary and extended answer:</p> <p><code>locale.strcoll</code> under Python 2, and <code>locale.strxfrm</code> will in fact solve the problem, and does a good job, assuming that you have the locale in question installed. I tested it under Windows too, where the locale names confusingly are different, but on the other hand it seems to have all locales that are supported installed by default.</p> <p><code>ICU</code> doesn't necessarily do this better in practice, it however does way <em>more</em>. Most notably it has support for splitters that can split texts in different languages into words. This is very useful for languages that doesn't have word separators. You'll need to have a corpus of words to use as a base for the splitting, because that's not included, though.</p> <p>It also has long names for the locales so you can get pretty display names for the locale, support for other calendars than Gregorian (although I'm not sure the Python interface supports that) and tons and tons of other more or less obscure locale supports.</p> <p><strong>So all in all:</strong> If you want to sort alphabetically and locale-dependent, you can use the <code>locale</code> module, unless you have special requirements, or also need more locale dependent functionality, like words splitter.</p>
7
2011-02-16T07:00:15Z
[ "python", "sorting", "unicode", "internationalization", "collation" ]
How do I sort unicode strings alphabetically in Python?
1,097,908
<p>Python sorts by byte value by default, which means é comes after z and other equally funny things. What is the best way to sort alphabetically in Python?</p> <p>Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that åäö should be sorted after z in Swedish, but that ü should be sorted by u, etc. Unicode support is thereby pretty much a requirement.</p> <p>If there is no library for it, what is the best way to do this? Just make a mapping from letter to a integer value and map the string to a integer list with that?</p>
78
2009-07-08T12:59:09Z
5,024,116
<h1>A Complete UCA Solution</h1> <p>The simplest, easiest, and most straightforward way to do this it to make a callout to the Perl library module, <a href="http://search.cpan.org/perldoc?Unicode%3A%3ACollate%3A%3ALocale" rel="nofollow">Unicode::Collate::Locale</a>, which is a subclass of the standard <a href="http://search.cpan.org/perldoc?Unicode%3A%3ACollate" rel="nofollow">Unicode::Collate</a> module. All you need do is pass the constructor a locale value of <code>"xv"</code> for Sweden. </p> <p>(You may not neccesarily appreciate this for Swedish text, but because Perl uses abstract characters, you can use any Unicode code point you please — no matter the platform or build! Few languages offer such convenience. I mention it because I’ve fighting a losing battle with Java a lot over this maddening problem lately.)</p> <p>The problem is that I do not know how to access a Perl module from Python — apart, that is, from using a shell callout or two-sided pipe. To that end, <a href="http://training.perl.com/scripts/ucsort" rel="nofollow">I have therefore provided you with a complete working script called <em>ucsort</em></a> that you can call to do exactly what you have asked for with perfect ease. </p> <p><strong>This script is 100% compliant with the full <a href="http://unicode.org/reports/tr10/" rel="nofollow">Unicode Collation Algorithm</a></strong>, with all tailoring options supported!! And if you have an optional module installed or run Perl 5.13 or better, then you have full access to easy-to-use CLDR locales. See below.</p> <h2>Demonstration</h2> <p>Imagine an input set ordered this way:</p> <pre><code>b o i j n l m å y e v s k h d f g t ö r x p z a ä c u q </code></pre> <p>A default sort by code point yields:</p> <pre><code>a b c d e f g h i j k l m n o p q r s t u v x y z ä å ö </code></pre> <p>which is incorrect by everybody’s book. Using my script, which uses the Unicode Collation Algorithm, you get this order:</p> <pre><code>% perl ucsort /tmp/swedish_alphabet | fmt a å ä b c d e f g h i j k l m n o ö p q r s t u v x y z </code></pre> <p>That is the default UCA sort. To get the Swedish locale, call <a href="http://training.perl.com/scripts/ucsort" rel="nofollow"><em>ucsort</em></a> this way:</p> <pre><code>% perl ucsort --locale=sv /tmp/swedish_alphabet | fmt a b c d e f g h i j k l m n o p q r s t u v x y z å ä ö </code></pre> <p>Here is a better input demo. First, the input set:</p> <pre><code>% fmt /tmp/swedish_set cTD cDD Cöd Cbd cAD cCD cYD Cud cZD Cod cBD Cnd cQD cFD Ced Cfd cOD cLD cXD Cid Cpd cID Cgd cVD cMD cÅD cGD Cqd Cäd cJD Cdd Ckd cÖD cÄD Ctd Czd Cxd cHD cND cKD Cvd Chd Cyd cUD Cld Cmd cED Crd Cad Cåd Ccd cRD cSD Csd Cjd cPD </code></pre> <p>By code point, that sorts this way:</p> <pre><code>Cad Cbd Ccd Cdd Ced Cfd Cgd Chd Cid Cjd Ckd Cld Cmd Cnd Cod Cpd Cqd Crd Csd Ctd Cud Cvd Cxd Cyd Czd Cäd Cåd Cöd cAD cBD cCD cDD cED cFD cGD cHD cID cJD cKD cLD cMD cND cOD cPD cQD cRD cSD cTD cUD cVD cXD cYD cZD cÄD cÅD cÖD </code></pre> <p>But using the default UCA makes it sort this way:</p> <pre><code>% ucsort /tmp/swedish_set | fmt cAD Cad cÅD Cåd cÄD Cäd cBD Cbd cCD Ccd cDD Cdd cED Ced cFD Cfd cGD Cgd cHD Chd cID Cid cJD Cjd cKD Ckd cLD Cld cMD Cmd cND Cnd cOD Cod cÖD Cöd cPD Cpd cQD Cqd cRD Crd cSD Csd cTD Ctd cUD Cud cVD Cvd cXD Cxd cYD Cyd cZD Czd </code></pre> <p>But in the Swedish locale, this way:</p> <pre><code>% ucsort --locale=sv /tmp/swedish_set | fmt cAD Cad cBD Cbd cCD Ccd cDD Cdd cED Ced cFD Cfd cGD Cgd cHD Chd cID Cid cJD Cjd cKD Ckd cLD Cld cMD Cmd cND Cnd cOD Cod cPD Cpd cQD Cqd cRD Crd cSD Csd cTD Ctd cUD Cud cVD Cvd cXD Cxd cYD Cyd cZD Czd cÅD Cåd cÄD Cäd cÖD Cöd </code></pre> <p>If you prefer uppercase to sort before lowercase, do this:</p> <pre><code>% ucsort --upper-before-lower --locale=sv /tmp/swedish_set | fmt Cad cAD Cbd cBD Ccd cCD Cdd cDD Ced cED Cfd cFD Cgd cGD Chd cHD Cid cID Cjd cJD Ckd cKD Cld cLD Cmd cMD Cnd cND Cod cOD Cpd cPD Cqd cQD Crd cRD Csd cSD Ctd cTD Cud cUD Cvd cVD Cxd cXD Cyd cYD Czd cZD Cåd cÅD Cäd cÄD Cöd cÖD </code></pre> <h2>Customized Sorts</h2> <p>You can do many other things with <a href="http://training.perl.com/scripts/ucsort" rel="nofollow"><em>ucsort</em></a>. For example, here is how to sort titles in English:</p> <pre><code>% ucsort --preprocess='s/^(an?|the)\s+//i' /tmp/titles Anathem The Book of Skulls A Civil Campaign The Claw of the Conciliator The Demolished Man Dune An Early Dawn The Faded Sun: Kesrith The Fall of Hyperion A Feast for Crows Flowers for Algernon The Forbidden Tower Foundation and Empire Foundation’s Edge The Goblin Reservation The High Crusade Jack of Shadows The Man in the High Castle The Ringworld Engineers The Robots of Dawn A Storm of Swords Stranger in a Strange Land There Will Be Time The White Dragon </code></pre> <p>You will need Perl 5.10.1 or better to run the script in general. For locale support, you must either install the optional CPAN module <code>Unicode::Collate::Locale</code>. Alternately, you can install a development versions of Perl, 5.13+, which include that module standardly.</p> <h1>Calling Conventions</h1> <p>This is a rapid prototype, so <a href="http://training.perl.com/scripts/ucsort" rel="nofollow"><em>ucsort</em></a> is mostly un(der)documented. But this is its SYNOPSIS of what switches/options it accepts on the command line:</p> <pre><code> # standard options --help|? --man|m --debug|d # collator constructor options --backwards-levels=i --collation-level|level|l=i --katakana-before-hiragana --normalization|n=s --override-CJK=s --override-Hangul=s --preprocess|P=s --upper-before-lower|u --variable=s # program specific options --case-insensitive|insensitive|i --input-encoding|e=s --locale|L=s --paragraph|p --reverse-fields|last --reverse-output|r --right-to-left|reverse-input </code></pre> <p>Yeah, ok: that’s really the argument list I use for the call to <code>Getopt::Long</code>, but you get the idea. :) </p> <p>If you can figure out how to call Perl library modules from Python directly without calling a Perl script, by all means do so. I just don’t know how myself. I’d love to learn how.</p> <p>In the meantime, I believe this script will do what you need done in all its particular — <strong>and more!</strong> I now use this for all of text sorting. It <em>finally</em> does what I’ve needed for a long, long time. </p> <p>The only downside is that <code>--locale</code> argument causes performance to go down the tubes, although it’s plenty fast enough for regular, non-locale <strong>but still 100% UCA compliant</strong> sorting. Since it loads everything in memory, you probably don’t want to use this on gigabyte documents. I use it many times a day, and it sure it great having sane text sorting at last.</p>
3
2011-02-17T01:19:02Z
[ "python", "sorting", "unicode", "internationalization", "collation" ]
How do I sort unicode strings alphabetically in Python?
1,097,908
<p>Python sorts by byte value by default, which means é comes after z and other equally funny things. What is the best way to sort alphabetically in Python?</p> <p>Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that åäö should be sorted after z in Swedish, but that ü should be sorted by u, etc. Unicode support is thereby pretty much a requirement.</p> <p>If there is no library for it, what is the best way to do this? Just make a mapping from letter to a integer value and map the string to a integer list with that?</p>
78
2009-07-08T12:59:09Z
8,535,192
<p>You might also be interested in <strong>pyuca</strong>:</p> <p><a href="http://jtauber.com/blog/2006/01/27/python_unicode_collation_algorithm/">http://jtauber.com/blog/2006/01/27/python_unicode_collation_algorithm/</a></p> <p>Though it is certainly not the most exact way, it is a very simple way to at least get it somewhat right. It also beats locale in a webapp as locale is not threadsafe and sets the language settings process-wide. It also easier to set up than PyICU which relies on an external C library. </p> <p>I uploaded the script to github as the original was down at the time of this writing and I had to resort to web caches to get it:</p> <p><a href="https://github.com/href/Python-Unicode-Collation-Algorithm">https://github.com/href/Python-Unicode-Collation-Algorithm</a></p> <p>I successfully used this script to sanely sort German/French/Italian text in a plone module.</p>
6
2011-12-16T13:54:45Z
[ "python", "sorting", "unicode", "internationalization", "collation" ]
How do I sort unicode strings alphabetically in Python?
1,097,908
<p>Python sorts by byte value by default, which means é comes after z and other equally funny things. What is the best way to sort alphabetically in Python?</p> <p>Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that åäö should be sorted after z in Swedish, but that ü should be sorted by u, etc. Unicode support is thereby pretty much a requirement.</p> <p>If there is no library for it, what is the best way to do this? Just make a mapping from letter to a integer value and map the string to a integer list with that?</p>
78
2009-07-08T12:59:09Z
16,480,912
<p>Lately I've been using zope.ucol (<a href="https://pypi.python.org/pypi/zope.ucol" rel="nofollow">https://pypi.python.org/pypi/zope.ucol</a>) for this task. For example, sorting the german ß:</p> <pre><code>&gt;&gt;&gt; import zope.ucol &gt;&gt;&gt; collator = zope.ucol.Collator("de-de") &gt;&gt;&gt; mylist = [u"a", u'x', u'\u00DF'] &gt;&gt;&gt; print mylist [u'a', u'x', u'\xdf'] &gt;&gt;&gt; print sorted(mylist, key=collator.key) [u'a', u'\xdf', u'x'] </code></pre> <p>zope.ucol also wraps ICU, so would be an alternative to PyICU.</p>
1
2013-05-10T11:08:14Z
[ "python", "sorting", "unicode", "internationalization", "collation" ]
How to empty a socket in python?
1,097,974
<p>I need to empty the data on a socket (making sure that there is nothing to receive). Unfortunately, there is no function for this in the python socket module.</p> <p>I've implemented something this way:</p> <pre><code>def empty_socket(sock): """remove the data present on the socket""" input = [sock] while 1: inputready, o, e = select.select(input,[],[], 0.0) if len(inputready)==0: break for s in inputready: s.recv(1) </code></pre> <p>What do you think? Is there a better way to do that?</p> <hr> <p>Update: I don't want to change the socket timeout. What's why i prefer a select to a read.</p> <hr> <p>Update: The original question was using the 'flush' term. It seems that 'empty' is a better term.</p> <hr> <p>Update - 2010-02-27 : I've noticed a bug when the pair has closed. The inputready is always filled with the sockets. I fixed that by adding a maximum number of loops. Is there a better fix?</p>
5
2009-07-08T13:10:12Z
1,098,016
<p>Not sure if this will work, but you could attach a file object to the socket's file descriptor and call the <code>flush()</code> method on that file object:</p> <pre><code>import os file_obj = os.fdopen(your_socket.fileno()) file_obj.flush() </code></pre> <p>This won't work in Windows because the descriptor returned by <code>fileno()</code> can't be passed to <code>os.fdopen()</code> in Windows</p>
-1
2009-07-08T13:18:16Z
[ "python", "sockets", "select" ]
How to empty a socket in python?
1,097,974
<p>I need to empty the data on a socket (making sure that there is nothing to receive). Unfortunately, there is no function for this in the python socket module.</p> <p>I've implemented something this way:</p> <pre><code>def empty_socket(sock): """remove the data present on the socket""" input = [sock] while 1: inputready, o, e = select.select(input,[],[], 0.0) if len(inputready)==0: break for s in inputready: s.recv(1) </code></pre> <p>What do you think? Is there a better way to do that?</p> <hr> <p>Update: I don't want to change the socket timeout. What's why i prefer a select to a read.</p> <hr> <p>Update: The original question was using the 'flush' term. It seems that 'empty' is a better term.</p> <hr> <p>Update - 2010-02-27 : I've noticed a bug when the pair has closed. The inputready is always filled with the sockets. I fixed that by adding a maximum number of loops. Is there a better fix?</p>
5
2009-07-08T13:10:12Z
1,098,025
<p>Using <code>select.select</code> is good practice, as indicated in the <a href="http://www.amk.ca/python/howto/sockets/sockets.html#SECTION000600000000000000000" rel="nofollow">Socket Programming HOWTO</a>. You'll need to set the socket as non-blocking, using <code>sock.setblocking(0)</code>.</p> <p>Just a comment about nomenclature: <code>flush</code> is normally associated with <em>output</em> operations.</p>
1
2009-07-08T13:19:32Z
[ "python", "sockets", "select" ]
How to empty a socket in python?
1,097,974
<p>I need to empty the data on a socket (making sure that there is nothing to receive). Unfortunately, there is no function for this in the python socket module.</p> <p>I've implemented something this way:</p> <pre><code>def empty_socket(sock): """remove the data present on the socket""" input = [sock] while 1: inputready, o, e = select.select(input,[],[], 0.0) if len(inputready)==0: break for s in inputready: s.recv(1) </code></pre> <p>What do you think? Is there a better way to do that?</p> <hr> <p>Update: I don't want to change the socket timeout. What's why i prefer a select to a read.</p> <hr> <p>Update: The original question was using the 'flush' term. It seems that 'empty' is a better term.</p> <hr> <p>Update - 2010-02-27 : I've noticed a bug when the pair has closed. The inputready is always filled with the sockets. I fixed that by adding a maximum number of loops. Is there a better fix?</p>
5
2009-07-08T13:10:12Z
1,098,216
<p>If by "flush" you mean throw away any pending incoming data then you can either use select() like you do, or set the socket to nonblocking and read in a loop until you're out of data.</p> <p>Also note that (from the Linux manpage):</p> <blockquote> <p>Under Linux, select() may report a socket file descriptor as "ready for reading", while nevertheless a subsequent read blocks. This could for example happen when data has arrived but upon examination has wrong checksum and is discarded. There may be other circumstances in which a file descriptor is spuriously reported as ready. Thus it may be safer to use O_NONBLOCK on sockets that should not block.</p> </blockquote> <p><a href="http://stackoverflow.com/questions/858282/spurious-readiness-notification-for-select-system-call">Spurious readiness notification for Select System call</a></p> <p>And as has been noted by others, "flush" usually refers to output.</p>
6
2009-07-08T13:51:46Z
[ "python", "sockets", "select" ]
How to empty a socket in python?
1,097,974
<p>I need to empty the data on a socket (making sure that there is nothing to receive). Unfortunately, there is no function for this in the python socket module.</p> <p>I've implemented something this way:</p> <pre><code>def empty_socket(sock): """remove the data present on the socket""" input = [sock] while 1: inputready, o, e = select.select(input,[],[], 0.0) if len(inputready)==0: break for s in inputready: s.recv(1) </code></pre> <p>What do you think? Is there a better way to do that?</p> <hr> <p>Update: I don't want to change the socket timeout. What's why i prefer a select to a read.</p> <hr> <p>Update: The original question was using the 'flush' term. It seems that 'empty' is a better term.</p> <hr> <p>Update - 2010-02-27 : I've noticed a bug when the pair has closed. The inputready is always filled with the sockets. I fixed that by adding a maximum number of loops. Is there a better fix?</p>
5
2009-07-08T13:10:12Z
23,276,613
<p>For UDP packets, I did the following:</p> <ol> <li><p>After creating the socket, setting options, and binding, I use <code>socket.settimeout()</code>. Note the documentation for <a href="https://docs.python.org/3.4/library/socket.html#socket.socket.setblocking" rel="nofollow"><code>setblocking()</code></a> gives some information which that of <code>settimeout()</code> doesn't - if you want your socket operations to block, you should just use <code>settimeout()</code> to set the timeout. <code>setblocking()</code> just puts an infinite timeout on it. (I had a bug calling <code>settimeout()</code> followed by <code>setblocking(1)</code>.)</p></li> <li><p>My "buffer emptying" function is then just this ("Listener" is my socket):</p> <p><code>def FlushListen(self): while 1: try: PacketBytes = self.__Listener.recv(1024) except: break;</code></p> <p>With a timeout of 1 second, this will read all the UDP packets and then return 1 second after there's no data.</p></li> </ol> <p>In my case I'm using it to just talk between two programs on the same PC so I could easily lower my timeout but speed is not an issue so I'm fine with this.</p> <p>According to some of the links others posted, this should work with data streams as well.</p>
0
2014-04-24T18:10:29Z
[ "python", "sockets", "select" ]
Stripping spaces between XML nodes with Python
1,098,118
<p>Is there a easy way to accomplish the same thing in Python as xsl accomplishes with:</p> <pre><code>&lt;xsl:strip-space elements="*"/&gt; </code></pre> <p>So for instance in the following </p> <pre><code>for event, elem in ElementTree.iterparse("/tmp/example.xml"): if elem.tag == "example": print ElementTree.tostring(elem) </code></pre> <p>when the example nodes are printed out all the spaces and line feeds in the input file between children of the example node will be removed? </p>
2
2009-07-08T13:34:20Z
1,098,514
<p>I believe you need to explicitly manipulate the subtree to strip every text and tail:</p> <pre><code>from xml.etree import ElementTree for event, elem in ElementTree.iterparse("/tmp/example.xml"): if elem.tag == "example": subiter = ElementTree.ElementTree(elem).getiterator() for x in subiter: if x.text: x.text = x.text.strip() if x.tail: x.tail = x.tail.strip() print ElementTree.tostring(elem) </code></pre>
3
2009-07-08T14:37:49Z
[ "python", "xml", "xslt" ]
Stripping spaces between XML nodes with Python
1,098,118
<p>Is there a easy way to accomplish the same thing in Python as xsl accomplishes with:</p> <pre><code>&lt;xsl:strip-space elements="*"/&gt; </code></pre> <p>So for instance in the following </p> <pre><code>for event, elem in ElementTree.iterparse("/tmp/example.xml"): if elem.tag == "example": print ElementTree.tostring(elem) </code></pre> <p>when the example nodes are printed out all the spaces and line feeds in the input file between children of the example node will be removed? </p>
2
2009-07-08T13:34:20Z
1,098,536
<p>An elegant solution could have an iterator which simply filters out whitespace-only text nodes:</p> <pre><code>import re whitespaces = re.compile('\s*$') def omit_whitespaces(iter): for event, elem in iter: if whitespaces.match(elem.text): elem.text = '' if whitespaces.match(elem.tail): elem.tail = '' yield event, elem def strip_whitespaces(iter): for event, elem in iter: elem.text = elem.text.strip() elem.tail = elem.tail.strip() yield event, elem </code></pre> <p>And then use it as follows (either <code>strip</code> or <code>omit</code>, depending on whether you want to preserve spaces in text nodes with non-whitespace characters too):</p> <pre><code>for event, elem in omit_whitespaces(ElementTree.iterparse("/tmp/example.xml")): if elem.tag == "example": print ElementTree.tostring(elem) </code></pre> <p>Note that in this case you have to use only 'end' event (otherwise parser can give you partial data).</p> <p>But... I don't really know ElementTree very well and I didn't tested this code though.</p>
1
2009-07-08T14:43:21Z
[ "python", "xml", "xslt" ]
Stripping spaces between XML nodes with Python
1,098,118
<p>Is there a easy way to accomplish the same thing in Python as xsl accomplishes with:</p> <pre><code>&lt;xsl:strip-space elements="*"/&gt; </code></pre> <p>So for instance in the following </p> <pre><code>for event, elem in ElementTree.iterparse("/tmp/example.xml"): if elem.tag == "example": print ElementTree.tostring(elem) </code></pre> <p>when the example nodes are printed out all the spaces and line feeds in the input file between children of the example node will be removed? </p>
2
2009-07-08T13:34:20Z
7,323,908
<p>If you can use the <a href="http://pypi.python.org/pypi/lxml" rel="nofollow">lxml</a> module, this becomes much easier. From <a href="http://lxml.de/tutorial.html#parser-objects" rel="nofollow">the lxml tutorial</a>:</p> <pre><code>&gt;&gt;&gt; parser = etree.XMLParser(remove_blank_text=True) # lxml.etree only! &gt;&gt;&gt; root = etree.XML("&lt;root&gt; &lt;a/&gt; &lt;b&gt; &lt;/b&gt; &lt;/root&gt;", parser) &gt;&gt;&gt; etree.tostring(root) b'&lt;root&gt;&lt;a/&gt;&lt;b&gt; &lt;/b&gt;&lt;/root&gt;' </code></pre>
3
2011-09-06T17:41:02Z
[ "python", "xml", "xslt" ]
Reallocating list in python
1,098,202
<p>Ok this is my problem. I am trying something like this:</p> <pre><code>for i in big_list: del glist[:] for j in range(0:val) glist.append(blah[j]) </code></pre> <p>The idea is to reset the list and reuse it for the next set of data points. The problem is, for some reason, if the first list has 3 points,</p> <pre><code>glist[0] glist[1] glist[2] </code></pre> <p>The next list will continue from index 3 and store the last 3 elements in those indexes</p> <pre><code>glist[0] = 4th elem of new list glist[1] = 5th elem of new list glist[2] = 6th elem of new list glist[3] = 1st elem of new list glist[4] = 2nd elem of new list glist[5] = 3rd elem of new list </code></pre> <p>I'm sure it is an issue with allocated space. But how can I achieve this del g_list[:] so the result is,</p> <pre><code>glist[0] = 1st elem of new list glist[1] = 2nd elem of new list glist[2] = 3rd elem of new list glist[3] = 4th elem of new list glist[4] = 5th elem of new list glist[5] = 6th elem of new list </code></pre> <p>Allocating variable from within loop is not an option. Any ideas?</p>
0
2009-07-08T13:50:05Z
1,098,240
<p>Change <code>del glist[:]</code> to <code>glist = []</code>. You don't need to "reuse" or "reallocate" in Python, the garbagecollector will take care of that for you.</p> <p>Also, you use 'i' as the loop variable in both loops. That's going to confuse you sooner or later. :)</p>
4
2009-07-08T13:54:47Z
[ "python", "list", "memory-management", "collections" ]
Reallocating list in python
1,098,202
<p>Ok this is my problem. I am trying something like this:</p> <pre><code>for i in big_list: del glist[:] for j in range(0:val) glist.append(blah[j]) </code></pre> <p>The idea is to reset the list and reuse it for the next set of data points. The problem is, for some reason, if the first list has 3 points,</p> <pre><code>glist[0] glist[1] glist[2] </code></pre> <p>The next list will continue from index 3 and store the last 3 elements in those indexes</p> <pre><code>glist[0] = 4th elem of new list glist[1] = 5th elem of new list glist[2] = 6th elem of new list glist[3] = 1st elem of new list glist[4] = 2nd elem of new list glist[5] = 3rd elem of new list </code></pre> <p>I'm sure it is an issue with allocated space. But how can I achieve this del g_list[:] so the result is,</p> <pre><code>glist[0] = 1st elem of new list glist[1] = 2nd elem of new list glist[2] = 3rd elem of new list glist[3] = 4th elem of new list glist[4] = 5th elem of new list glist[5] = 6th elem of new list </code></pre> <p>Allocating variable from within loop is not an option. Any ideas?</p>
0
2009-07-08T13:50:05Z
1,098,262
<p>you can try </p> <pre><code>glist=[] </code></pre>
1
2009-07-08T13:58:08Z
[ "python", "list", "memory-management", "collections" ]
Reallocating list in python
1,098,202
<p>Ok this is my problem. I am trying something like this:</p> <pre><code>for i in big_list: del glist[:] for j in range(0:val) glist.append(blah[j]) </code></pre> <p>The idea is to reset the list and reuse it for the next set of data points. The problem is, for some reason, if the first list has 3 points,</p> <pre><code>glist[0] glist[1] glist[2] </code></pre> <p>The next list will continue from index 3 and store the last 3 elements in those indexes</p> <pre><code>glist[0] = 4th elem of new list glist[1] = 5th elem of new list glist[2] = 6th elem of new list glist[3] = 1st elem of new list glist[4] = 2nd elem of new list glist[5] = 3rd elem of new list </code></pre> <p>I'm sure it is an issue with allocated space. But how can I achieve this del g_list[:] so the result is,</p> <pre><code>glist[0] = 1st elem of new list glist[1] = 2nd elem of new list glist[2] = 3rd elem of new list glist[3] = 4th elem of new list glist[4] = 5th elem of new list glist[5] = 6th elem of new list </code></pre> <p>Allocating variable from within loop is not an option. Any ideas?</p>
0
2009-07-08T13:50:05Z
1,098,280
<p><code>del glist[:]</code> works fine for clearing a list. You need to show us your exact code. As shown below, the behavior you're describing does not happen. The <code>append</code> after the <code>del a[:]</code> puts the item at index 0.</p> <pre><code>&gt;&gt;&gt; a = [1,2,3] &gt;&gt;&gt; del a[:] &gt;&gt;&gt; a [] &gt;&gt;&gt; a.append(4) &gt;&gt;&gt; a [4] </code></pre>
1
2009-07-08T14:02:56Z
[ "python", "list", "memory-management", "collections" ]
How to make Python check if ftp directory exists?
1,098,218
<p>I'm using this script to connect to sample ftp server and list available directories:</p> <pre><code>from ftplib import FTP ftp = FTP('ftp.cwi.nl') # connect to host, default port (some example server, i'll use other one) ftp.login() # user anonymous, passwd anonymous@ ftp.retrlines('LIST') # list directory contents ftp.quit() </code></pre> <p>How do I use ftp.retrlines('LIST') output to check if directory (for example public_html) exists, if it exists cd to it and then execute some other code and exit; if not execute code right away and exit?</p>
8
2009-07-08T13:51:56Z
1,098,253
<p>you can use a list. example</p> <pre><code>import ftplib server="localhost" user="user" password="test@email.com" try: ftp = ftplib.FTP(server) ftp.login(user,password) except Exception,e: print e else: filelist = [] #to store all files ftp.retrlines('LIST',filelist.append) # append to list f=0 for f in filelist: if "public_html" in f: #do something f=1 if f==0: print "No public_html" #do your processing here </code></pre>
8
2009-07-08T13:56:38Z
[ "python", "ftp" ]
How to make Python check if ftp directory exists?
1,098,218
<p>I'm using this script to connect to sample ftp server and list available directories:</p> <pre><code>from ftplib import FTP ftp = FTP('ftp.cwi.nl') # connect to host, default port (some example server, i'll use other one) ftp.login() # user anonymous, passwd anonymous@ ftp.retrlines('LIST') # list directory contents ftp.quit() </code></pre> <p>How do I use ftp.retrlines('LIST') output to check if directory (for example public_html) exists, if it exists cd to it and then execute some other code and exit; if not execute code right away and exit?</p>
8
2009-07-08T13:51:56Z
3,703,987
<p>The examples attached to ghostdog74's answer have a bit of a bug: the list you get back is the whole line of the response, so you get something like</p> <pre><code>drwxrwxrwx 4 5063 5063 4096 Sep 13 20:00 resized </code></pre> <p>This means if your directory name is something like '50' (which is was in my case), you'll get a false positive. I modified the code to handle this:</p> <pre><code>def directory_exists_here(self, directory_name): filelist = [] self.ftp.retrlines('LIST',filelist.append) for f in filelist: if f.split()[-1] == directory_name: return True return False </code></pre> <p>N.B., this is inside an FTP wrapper class I wrote and self.ftp is the actual FTP connection.</p>
2
2010-09-13T20:07:19Z
[ "python", "ftp" ]
How to make Python check if ftp directory exists?
1,098,218
<p>I'm using this script to connect to sample ftp server and list available directories:</p> <pre><code>from ftplib import FTP ftp = FTP('ftp.cwi.nl') # connect to host, default port (some example server, i'll use other one) ftp.login() # user anonymous, passwd anonymous@ ftp.retrlines('LIST') # list directory contents ftp.quit() </code></pre> <p>How do I use ftp.retrlines('LIST') output to check if directory (for example public_html) exists, if it exists cd to it and then execute some other code and exit; if not execute code right away and exit?</p>
8
2009-07-08T13:51:56Z
13,155,592
<p>Tom is correct, but no one voted him up however for the satisfaction who voted up ghostdog74 I will mix and write this code, works for me, should work for you guys.</p> <pre><code>import ftplib server="localhost" user="user" uploadToDir="public_html" password="test@email.com" try: ftp = ftplib.FTP(server) ftp.login(user,password) except Exception,e: print e else: filelist = [] #to store all files ftp.retrlines('NLST',filelist.append) # append to list num=0 for f in filelist: if f.split()[-1] == uploadToDir: #do something num=1 if num==0: print "No public_html" #do your processing here </code></pre> <p>first of all if you follow ghost dog method, even if you say directory "public" in f, even when it doesnt exist it will evaluate to true because the word public exist in "public_html" so thats where Tom if condition can be used so I changed it to <strong>if f.split()[-1] == uploadToDir:</strong>.</p> <p>Also if you enter a directory name somethig that doesnt exist but some files and folder exist the second by ghostdog74 will never execute because its never 0 as overridden by f in for loop so I used <em>num</em> variable instead of <em>f</em> and voila the goodness follows...</p> <p>Vinay and Jonathon are right about what they commented.</p>
1
2012-10-31T10:12:31Z
[ "python", "ftp" ]
How to make Python check if ftp directory exists?
1,098,218
<p>I'm using this script to connect to sample ftp server and list available directories:</p> <pre><code>from ftplib import FTP ftp = FTP('ftp.cwi.nl') # connect to host, default port (some example server, i'll use other one) ftp.login() # user anonymous, passwd anonymous@ ftp.retrlines('LIST') # list directory contents ftp.quit() </code></pre> <p>How do I use ftp.retrlines('LIST') output to check if directory (for example public_html) exists, if it exists cd to it and then execute some other code and exit; if not execute code right away and exit?</p>
8
2009-07-08T13:51:56Z
14,331,184
<p>Nslt will list an array for all files in ftp server. Just check if your folder name is there.</p> <pre><code>from ftplib import FTP ftp = FTP('yourserver') ftp.login('username', 'password') folderName = 'yourFolderName' if folderName in ftp.nlst(): #do needed task </code></pre>
10
2013-01-15T04:28:30Z
[ "python", "ftp" ]
How to make Python check if ftp directory exists?
1,098,218
<p>I'm using this script to connect to sample ftp server and list available directories:</p> <pre><code>from ftplib import FTP ftp = FTP('ftp.cwi.nl') # connect to host, default port (some example server, i'll use other one) ftp.login() # user anonymous, passwd anonymous@ ftp.retrlines('LIST') # list directory contents ftp.quit() </code></pre> <p>How do I use ftp.retrlines('LIST') output to check if directory (for example public_html) exists, if it exists cd to it and then execute some other code and exit; if not execute code right away and exit?</p>
8
2009-07-08T13:51:56Z
17,346,128
<p>In 3.x <code>nlst()</code> method is deprecated. Use this code:</p> <pre><code>import ftplib remote = ftplib.FTP('example.com') remote.login() if 'foo' in [name for name, data in list(remote.mlsd())]: # do your stuff </code></pre> <p>The <code>list()</code> call is needed because <code>mlsd()</code> returns a generator and they do not support checking what is in them (do not have <code>__contains__()</code> method).</p> <p>You can wrap <code>[name for name, data in list(remote.mlsd())]</code> list comp in a function of method and call it when you will need to just check if a directory (or file) exists.</p>
1
2013-06-27T14:38:08Z
[ "python", "ftp" ]
How to make Python check if ftp directory exists?
1,098,218
<p>I'm using this script to connect to sample ftp server and list available directories:</p> <pre><code>from ftplib import FTP ftp = FTP('ftp.cwi.nl') # connect to host, default port (some example server, i'll use other one) ftp.login() # user anonymous, passwd anonymous@ ftp.retrlines('LIST') # list directory contents ftp.quit() </code></pre> <p>How do I use ftp.retrlines('LIST') output to check if directory (for example public_html) exists, if it exists cd to it and then execute some other code and exit; if not execute code right away and exit?</p>
8
2009-07-08T13:51:56Z
19,950,512
<p>You can send "MLST path" over the control connection. That will return a line including the <em>type</em> of the path (notice 'type=dir' down here):</p> <pre><code>250-Listing "/home/user": modify=20131113091701;perm=el;size=4096;type=dir;unique=813gc0004; / 250 End MLST. </code></pre> <p>Translated into python that should be something along these lines:</p> <pre><code>import ftplib ftp = ftplib.FTP() ftp.connect('ftp.somedomain.com', 21) ftp.login() resp = ftp.sendcmd('MLST pathname') if 'type=dir;' in resp: # it should be a directory pass </code></pre> <p>Of course the code above is not 100% reliable and would need a 'real' parser. You can look at the implementation of MLSD command in ftplib.py which is very similar (MLSD differs from MLST in that the response in sent over the <em>data</em> connection but the format of the lines being transmitted is the same): <a href="http://hg.python.org/cpython/file/8af2dc11464f/Lib/ftplib.py#l577" rel="nofollow">http://hg.python.org/cpython/file/8af2dc11464f/Lib/ftplib.py#l577</a></p>
1
2013-11-13T09:50:51Z
[ "python", "ftp" ]
How to make Python check if ftp directory exists?
1,098,218
<p>I'm using this script to connect to sample ftp server and list available directories:</p> <pre><code>from ftplib import FTP ftp = FTP('ftp.cwi.nl') # connect to host, default port (some example server, i'll use other one) ftp.login() # user anonymous, passwd anonymous@ ftp.retrlines('LIST') # list directory contents ftp.quit() </code></pre> <p>How do I use ftp.retrlines('LIST') output to check if directory (for example public_html) exists, if it exists cd to it and then execute some other code and exit; if not execute code right away and exit?</p>
8
2009-07-08T13:51:56Z
20,205,019
<p>=> I found this web-page while googling for a way to check if a file exists using ftplib in python. The following is what I figured out (hope it helps someone):</p> <p>=> When trying to list non-existent files/directories, ftplib raises an exception. Even though Adding a try/except block is a standard practice and a good idea, I would prefer my FTP scripts to download file(s) only after making sure they exist. This helps in keeping my scripts simpler - at least when listing a directory on the FTP server is possible. </p> <p>For example, the Edgar FTP server has multiple files that are stored under the directory /edgar/daily-index/. Each file is named liked "master.YYYYMMDD.idx". There is no guarantee that a file will exist for every date (YYYYMMDD) - there is no file dated 24th Nov 2013, but there is a file dated: 22th Nov 2013. How does listing work in these two cases?</p> <pre><code># Code from __future__ import print_function import ftplib ftp_client = ftplib.FTP("ftp.sec.gov", "anonymous", "MY.EMAIL@gmail.com") resp = ftp_client.sendcmd("MLST /edgar/daily-index/master.20131122.idx") print(resp) resp = ftp_client.sendcmd("MLST /edgar/daily-index/master.20131124.idx") print(resp) # Output 250-Start of list for /edgar/daily-index/master.20131122.idx modify=20131123030124;perm=adfr;size=301580;type=file;unique=11UAEAA398; UNIX.group=1;UNIX.mode=0644;UNIX.owner=1019; /edgar/daily-index/master.20131122.idx 250 End of list Traceback (most recent call last): File "", line 10, in &lt;module&gt; resp = ftp_client.sendcmd("MLST /edgar/daily-index/master.20131124.idx") File "lib/python2.7/ftplib.py", line 244, in sendcmd return self.getresp() File "lib/python2.7/ftplib.py", line 219, in getresp raise error_perm, resp ftplib.error_perm: 550 '/edgar/daily-index/master.20131124.idx' cannot be listed </code></pre> <p>As expected, listing a non-existent file generates an exception.</p> <p>=> Since I know that the Edgar FTP server will surely have the directory /edgar/daily-index/, my script can do the following to avoid raising exceptions due to non-existent files:<br> a) list this directory.<br> b) download the required file(s) if they are are present in this listing - To check the listing I typically perform a regexp search, on the list of strings that the listing operation returns. </p> <p>For example this script tries to download files for the past three days. If a file is found for a certain date then it is downloaded, else nothing happens. </p> <pre><code>import ftplib import re from datetime import date, timedelta ftp_client = ftplib.FTP("ftp.sec.gov", "anonymous", "MY.EMAIL@gmail.com") listing = [] # List the directory and store each directory entry as a string in an array ftp_client.retrlines("LIST /edgar/daily-index", listing.append) # go back 1,2 and 3 days for diff in [1,2,3]: today = (date.today() - timedelta(days=diff)).strftime("%Y%m%d") month = (date.today() - timedelta(days=diff)).strftime("%Y_%m") # the absolute path of the file we want to download - if it indeed exists file_path = "/edgar/daily-index/master.%(date)s.idx" % { "date": today } # create a regex to match the file's name pattern = re.compile("master.%(date)s.idx" % { "date": today }) # filter out elements from the listing that match the pattern found = filter(lambda x: re.search(pattern, x) != None, listing) if( len(found) &gt; 0 ): ftp_client.retrbinary( "RETR %(file_path)s" % { "file_path": file_path }, open( './edgar/daily-index/%(month)s/master.%(date)s.idx' % { "date": today }, 'wb' ).write ) </code></pre> <p>=> Interestingly, there are situations where we cannot list a directory on the FTP server. The edgar FTP server, for example, disallows listing on /edgar/data because it contains far too many sub-directories. In such cases, I wouldn't be able to use the "List and check for existence" approach described here - in these cases I would have to use exception handling in my downloader script to recover from non-existent file/directory access attempts.</p>
1
2013-11-25T22:46:48Z
[ "python", "ftp" ]
Is os.popen really deprecated in Python 2.6?
1,098,257
<p>The on-line <a href="http://docs.python.org/library/os.html#os.popen">documentation</a> states that os.popen is now deprecated. All other deprecated functions duly raise a DeprecationWarning. For instance:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; [c.close() for c in os.popen2('ps h -eo pid:1,command')] __main__:1: DeprecationWarning: os.popen2 is deprecated. Use the subprocess module. [None, None] </code></pre> <p>The function os.popen, on the other hand, completes silently:</p> <pre><code>&gt;&gt;&gt;len(list(os.popen('ps h -eo pid:1,command'))) 202 </code></pre> <p>Without raising a warning. Of the three possible scenarios</p> <ol> <li>It is expected behaviour that documentation and standard library have different ideas of what is deprecated;</li> <li>There is an error in the documentation and os.popen is not really deprecated;</li> <li>There is an error in the standard library and os.popen should raise a warning;</li> </ol> <p>which one is the correct one?</p> <p>For background information, here's the Python I'm using:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.version 2.6.2 (r262:71600, May 12 2009, 10:57:01) [GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] </code></pre> <p>The argument to os.popen is taken from a <a href="http://stackoverflow.com/questions/1091327/processlist/1091426#1091426">reply of mine</a> here on Stack Overflow.</p> <p><strong>Addendum</strong>: Thanks to cobbal <a href="http://stackoverflow.com/questions/1098257/is-os-popen-really-deprecated-in-python-2-6/1098268#1098268">below</a>, it turns out that os.popen is not deprecated in Python 3.1, after all.</p>
6
2009-07-08T13:57:19Z
1,098,268
<p>one thing that I can think of is that os.popen exists in python3, while os.popen2 doesn't. So one is "more deprecated" than the other, and scheduled for sooner removal from the language.</p>
4
2009-07-08T13:59:47Z
[ "python", "deprecated", "std" ]
Is os.popen really deprecated in Python 2.6?
1,098,257
<p>The on-line <a href="http://docs.python.org/library/os.html#os.popen">documentation</a> states that os.popen is now deprecated. All other deprecated functions duly raise a DeprecationWarning. For instance:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; [c.close() for c in os.popen2('ps h -eo pid:1,command')] __main__:1: DeprecationWarning: os.popen2 is deprecated. Use the subprocess module. [None, None] </code></pre> <p>The function os.popen, on the other hand, completes silently:</p> <pre><code>&gt;&gt;&gt;len(list(os.popen('ps h -eo pid:1,command'))) 202 </code></pre> <p>Without raising a warning. Of the three possible scenarios</p> <ol> <li>It is expected behaviour that documentation and standard library have different ideas of what is deprecated;</li> <li>There is an error in the documentation and os.popen is not really deprecated;</li> <li>There is an error in the standard library and os.popen should raise a warning;</li> </ol> <p>which one is the correct one?</p> <p>For background information, here's the Python I'm using:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.version 2.6.2 (r262:71600, May 12 2009, 10:57:01) [GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] </code></pre> <p>The argument to os.popen is taken from a <a href="http://stackoverflow.com/questions/1091327/processlist/1091426#1091426">reply of mine</a> here on Stack Overflow.</p> <p><strong>Addendum</strong>: Thanks to cobbal <a href="http://stackoverflow.com/questions/1098257/is-os-popen-really-deprecated-in-python-2-6/1098268#1098268">below</a>, it turns out that os.popen is not deprecated in Python 3.1, after all.</p>
6
2009-07-08T13:57:19Z
1,098,460
<p>Here is the <a href="http://www.python.org/dev/peps/pep-0361/">PEP</a>.</p> <blockquote> <pre><code>Deprecated modules and functions in the standard library: - buildtools - cfmfile - commands.getstatus() - macostools.touched() - md5 - MimeWriter - mimify - popen2, os.popen[234]() - posixfile - sets - sha </code></pre> </blockquote>
5
2009-07-08T14:28:01Z
[ "python", "deprecated", "std" ]
Is os.popen really deprecated in Python 2.6?
1,098,257
<p>The on-line <a href="http://docs.python.org/library/os.html#os.popen">documentation</a> states that os.popen is now deprecated. All other deprecated functions duly raise a DeprecationWarning. For instance:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; [c.close() for c in os.popen2('ps h -eo pid:1,command')] __main__:1: DeprecationWarning: os.popen2 is deprecated. Use the subprocess module. [None, None] </code></pre> <p>The function os.popen, on the other hand, completes silently:</p> <pre><code>&gt;&gt;&gt;len(list(os.popen('ps h -eo pid:1,command'))) 202 </code></pre> <p>Without raising a warning. Of the three possible scenarios</p> <ol> <li>It is expected behaviour that documentation and standard library have different ideas of what is deprecated;</li> <li>There is an error in the documentation and os.popen is not really deprecated;</li> <li>There is an error in the standard library and os.popen should raise a warning;</li> </ol> <p>which one is the correct one?</p> <p>For background information, here's the Python I'm using:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.version 2.6.2 (r262:71600, May 12 2009, 10:57:01) [GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] </code></pre> <p>The argument to os.popen is taken from a <a href="http://stackoverflow.com/questions/1091327/processlist/1091426#1091426">reply of mine</a> here on Stack Overflow.</p> <p><strong>Addendum</strong>: Thanks to cobbal <a href="http://stackoverflow.com/questions/1098257/is-os-popen-really-deprecated-in-python-2-6/1098268#1098268">below</a>, it turns out that os.popen is not deprecated in Python 3.1, after all.</p>
6
2009-07-08T13:57:19Z
1,223,080
<p>In the meanwhile I have opened a <a href="http://bugs.python.org/issue6490" rel="nofollow">ticket</a> on the Python issue tracker. I'll keep this question open until the ticket is closed.</p>
2
2009-08-03T15:45:21Z
[ "python", "deprecated", "std" ]
Is os.popen really deprecated in Python 2.6?
1,098,257
<p>The on-line <a href="http://docs.python.org/library/os.html#os.popen">documentation</a> states that os.popen is now deprecated. All other deprecated functions duly raise a DeprecationWarning. For instance:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; [c.close() for c in os.popen2('ps h -eo pid:1,command')] __main__:1: DeprecationWarning: os.popen2 is deprecated. Use the subprocess module. [None, None] </code></pre> <p>The function os.popen, on the other hand, completes silently:</p> <pre><code>&gt;&gt;&gt;len(list(os.popen('ps h -eo pid:1,command'))) 202 </code></pre> <p>Without raising a warning. Of the three possible scenarios</p> <ol> <li>It is expected behaviour that documentation and standard library have different ideas of what is deprecated;</li> <li>There is an error in the documentation and os.popen is not really deprecated;</li> <li>There is an error in the standard library and os.popen should raise a warning;</li> </ol> <p>which one is the correct one?</p> <p>For background information, here's the Python I'm using:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; print sys.version 2.6.2 (r262:71600, May 12 2009, 10:57:01) [GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] </code></pre> <p>The argument to os.popen is taken from a <a href="http://stackoverflow.com/questions/1091327/processlist/1091426#1091426">reply of mine</a> here on Stack Overflow.</p> <p><strong>Addendum</strong>: Thanks to cobbal <a href="http://stackoverflow.com/questions/1098257/is-os-popen-really-deprecated-in-python-2-6/1098268#1098268">below</a>, it turns out that os.popen is not deprecated in Python 3.1, after all.</p>
6
2009-07-08T13:57:19Z
1,801,288
<p><a href="http://docs.python.org/library/commands.html" rel="nofollow">commands.getstatusoutput</a> still uses it according to the 2.6.4 documentation.</p>
0
2009-11-26T02:47:37Z
[ "python", "deprecated", "std" ]
Looking for elegant glob-like DNA string expansion
1,098,461
<p>I'm trying to make a glob-like expansion of a set of DNA strings that have multiple possible bases.</p> <p>The base of my DNA strings contains the letters A, C, G, and T. However, I can have special characters like M which could be an A or a C.</p> <p>For example, say I have the string:</p> <p><code>ATMM</code></p> <p>I would like to take this string as input and output the four possible matching strings:</p> <p><code>ATAA</code> <code>ATAC</code> <code>ATCA</code> <code>ATCC</code></p> <p>Rather than brute force a solution, I feel like there must be some elegant Python/Perl/Regular Expression trick to do this. </p> <p>Thank you for any advice.</p> <p><strong>Edit, thanks cortex for the product operator. This is my solution:</strong></p> <p>Still a Python newbie, so I bet there's a better way to handle each dictionary key than another for loop. Any suggestions would be great.</p> <pre><code>import sys from itertools import product baseDict = dict(M=['A','C'],R=['A','G'],W=['A','T'],S=['C','G'], Y=['C','T'],K=['G','T'],V=['A','C','G'], H=['A','C','T'],D=['A','G','T'],B=['C','G','T']) def glob(str): strings = [str] ## this loop visits very possible base in the dictionary ## probably a cleaner way to do it for base in baseDict: oldstrings = strings strings = [] for string in oldstrings: strings += map("".join,product(*[baseDict[base] if x == base else [x] for x in string])) return strings for line in sys.stdin.readlines(): line = line.rstrip('\n') permutations = glob(line) for x in permutations: print x </code></pre>
2
2009-07-08T14:28:03Z
1,098,478
<p>This isn't really an "expansion" problem and it's almost certainly not doable with any sensible regular expression.</p> <p>I believe what you're looking for is "how to generate permutations".</p>
0
2009-07-08T14:31:13Z
[ "python", "permutation", "glob", "dna-sequence" ]
Looking for elegant glob-like DNA string expansion
1,098,461
<p>I'm trying to make a glob-like expansion of a set of DNA strings that have multiple possible bases.</p> <p>The base of my DNA strings contains the letters A, C, G, and T. However, I can have special characters like M which could be an A or a C.</p> <p>For example, say I have the string:</p> <p><code>ATMM</code></p> <p>I would like to take this string as input and output the four possible matching strings:</p> <p><code>ATAA</code> <code>ATAC</code> <code>ATCA</code> <code>ATCC</code></p> <p>Rather than brute force a solution, I feel like there must be some elegant Python/Perl/Regular Expression trick to do this. </p> <p>Thank you for any advice.</p> <p><strong>Edit, thanks cortex for the product operator. This is my solution:</strong></p> <p>Still a Python newbie, so I bet there's a better way to handle each dictionary key than another for loop. Any suggestions would be great.</p> <pre><code>import sys from itertools import product baseDict = dict(M=['A','C'],R=['A','G'],W=['A','T'],S=['C','G'], Y=['C','T'],K=['G','T'],V=['A','C','G'], H=['A','C','T'],D=['A','G','T'],B=['C','G','T']) def glob(str): strings = [str] ## this loop visits very possible base in the dictionary ## probably a cleaner way to do it for base in baseDict: oldstrings = strings strings = [] for string in oldstrings: strings += map("".join,product(*[baseDict[base] if x == base else [x] for x in string])) return strings for line in sys.stdin.readlines(): line = line.rstrip('\n') permutations = glob(line) for x in permutations: print x </code></pre>
2
2009-07-08T14:28:03Z
1,098,498
<p>You could for example do this recursively. Pseudo-code:</p> <pre><code>printSequences(sequence s) switch "first special character in sequence" case ... case M: s1 = s, but first M replaced with A printSequences(s1) s2 = s, but first M replaced with C printSequences(s2) case none: print s; </code></pre>
0
2009-07-08T14:35:40Z
[ "python", "permutation", "glob", "dna-sequence" ]
Looking for elegant glob-like DNA string expansion
1,098,461
<p>I'm trying to make a glob-like expansion of a set of DNA strings that have multiple possible bases.</p> <p>The base of my DNA strings contains the letters A, C, G, and T. However, I can have special characters like M which could be an A or a C.</p> <p>For example, say I have the string:</p> <p><code>ATMM</code></p> <p>I would like to take this string as input and output the four possible matching strings:</p> <p><code>ATAA</code> <code>ATAC</code> <code>ATCA</code> <code>ATCC</code></p> <p>Rather than brute force a solution, I feel like there must be some elegant Python/Perl/Regular Expression trick to do this. </p> <p>Thank you for any advice.</p> <p><strong>Edit, thanks cortex for the product operator. This is my solution:</strong></p> <p>Still a Python newbie, so I bet there's a better way to handle each dictionary key than another for loop. Any suggestions would be great.</p> <pre><code>import sys from itertools import product baseDict = dict(M=['A','C'],R=['A','G'],W=['A','T'],S=['C','G'], Y=['C','T'],K=['G','T'],V=['A','C','G'], H=['A','C','T'],D=['A','G','T'],B=['C','G','T']) def glob(str): strings = [str] ## this loop visits very possible base in the dictionary ## probably a cleaner way to do it for base in baseDict: oldstrings = strings strings = [] for string in oldstrings: strings += map("".join,product(*[baseDict[base] if x == base else [x] for x in string])) return strings for line in sys.stdin.readlines(): line = line.rstrip('\n') permutations = glob(line) for x in permutations: print x </code></pre>
2
2009-07-08T14:28:03Z
1,098,510
<p>You probably could do something like this in python using the yield operator</p> <pre><code>def glob(str): if str=='': yield '' return if str[0]!='M': for tail in glob(str[1:]): yield str[0] + tail else: for c in ['A','G','C','T']: for tail in glob(str[1:]): yield c + tail return </code></pre> <p>EDIT: As correctly pointed out I was making a few mistakes. Here is a version which I tried out and works.</p>
1
2009-07-08T14:37:12Z
[ "python", "permutation", "glob", "dna-sequence" ]
Looking for elegant glob-like DNA string expansion
1,098,461
<p>I'm trying to make a glob-like expansion of a set of DNA strings that have multiple possible bases.</p> <p>The base of my DNA strings contains the letters A, C, G, and T. However, I can have special characters like M which could be an A or a C.</p> <p>For example, say I have the string:</p> <p><code>ATMM</code></p> <p>I would like to take this string as input and output the four possible matching strings:</p> <p><code>ATAA</code> <code>ATAC</code> <code>ATCA</code> <code>ATCC</code></p> <p>Rather than brute force a solution, I feel like there must be some elegant Python/Perl/Regular Expression trick to do this. </p> <p>Thank you for any advice.</p> <p><strong>Edit, thanks cortex for the product operator. This is my solution:</strong></p> <p>Still a Python newbie, so I bet there's a better way to handle each dictionary key than another for loop. Any suggestions would be great.</p> <pre><code>import sys from itertools import product baseDict = dict(M=['A','C'],R=['A','G'],W=['A','T'],S=['C','G'], Y=['C','T'],K=['G','T'],V=['A','C','G'], H=['A','C','T'],D=['A','G','T'],B=['C','G','T']) def glob(str): strings = [str] ## this loop visits very possible base in the dictionary ## probably a cleaner way to do it for base in baseDict: oldstrings = strings strings = [] for string in oldstrings: strings += map("".join,product(*[baseDict[base] if x == base else [x] for x in string])) return strings for line in sys.stdin.readlines(): line = line.rstrip('\n') permutations = glob(line) for x in permutations: print x </code></pre>
2
2009-07-08T14:28:03Z
1,098,546
<p>Regexps <em>match</em> strings, they're not intended to be turned into every string they might match.</p> <p>Also, you're looking at a lot of strings being output from this - for instance:</p> <pre><code>MMMMMMMMMMMMMMMM (16 M's) </code></pre> <p>produces 65,536 16 character strings - and I'm guessing that DNA sequences are usually longer than that. </p> <p>Arguably any solution to this is pretty much 'brute force' from a computer science perspective, because your algorithm is O(2^n) on the original string length. There's actually quite a lot of work to be done.</p> <p>Why do you want to produce all the combinations? What are you going to do with them? (If you're thinking to produce every string possibility and then look for it in a large DNA sequence, then there are <em>much</em> better ways of doing that.)</p>
0
2009-07-08T14:45:23Z
[ "python", "permutation", "glob", "dna-sequence" ]
Looking for elegant glob-like DNA string expansion
1,098,461
<p>I'm trying to make a glob-like expansion of a set of DNA strings that have multiple possible bases.</p> <p>The base of my DNA strings contains the letters A, C, G, and T. However, I can have special characters like M which could be an A or a C.</p> <p>For example, say I have the string:</p> <p><code>ATMM</code></p> <p>I would like to take this string as input and output the four possible matching strings:</p> <p><code>ATAA</code> <code>ATAC</code> <code>ATCA</code> <code>ATCC</code></p> <p>Rather than brute force a solution, I feel like there must be some elegant Python/Perl/Regular Expression trick to do this. </p> <p>Thank you for any advice.</p> <p><strong>Edit, thanks cortex for the product operator. This is my solution:</strong></p> <p>Still a Python newbie, so I bet there's a better way to handle each dictionary key than another for loop. Any suggestions would be great.</p> <pre><code>import sys from itertools import product baseDict = dict(M=['A','C'],R=['A','G'],W=['A','T'],S=['C','G'], Y=['C','T'],K=['G','T'],V=['A','C','G'], H=['A','C','T'],D=['A','G','T'],B=['C','G','T']) def glob(str): strings = [str] ## this loop visits very possible base in the dictionary ## probably a cleaner way to do it for base in baseDict: oldstrings = strings strings = [] for string in oldstrings: strings += map("".join,product(*[baseDict[base] if x == base else [x] for x in string])) return strings for line in sys.stdin.readlines(): line = line.rstrip('\n') permutations = glob(line) for x in permutations: print x </code></pre>
2
2009-07-08T14:28:03Z
1,098,598
<p>Agree with other posters that it seems like a strange thing to want to do. Of course, if you really want to, there is (as always) an elegant way to do it in Python (2.6+):</p> <pre><code>from itertools import product map("".join, product(*[['A', 'C'] if x == "M" else [x] for x in "GMTTMCA"])) </code></pre> <p>Full solution with input handling:</p> <pre><code>import sys from itertools import product base_globs = {"M":['A','C'], "R":['A','G'], "W":['A','T'], "S":['C','G'], "Y":['C','T'], "K":['G','T'], "V":['A','C','G'], "H":['A','C','T'], "D":['A','G','T'], "B":['C','G','T'], } def base_glob(glob_sequence): production_sequence = [base_globs.get(base, [base]) for base in glob_sequence] return map("".join, product(*production_sequence)) for line in sys.stdin.readlines(): productions = base_glob(line.strip()) print "\n".join(productions) </code></pre>
2
2009-07-08T14:54:21Z
[ "python", "permutation", "glob", "dna-sequence" ]
Proper way to use **kwargs in Python
1,098,549
<p>What is the proper way to use <code>**kwargs</code> in Python when it comes to default values?</p> <p><code>kwargs</code> returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? </p> <pre><code>class ExampleClass: def __init__(self, **kwargs): self.val = kwargs['val'] self.val2 = kwargs.get('val2') </code></pre> <p>A simple question, but one that I can't find good resources on. People do it different ways in code that I've seen and it's hard to know what to use.</p>
247
2009-07-08T14:45:53Z
1,098,556
<p>You can pass a default value to <code>get()</code> for keys that are not in the dictionary:</p> <pre><code>self.val2 = kwargs.get('val2',"default value") </code></pre> <p>However, if you plan on using a particular argument with a particular default value, why not use named arguments in the first place?</p> <pre><code>def __init__(self, val2="default value", **kwargs): </code></pre>
245
2009-07-08T14:47:38Z
[ "python", "kwargs" ]
Proper way to use **kwargs in Python
1,098,549
<p>What is the proper way to use <code>**kwargs</code> in Python when it comes to default values?</p> <p><code>kwargs</code> returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? </p> <pre><code>class ExampleClass: def __init__(self, **kwargs): self.val = kwargs['val'] self.val2 = kwargs.get('val2') </code></pre> <p>A simple question, but one that I can't find good resources on. People do it different ways in code that I've seen and it's hard to know what to use.</p>
247
2009-07-08T14:45:53Z
1,098,577
<p>You'd do</p> <pre><code>self.attribute = kwargs.pop('name', default_value) </code></pre> <p>or</p> <pre><code>self.attribute = kwargs.get('name', default_value) </code></pre> <p>If you use <code>pop</code>, then you can check if there are any spurious values sent, and take the appropriate action (if any).</p>
42
2009-07-08T14:49:58Z
[ "python", "kwargs" ]
Proper way to use **kwargs in Python
1,098,549
<p>What is the proper way to use <code>**kwargs</code> in Python when it comes to default values?</p> <p><code>kwargs</code> returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? </p> <pre><code>class ExampleClass: def __init__(self, **kwargs): self.val = kwargs['val'] self.val2 = kwargs.get('val2') </code></pre> <p>A simple question, but one that I can't find good resources on. People do it different ways in code that I've seen and it's hard to know what to use.</p>
247
2009-07-08T14:45:53Z
1,098,588
<p>You could do something like this</p> <pre><code>class ExampleClass: def __init__(self, **kwargs): arguments = {'val':1, 'val2':2} arguments.update(kwargs) self.val = arguments['val'] self.val2 = arguments['val2'] </code></pre>
8
2009-07-08T14:51:57Z
[ "python", "kwargs" ]
Proper way to use **kwargs in Python
1,098,549
<p>What is the proper way to use <code>**kwargs</code> in Python when it comes to default values?</p> <p><code>kwargs</code> returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? </p> <pre><code>class ExampleClass: def __init__(self, **kwargs): self.val = kwargs['val'] self.val2 = kwargs.get('val2') </code></pre> <p>A simple question, but one that I can't find good resources on. People do it different ways in code that I've seen and it's hard to know what to use.</p>
247
2009-07-08T14:45:53Z
1,098,605
<p>Using **kwargs and default values is easy. Sometimes, however, you shouldn't be using **kwargs in the first place.</p> <p>In this case, we're not really making best use of **kwargs.</p> <pre><code>class ExampleClass( object ): def __init__(self, **kwargs): self.val = kwargs.get('val',"default1") self.val2 = kwargs.get('val2',"default2") </code></pre> <p>The above is a "why bother?" declaration. It is the same as</p> <pre><code>class ExampleClass( object ): def __init__(self, val="default1", val2="default2"): self.val = val self.val2 = val2 </code></pre> <p>When you're using **kwargs, you mean that a keyword is not just optional, but conditional. There are more complex rules than simple default values.</p> <p>When you're using **kwargs, you usually mean something more like the following, where simple defaults don't apply.</p> <pre><code>class ExampleClass( object ): def __init__(self, **kwargs): self.val = "default1" self.val2 = "default2" if "val" in kwargs: self.val = kwargs["val"] self.val2 = 2*self.val elif "val2" in kwargs: self.val2 = kwargs["val2"] self.val = self.val2 / 2 else: raise TypeError( "must provide val= or val2= parameter values" ) </code></pre>
30
2009-07-08T14:55:22Z
[ "python", "kwargs" ]
Proper way to use **kwargs in Python
1,098,549
<p>What is the proper way to use <code>**kwargs</code> in Python when it comes to default values?</p> <p><code>kwargs</code> returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? </p> <pre><code>class ExampleClass: def __init__(self, **kwargs): self.val = kwargs['val'] self.val2 = kwargs.get('val2') </code></pre> <p>A simple question, but one that I can't find good resources on. People do it different ways in code that I've seen and it's hard to know what to use.</p>
247
2009-07-08T14:45:53Z
1,098,639
<p>I suggest something like this</p> <pre><code>def testFunc( **kwargs ): options = { 'option1' : 'default_value1', 'option2' : 'default_value2', 'option3' : 'default_value3', } options.update(kwargs) print options testFunc( option1='new_value1', option3='new_value3' ) # {'option2': 'default_value2', 'option3': 'new_value3', 'option1': 'new_value1'} testFunc( option2='new_value2' ) # {'option1': 'default_value1', 'option3': 'default_value3', 'option2': 'new_value2'} </code></pre> <p>And then use the values any way you want</p> <p><code>dictionaryA.update(dictionaryB)</code> adds the contents of <code>dictionaryB</code> to <code>dictionaryA</code> overwriting any duplicate keys.</p>
36
2009-07-08T15:03:14Z
[ "python", "kwargs" ]
Proper way to use **kwargs in Python
1,098,549
<p>What is the proper way to use <code>**kwargs</code> in Python when it comes to default values?</p> <p><code>kwargs</code> returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? </p> <pre><code>class ExampleClass: def __init__(self, **kwargs): self.val = kwargs['val'] self.val2 = kwargs.get('val2') </code></pre> <p>A simple question, but one that I can't find good resources on. People do it different ways in code that I've seen and it's hard to know what to use.</p>
247
2009-07-08T14:45:53Z
1,098,834
<p>While most answers are saying that, e.g.,</p> <pre><code>def f(**kwargs): foo = kwargs.pop('foo') bar = kwargs.pop('bar') ...etc... </code></pre> <p>is "the same as"</p> <pre><code>def f(foo=None, bar=None, **kwargs): ...etc... </code></pre> <p>this is not true. In the latter case, <code>f</code> can be called as <code>f(23, 42)</code>, while the former case accepts named arguments <strong>only</strong> -- no positional calls. Often you want to allow the caller maximum flexibility and therefore the second form, as most answers assert, is preferable: but that is not always the case. When you accept many optional parameters of which typically only a few are passed, it may be an excellent idea (avoiding accidents and unreadable code at your call sites!) to force the use of named arguments -- <code>threading.Thread</code> is an example. The first form is how you implement that in Python 2.</p> <p>The idiom is so important that in Python 3 it now has special supporting syntax: every argument after a single <code>*</code> in the <code>def</code> signature is keyword-only, that is, cannot be passed as a positional argument, but only as a named one. So in Python 3 you could code the above as:</p> <pre><code>def f(*, foo=None, bar=None, **kwargs): ...etc... </code></pre> <p>Indeed, in Python 3 you can even have keyword-only arguments that <em>aren't</em> optional (ones without a default value).</p> <p>However, Python 2 still has long years of productive life ahead, so it's better to <strong>not</strong> forget the techniques and idioms that let you implement in Python 2 important design ideas that are directly supported in the language in Python 3!</p>
156
2009-07-08T15:29:29Z
[ "python", "kwargs" ]
Proper way to use **kwargs in Python
1,098,549
<p>What is the proper way to use <code>**kwargs</code> in Python when it comes to default values?</p> <p><code>kwargs</code> returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? </p> <pre><code>class ExampleClass: def __init__(self, **kwargs): self.val = kwargs['val'] self.val2 = kwargs.get('val2') </code></pre> <p>A simple question, but one that I can't find good resources on. People do it different ways in code that I've seen and it's hard to know what to use.</p>
247
2009-07-08T14:45:53Z
2,053,613
<p>Here's another approach:</p> <pre><code>def my_func(arg1, arg2, arg3): ... so something ... kwargs = {'arg1': 'Value One', 'arg2': 'Value Two', 'arg3': 'Value Three'} # Now you can call the function with kwargs like this: my_func(**kwargs) </code></pre>
11
2010-01-13T00:44:27Z
[ "python", "kwargs" ]
Proper way to use **kwargs in Python
1,098,549
<p>What is the proper way to use <code>**kwargs</code> in Python when it comes to default values?</p> <p><code>kwargs</code> returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? </p> <pre><code>class ExampleClass: def __init__(self, **kwargs): self.val = kwargs['val'] self.val2 = kwargs.get('val2') </code></pre> <p>A simple question, but one that I can't find good resources on. People do it different ways in code that I've seen and it's hard to know what to use.</p>
247
2009-07-08T14:45:53Z
12,492,336
<p>If you want to combine this with *args you have to keep *args and **kwargs at the end of the definition.</p> <p>So:</p> <pre><code>def method(foo, bar=None, *args, **kwargs): do_something_with(foo, bar) some_other_function(*args, **kwargs) </code></pre>
1
2012-09-19T09:50:37Z
[ "python", "kwargs" ]
Proper way to use **kwargs in Python
1,098,549
<p>What is the proper way to use <code>**kwargs</code> in Python when it comes to default values?</p> <p><code>kwargs</code> returns a dictionary, but what is the best way to set default values, or is there one? Should I just access it as a dictionary? Use get function? </p> <pre><code>class ExampleClass: def __init__(self, **kwargs): self.val = kwargs['val'] self.val2 = kwargs.get('val2') </code></pre> <p>A simple question, but one that I can't find good resources on. People do it different ways in code that I've seen and it's hard to know what to use.</p>
247
2009-07-08T14:45:53Z
13,629,607
<p>Since <code>**kwargs</code> is used when the number of arguments is unknown, why not doing this?</p> <pre><code>class Exampleclass(object): def __init__(self, **kwargs): for k in kwargs.keys(): if k in [acceptable_keys_list]: self.__setattr__(k, kwargs[k]) </code></pre>
19
2012-11-29T15:55:28Z
[ "python", "kwargs" ]