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
django-cart or Satchmo?
490,439
<p>I'm looking to implement a very basic shopping cart. <a href="http://www.satchmoproject.com/">Satchmo</a> seems to install a <strong>lot</strong> of applications and extra stuff that I don't need. I've heard others mention <a href="http://code.google.com/p/django-cart/">django-cart</a>. Has anyone tried this Django app (django-cart)? Anything to watch for or any other experiences?</p>
23
2009-01-29T04:00:49Z
490,534
<p>Well if you want to use django-cart you should view it as a starting point for developing your own. The last commit (r4) for the project was November 2006.</p> <p>By comparison, the last commit (r1922) to Satchmo was a couple of hours ago.</p> <p>With Satchmo you get code that is under active development and actually used by real e-commerce sites.</p> <p>If you develop your own you're running the risk of alienating customers and losing money. If you use Satchmo you can spend more time developing/improving other areas of your site.</p> <p>I bet you can already guess my recommendation :)</p> <p>As for the apps and other stuff in Satchmo I can tell you, from personal experience, that you don't need to include them all in your INSTALLED_APPS setting. I don't remember exactly what I pared it down to, but there were only around 6-7 Satchmo apps in my INSTALLED_APPS and they were all ones I needed. I think they've done even more modularization since then.</p>
26
2009-01-29T05:04:35Z
[ "python", "django", "e-commerce", "satchmo" ]
django-cart or Satchmo?
490,439
<p>I'm looking to implement a very basic shopping cart. <a href="http://www.satchmoproject.com/">Satchmo</a> seems to install a <strong>lot</strong> of applications and extra stuff that I don't need. I've heard others mention <a href="http://code.google.com/p/django-cart/">django-cart</a>. Has anyone tried this Django app (django-cart)? Anything to watch for or any other experiences?</p>
23
2009-01-29T04:00:49Z
493,895
<p>As mentioned above, Django-cart hasn't been updated in a long time so it is most likely not compatible with Django 1.0 and the more recent versions of Django. For that reason alone, I'd recommend sticking with something more recent.</p> <p>I'm biased because I'm a dev on Satchmo but I think the feeling of overkill with Satchmo is a bit overblown. You'll probably be surprised at all the things you think you'll want to do with your "simple cart." Soon it may not be so simple.</p> <p>Worst case, if Satchmo is too much you can yank out the parts you don't care about.</p>
4
2009-01-29T23:05:52Z
[ "python", "django", "e-commerce", "satchmo" ]
django-cart or Satchmo?
490,439
<p>I'm looking to implement a very basic shopping cart. <a href="http://www.satchmoproject.com/">Satchmo</a> seems to install a <strong>lot</strong> of applications and extra stuff that I don't need. I've heard others mention <a href="http://code.google.com/p/django-cart/">django-cart</a>. Has anyone tried this Django app (django-cart)? Anything to watch for or any other experiences?</p>
23
2009-01-29T04:00:49Z
700,439
<p>Seems that a new version of Django-cart has been released on 25th March. <a href="http://vaig.be/2009/03/django-cart-released.html" rel="nofollow">http://vaig.be/2009/03/django-cart-released.html</a></p> <p>Wonder how the new version fares with respect to Satchmo.</p>
1
2009-03-31T07:43:41Z
[ "python", "django", "e-commerce", "satchmo" ]
django-cart or Satchmo?
490,439
<p>I'm looking to implement a very basic shopping cart. <a href="http://www.satchmoproject.com/">Satchmo</a> seems to install a <strong>lot</strong> of applications and extra stuff that I don't need. I've heard others mention <a href="http://code.google.com/p/django-cart/">django-cart</a>. Has anyone tried this Django app (django-cart)? Anything to watch for or any other experiences?</p>
23
2009-01-29T04:00:49Z
818,404
<p>I am using django-cart and it is not really an app - it is a start of an app. There are no views, and it totals about 150 lines of code. There is no doc but it is pretty clear how to use most of it. I am a little unsure of the intention of ItemManager or how that is supposed to be used. Comparing it to Satchmo is like comparing a flea to an elephant. They are a little different.</p>
0
2009-05-04T00:24:15Z
[ "python", "django", "e-commerce", "satchmo" ]
django-cart or Satchmo?
490,439
<p>I'm looking to implement a very basic shopping cart. <a href="http://www.satchmoproject.com/">Satchmo</a> seems to install a <strong>lot</strong> of applications and extra stuff that I don't need. I've heard others mention <a href="http://code.google.com/p/django-cart/">django-cart</a>. Has anyone tried this Django app (django-cart)? Anything to watch for or any other experiences?</p>
23
2009-01-29T04:00:49Z
16,063,883
<p><a href="http://www.satchmoproject.com/" rel="nofollow">Satchmo</a> has more features than <a href="http://code.google.com/p/django-cart/" rel="nofollow">django-cart</a>. If you are looking for simple and lightweight shopping cart application, try <a href="https://github.com/lazybird/django-carton" rel="nofollow">django-carton</a> which is pretty similar to django-cart.</p> <p>It helps with shopping cart operations such as adding and removing items. It's does not implement views, templates nor payment processing modules - you are free to build them your way. The cart lives in the session, not in the database. The cart items are arbitrary product objects so you can define your product model the way you want.</p>
1
2013-04-17T15:16:30Z
[ "python", "django", "e-commerce", "satchmo" ]
Regex replace (in Python) - a simpler way?
490,597
<p>Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like:</p> <pre><code>"(?P&lt;start&gt;some_pattern)(?P&lt;replace&gt;foo)(?P&lt;end&gt;end)" </code></pre> <p>And then concatenate the <code>start</code> group with the new data for <code>replace</code> and then the <code>end</code> group.</p> <p>Is there a better method for this?</p>
42
2009-01-29T05:43:24Z
490,609
<p>Look in the Python <a href="http://docs.python.org/library/re.html">re documentation</a> for lookaheads <code>(?=...)</code> and lookbehinds <code>(?&lt;=...)</code> -- I'm pretty sure they're what you want. They match strings, but do not "consume" the bits of the strings they match.</p>
18
2009-01-29T05:51:21Z
[ "python", "regex" ]
Regex replace (in Python) - a simpler way?
490,597
<p>Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like:</p> <pre><code>"(?P&lt;start&gt;some_pattern)(?P&lt;replace&gt;foo)(?P&lt;end&gt;end)" </code></pre> <p>And then concatenate the <code>start</code> group with the new data for <code>replace</code> and then the <code>end</code> group.</p> <p>Is there a better method for this?</p>
42
2009-01-29T05:43:24Z
490,616
<pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; s = "start foo end" &gt;&gt;&gt; s = re.sub("foo", "replaced", s) &gt;&gt;&gt; s 'start replaced end' &gt;&gt;&gt; s = re.sub("(?&lt;= )(.+)(?= )", lambda m: "can use a callable for the %s text too" % m.group(1), s) &gt;&gt;&gt; s 'start can use a callable for the replaced text too end' &gt;&gt;&gt; help(re.sub) Help on function sub in module re: sub(pattern, repl, string, count=0) Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a callable, it's passed the match object and must return a replacement string to be used. </code></pre>
105
2009-01-29T05:56:21Z
[ "python", "regex" ]
Regex replace (in Python) - a simpler way?
490,597
<p>Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like:</p> <pre><code>"(?P&lt;start&gt;some_pattern)(?P&lt;replace&gt;foo)(?P&lt;end&gt;end)" </code></pre> <p>And then concatenate the <code>start</code> group with the new data for <code>replace</code> and then the <code>end</code> group.</p> <p>Is there a better method for this?</p>
42
2009-01-29T05:43:24Z
491,966
<p>The short version is that you <em>cannot use</em> variable-width patterns in lookbehinds using Python's <code>re</code> module. There is no way to change this:</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; re.sub("(?&lt;=foo)bar(?=baz)", "quux", "foobarbaz") 'fooquuxbaz' &gt;&gt;&gt; re.sub("(?&lt;=fo+)bar(?=baz)", "quux", "foobarbaz") Traceback (most recent call last): File "&lt;pyshell#2&gt;", line 1, in &lt;module&gt; re.sub("(?&lt;=fo+)bar(?=baz)", "quux", string) File "C:\Development\Python25\lib\re.py", line 150, in sub return _compile(pattern, 0).sub(repl, string, count) File "C:\Development\Python25\lib\re.py", line 241, in _compile raise error, v # invalid expression error: look-behind requires fixed-width pattern </code></pre> <p>This means that you'll need to work around it, the simplest solution being very similar to what you're doing now:</p> <pre><code>&gt;&gt;&gt; re.sub("(fo+)bar(?=baz)", "\\1quux", "foobarbaz") 'fooquuxbaz' &gt;&gt;&gt; &gt;&gt;&gt; # If you need to turn this into a callable function: &gt;&gt;&gt; def replace(start, replace, end, replacement, search): return re.sub("(" + re.escape(start) + ")" + re.escape(replace) + "(?=" + re.escape + ")", "\\1" + re.escape(replacement), search) </code></pre> <p>This doesn't have the elegance of the lookbehind solution, but it's still a very clear, straightforward one-liner. And if you look at what <a href="http://blog.stevenlevithan.com/archives/mimic-lookbehind-javascript">an expert has to say on the matter</a> (he's talking about JavaScript, which lacks lookbehinds entirely, but many of the principles are the same), you'll see that his simplest solution looks a lot like this one.</p>
11
2009-01-29T15:11:48Z
[ "python", "regex" ]
Regex replace (in Python) - a simpler way?
490,597
<p>Any time I want to replace a piece of text that is part of a larger piece of text, I always have to do something like:</p> <pre><code>"(?P&lt;start&gt;some_pattern)(?P&lt;replace&gt;foo)(?P&lt;end&gt;end)" </code></pre> <p>And then concatenate the <code>start</code> group with the new data for <code>replace</code> and then the <code>end</code> group.</p> <p>Is there a better method for this?</p>
42
2009-01-29T05:43:24Z
2,053,304
<p>I believe that the best idea is just to capture in a group whatever you want to replace, and then replace it by using the start and end properties of the captured group.</p> <p>regards</p> <p>Adrián</p> <pre><code>#the pattern will contain the expression we want to replace as the first group pat = "word1\s(.*)\sword2" test = "word1 will never be a word2" repl = "replace" import re m = re.search(pat,test) if m and m.groups() &gt; 0: line = test[:m.start(1)] + repl + test[m.end(1):] print line else: print "the pattern didn't capture any text" </code></pre> <p>This will print: 'word1 will never be a word2'</p> <p>The group to be replaced could be located in any position of the string.</p>
4
2010-01-12T23:39:10Z
[ "python", "regex" ]
Statistics & other add-on tools for Planet blog aggregator software
490,634
<p>The Planet software is often used for particular topics or large projects, to collect blogs that post on a particular theme. <a href="http://www.planetplanet.org/" rel="nofollow">http://www.planetplanet.org/</a></p> <p>I think there are lots of interesting add-ons that could be done for it but so far I haven't seen any. Does anyone know any? (Because of the name, it's kinda hard to search for...)</p> <p>Like: - for users, subscribe to a planet, but block particular posters (maybe some kind of Greasemonkey script for google reader?) - Statistics for a planet - how long have various blogs been 'members', how regularly do each of them post? Which posters typically get the most comments?</p> <p>BTW this should have the tag "planet" :)</p>
2
2009-01-29T06:09:33Z
7,552,287
<p>Answer: No, there are no addons afaik. You could write them. :-)</p>
0
2011-09-26T08:11:56Z
[ "python", "blogs", "add-on" ]
regex: Matching parts of a string when the string contains part of a regex pattern
490,762
<p>I want to reduce the number of patterns I have to write by using a regex that picks up any or all of the pattern when it appears in a string.</p> <p>Is this possible with Regex?</p> <pre><code>E.g. Pattern is: "the cat sat on the mat" I would like pattern to match on following strings: "the" "the cat" "the cat sat" ... "the cat sat on the mat" </code></pre> <p>But it should not match on the following string because although some words match, they are split by a non matching word: "the dog sat"</p>
1
2009-01-29T07:21:53Z
490,767
<p>If you know the match always begins at the first character, it would be much faster to match the characters directly in a loop. I don't think Regex will do it anyway.</p>
1
2009-01-29T07:24:58Z
[ "python", "regex" ]
regex: Matching parts of a string when the string contains part of a regex pattern
490,762
<p>I want to reduce the number of patterns I have to write by using a regex that picks up any or all of the pattern when it appears in a string.</p> <p>Is this possible with Regex?</p> <pre><code>E.g. Pattern is: "the cat sat on the mat" I would like pattern to match on following strings: "the" "the cat" "the cat sat" ... "the cat sat on the mat" </code></pre> <p>But it should not match on the following string because although some words match, they are split by a non matching word: "the dog sat"</p>
1
2009-01-29T07:21:53Z
490,785
<p>It could be fairly complicated:</p> <pre><code>(?ms)the(?=(\s+cat)|[\r\n]+)(:?\s+cat(?=(\s+sat)|[\r\n]+))?(:?\s+sat(?=(\s+on)|[\r\n]+))?(:?\s+on(?=(\s+the)|[\r\n]+))?(:?\s+the(?=(\s+mat)|[\r\n]+))?(:?\s+mat)?[\r\n]+ </code></pre> <p>Meaning:</p> <ul> <li>I want "<code>the</code>" only if followed by "<code>cat</code>" or end of line</li> <li>then I want "<code>cat</code>" (optional) only if followed by "<code>sat</code>"</li> <li>and so one</li> <li>followed by and end of line (which ensure to not match partial "the cat walk...")</li> </ul> <p>It does match </p> <p><strong>the cat sat on the mat</strong><br /> <strong>the cat</strong><br /> <strong>the cat sat</strong><br /> the cat sat aa on the mat (nothing is match either)<br /> the dog sat (nothing is matched there)</p> <p><hr /></p> <p>On second thought, <a href="http://stackoverflow.com/questions/490762#490794">Tomalak's answer</a> is simpler (if fixed, that is ended with a '$').<br /> I keep mine as a wiki post.</p>
2
2009-01-29T07:35:42Z
[ "python", "regex" ]
regex: Matching parts of a string when the string contains part of a regex pattern
490,762
<p>I want to reduce the number of patterns I have to write by using a regex that picks up any or all of the pattern when it appears in a string.</p> <p>Is this possible with Regex?</p> <pre><code>E.g. Pattern is: "the cat sat on the mat" I would like pattern to match on following strings: "the" "the cat" "the cat sat" ... "the cat sat on the mat" </code></pre> <p>But it should not match on the following string because although some words match, they are split by a non matching word: "the dog sat"</p>
1
2009-01-29T07:21:53Z
490,794
<p>This:</p> <pre><code>the( cat( sat( on( the( mat)?)?)?)?)? </code></pre> <p>would answer your question. Remove "optional group" parens "(...)?" for parts that are not optional, add additional groups for things that must match together.</p> <pre><code>the // complete match the cat // complete match the cat sat // complete match the cat sat on // complete match the cat sat on the // complete match the cat sat on the mat // complete match the dog sat on the mat // two partial matches ("the") </code></pre> <p>You might want to add some pre-condition, like a start of line anchor, to prevent the expression from matching the second "the" in the last line:</p> <pre><code>^the( cat( sat( on( the( mat)?)?)?)?)? </code></pre> <p><strong>EDIT:</strong> If you add a post-condition, like the end-of-line anchor, matching will be prevented entirely on the last example, that is, the last example won't match at all:</p> <pre><code>the( cat( sat( on( the( mat)?)?)?)?)?$ </code></pre> <p>Credits for the tip go to <a href="http://stackoverflow.com/questions/490762/regex-matching-parts-of-a-string-when-the-string-contains-part-of-a-regex-patter#490785">VonC</a>. Thanks!</p> <p>The post-condition may of course be something else you expect to follow the match. </p> <p>Alternatively, you remove the last question mark:</p> <pre><code>the( cat( sat( on( the( mat)?)?)?)?) </code></pre> <p>Be aware though: This would make a single "the" a non-match, so the first line will also not match.</p>
7
2009-01-29T07:42:14Z
[ "python", "regex" ]
regex: Matching parts of a string when the string contains part of a regex pattern
490,762
<p>I want to reduce the number of patterns I have to write by using a regex that picks up any or all of the pattern when it appears in a string.</p> <p>Is this possible with Regex?</p> <pre><code>E.g. Pattern is: "the cat sat on the mat" I would like pattern to match on following strings: "the" "the cat" "the cat sat" ... "the cat sat on the mat" </code></pre> <p>But it should not match on the following string because although some words match, they are split by a non matching word: "the dog sat"</p>
1
2009-01-29T07:21:53Z
491,687
<p>Perhaps it would be easier and more logical to think about the problem a little differently..</p> <p>Instead of matching the pattern against the string.... how about using the string as the pattern and looking for it in the pattern.</p> <p>For example where</p> <p>string = "the cat sat on" pattern = "the cat sat on the mat"</p> <p>string is always a subset of pattern and is simply a case of doing a regex match.</p> <p>If that makes sense ;-)</p>
0
2009-01-29T14:01:49Z
[ "python", "regex" ]
MSN with Python
490,929
<p>I have plans to create a simple bot for a game I run and have it sit on MSN and answer queries. I want to use Python to do this and googled around and found <a href="http://msnp.sourceforge.net/" rel="nofollow">MSNP</a>. I thought "great" and "how awesome" but it appears that it's about 5 years old and oddly enough doesn't connect to MSN as they've probably changed one or two small little things over the years.</p> <p>Does anybody know of something equivalent to that?</p>
2
2009-01-29T08:51:45Z
490,933
<p>I don't know of anything equivalent, but you can look at the source to <a href="http://developer.pidgin.im/wiki/WhatIsLibpurple" rel="nofollow">libpurple</a> and roll your own without a terrible amount of difficulty.</p>
1
2009-01-29T08:53:03Z
[ "python", "msn" ]
MSN with Python
490,929
<p>I have plans to create a simple bot for a game I run and have it sit on MSN and answer queries. I want to use Python to do this and googled around and found <a href="http://msnp.sourceforge.net/" rel="nofollow">MSNP</a>. I thought "great" and "how awesome" but it appears that it's about 5 years old and oddly enough doesn't connect to MSN as they've probably changed one or two small little things over the years.</p> <p>Does anybody know of something equivalent to that?</p>
2
2009-01-29T08:51:45Z
491,368
<p>If you're prepared to do some hard work with the original source code, you could update it to support the current version of the MSN protocol:</p> <p><a href="http://msnpiki.msnfanatic.com/index.php/Main_Page" rel="nofollow">http://msnpiki.msnfanatic.com/index.php/Main_Page</a></p>
1
2009-01-29T12:16:13Z
[ "python", "msn" ]
MSN with Python
490,929
<p>I have plans to create a simple bot for a game I run and have it sit on MSN and answer queries. I want to use Python to do this and googled around and found <a href="http://msnp.sourceforge.net/" rel="nofollow">MSNP</a>. I thought "great" and "how awesome" but it appears that it's about 5 years old and oddly enough doesn't connect to MSN as they've probably changed one or two small little things over the years.</p> <p>Does anybody know of something equivalent to that?</p>
2
2009-01-29T08:51:45Z
4,487,016
<p>You can use <a href="http://blitiri.com.ar/p/msnlib/" rel="nofollow"><code>msnlib</code></a>, which after a quick test seems to be up to date, and is quite a small and readable library in two files, with a reference implementation of a few cli chat clients and chat bots.</p>
1
2010-12-20T05:03:19Z
[ "python", "msn" ]
No code completion and syntax highlighting in Pydev
491,053
<p>I just configured Eclipse with PyDev latest version, but when I import external modules, neither code completion nor syntax highlighting works. How do I enable it?</p> <p>Komodo Edit does a better synax highlighting, apparently. - But Ctrl+R doesnt run the program. </p> <p>I prefer a SciTE kind of editor with similar highlighting and fonts (aesthetics) and F5 working but with display of folder and files dynamically like Komodo Edit and a better code completion and vi emulation. Suggestions, please.</p> <p>If I want to buy a Py IDE, Komodo or Wingware, which is better?-- Wrt syntax highlighting and code completion</p>
12
2009-01-29T09:50:56Z
492,073
<p>To enable code completion, go to Window > Preferences > Pydev > Editor > Code Completion, and check the 'Use Code Completion?' box, as well as the other boxes for what you want to complete on. It seems to take a second to load, the first time it has to complete something.</p> <p>Syntax coloring should just work by default. Right-click on the file in the package explorer, go to 'Open With', and make sure you're opening it with the Python Editor, and not the regular Text Editor.</p> <p>I don't know exactly what you mean by importing external modules. I have my source in a separate directory structure on disk; my PyDev projects contain folders linked to those. Code completion works for that, as well as other modules like 'os'. If you're having troubles, are the modules added to the PyDev's Python search path (not necessarily the same as the regular one)?</p> <p>I took a brief look at Komodo and Wingware a while back, so I can't answer the second part of your question. But ended up going with PyDev. I'm not a big fan of Eclipse, but PyDev works reasonably well for me.</p>
21
2009-01-29T15:32:20Z
[ "python", "ide" ]
No code completion and syntax highlighting in Pydev
491,053
<p>I just configured Eclipse with PyDev latest version, but when I import external modules, neither code completion nor syntax highlighting works. How do I enable it?</p> <p>Komodo Edit does a better synax highlighting, apparently. - But Ctrl+R doesnt run the program. </p> <p>I prefer a SciTE kind of editor with similar highlighting and fonts (aesthetics) and F5 working but with display of folder and files dynamically like Komodo Edit and a better code completion and vi emulation. Suggestions, please.</p> <p>If I want to buy a Py IDE, Komodo or Wingware, which is better?-- Wrt syntax highlighting and code completion</p>
12
2009-01-29T09:50:56Z
495,297
<p>Well, I tried the Wing Professional and I think its really the best Py IDE out there.</p>
0
2009-01-30T12:03:46Z
[ "python", "ide" ]
No code completion and syntax highlighting in Pydev
491,053
<p>I just configured Eclipse with PyDev latest version, but when I import external modules, neither code completion nor syntax highlighting works. How do I enable it?</p> <p>Komodo Edit does a better synax highlighting, apparently. - But Ctrl+R doesnt run the program. </p> <p>I prefer a SciTE kind of editor with similar highlighting and fonts (aesthetics) and F5 working but with display of folder and files dynamically like Komodo Edit and a better code completion and vi emulation. Suggestions, please.</p> <p>If I want to buy a Py IDE, Komodo or Wingware, which is better?-- Wrt syntax highlighting and code completion</p>
12
2009-01-29T09:50:56Z
495,362
<p>Between komodo and wingide i would go for wing. The license is not that expensive and the fact that it is commercial gives you a bigger probability of more updates and bug fixes. If you, like me, prefer a free solution, then stick with pydev. At least until aptana closes the free door :)</p>
0
2009-01-30T12:28:52Z
[ "python", "ide" ]
No code completion and syntax highlighting in Pydev
491,053
<p>I just configured Eclipse with PyDev latest version, but when I import external modules, neither code completion nor syntax highlighting works. How do I enable it?</p> <p>Komodo Edit does a better synax highlighting, apparently. - But Ctrl+R doesnt run the program. </p> <p>I prefer a SciTE kind of editor with similar highlighting and fonts (aesthetics) and F5 working but with display of folder and files dynamically like Komodo Edit and a better code completion and vi emulation. Suggestions, please.</p> <p>If I want to buy a Py IDE, Komodo or Wingware, which is better?-- Wrt syntax highlighting and code completion</p>
12
2009-01-29T09:50:56Z
1,399,741
<p>Check to see if the 'P' icon is appearing for your items and in the top of your editor after opening it. If it's not appearing, it may be that there's a problem with the file association, so, go to window > preferences > general > editors > file associations and make sure that the .py files are associated with the Python Editor (note that because of an eclipse bug, if it seems correct, you may have to remove the association and add it again)</p>
2
2009-09-09T13:38:23Z
[ "python", "ide" ]
No code completion and syntax highlighting in Pydev
491,053
<p>I just configured Eclipse with PyDev latest version, but when I import external modules, neither code completion nor syntax highlighting works. How do I enable it?</p> <p>Komodo Edit does a better synax highlighting, apparently. - But Ctrl+R doesnt run the program. </p> <p>I prefer a SciTE kind of editor with similar highlighting and fonts (aesthetics) and F5 working but with display of folder and files dynamically like Komodo Edit and a better code completion and vi emulation. Suggestions, please.</p> <p>If I want to buy a Py IDE, Komodo or Wingware, which is better?-- Wrt syntax highlighting and code completion</p>
12
2009-01-29T09:50:56Z
1,836,524
<p>The typical reason that code completion doesn't work under PyDev is that the libraries aren't in the PYTHONPATH. If you go into the Project Properties, and setup PyDev PYTHONPATH preferences to include the places where the code you are trying to complete lives, it will work just fine...</p> <p>Project > Properties > PyDev-PYTHONPAH > click 'Add source folder'</p>
8
2009-12-02T23:07:53Z
[ "python", "ide" ]
No code completion and syntax highlighting in Pydev
491,053
<p>I just configured Eclipse with PyDev latest version, but when I import external modules, neither code completion nor syntax highlighting works. How do I enable it?</p> <p>Komodo Edit does a better synax highlighting, apparently. - But Ctrl+R doesnt run the program. </p> <p>I prefer a SciTE kind of editor with similar highlighting and fonts (aesthetics) and F5 working but with display of folder and files dynamically like Komodo Edit and a better code completion and vi emulation. Suggestions, please.</p> <p>If I want to buy a Py IDE, Komodo or Wingware, which is better?-- Wrt syntax highlighting and code completion</p>
12
2009-01-29T09:50:56Z
4,665,424
<p>It sounds like you have to specify the location of the Python interpreter. Do this under Preferences > Pydev > Interpreter - Python. Create a new interpreter and point it to the Python interpreter executable.</p>
1
2011-01-12T04:47:00Z
[ "python", "ide" ]
No code completion and syntax highlighting in Pydev
491,053
<p>I just configured Eclipse with PyDev latest version, but when I import external modules, neither code completion nor syntax highlighting works. How do I enable it?</p> <p>Komodo Edit does a better synax highlighting, apparently. - But Ctrl+R doesnt run the program. </p> <p>I prefer a SciTE kind of editor with similar highlighting and fonts (aesthetics) and F5 working but with display of folder and files dynamically like Komodo Edit and a better code completion and vi emulation. Suggestions, please.</p> <p>If I want to buy a Py IDE, Komodo or Wingware, which is better?-- Wrt syntax highlighting and code completion</p>
12
2009-01-29T09:50:56Z
17,847,161
<p>Make sure you use 'Open With' as 'Python Editor' by right clicking on the file - It worked for me </p>
4
2013-07-25T00:43:03Z
[ "python", "ide" ]
No code completion and syntax highlighting in Pydev
491,053
<p>I just configured Eclipse with PyDev latest version, but when I import external modules, neither code completion nor syntax highlighting works. How do I enable it?</p> <p>Komodo Edit does a better synax highlighting, apparently. - But Ctrl+R doesnt run the program. </p> <p>I prefer a SciTE kind of editor with similar highlighting and fonts (aesthetics) and F5 working but with display of folder and files dynamically like Komodo Edit and a better code completion and vi emulation. Suggestions, please.</p> <p>If I want to buy a Py IDE, Komodo or Wingware, which is better?-- Wrt syntax highlighting and code completion</p>
12
2009-01-29T09:50:56Z
18,933,901
<p>Check your Theme configuration. Python highlighting uses Theme Colors</p>
0
2013-09-21T14:39:21Z
[ "python", "ide" ]
No code completion and syntax highlighting in Pydev
491,053
<p>I just configured Eclipse with PyDev latest version, but when I import external modules, neither code completion nor syntax highlighting works. How do I enable it?</p> <p>Komodo Edit does a better synax highlighting, apparently. - But Ctrl+R doesnt run the program. </p> <p>I prefer a SciTE kind of editor with similar highlighting and fonts (aesthetics) and F5 working but with display of folder and files dynamically like Komodo Edit and a better code completion and vi emulation. Suggestions, please.</p> <p>If I want to buy a Py IDE, Komodo or Wingware, which is better?-- Wrt syntax highlighting and code completion</p>
12
2009-01-29T09:50:56Z
19,301,447
<p>In case anyone else makes the embarrassing mistake that I did: be sure your source code file actually ends with ".py". Even if its in a Python project, PyDev won't guess without the extension. </p>
0
2013-10-10T16:37:05Z
[ "python", "ide" ]
No code completion and syntax highlighting in Pydev
491,053
<p>I just configured Eclipse with PyDev latest version, but when I import external modules, neither code completion nor syntax highlighting works. How do I enable it?</p> <p>Komodo Edit does a better synax highlighting, apparently. - But Ctrl+R doesnt run the program. </p> <p>I prefer a SciTE kind of editor with similar highlighting and fonts (aesthetics) and F5 working but with display of folder and files dynamically like Komodo Edit and a better code completion and vi emulation. Suggestions, please.</p> <p>If I want to buy a Py IDE, Komodo or Wingware, which is better?-- Wrt syntax highlighting and code completion</p>
12
2009-01-29T09:50:56Z
25,439,963
<p><strong>If you want to work with Eclipse please have a look at these pluggins.</strong></p> <p>-To make your eclipse editor work like vim. I use this plugin. <a href="http://vrapper.sourceforge.net/home/" rel="nofollow">http://vrapper.sourceforge.net/home/</a></p> <p>-Then if you do something with HTML,CSS etc. This plug in might be useful. <a href="https://github.com/emmetio/emmet-eclipse" rel="nofollow">https://github.com/emmetio/emmet-eclipse</a></p> <p><strong>If you are looking for a Text editor. I suggest you to use:-</strong></p> <p>Either <strong>Notepad++ (in Windows)</strong> - with plugins like - ViSimulator - Emmet - Explorer - Python Script - NppExec</p> <p><strong>Kate(KDE Advanced Text editro)</strong>,[In Linux], which have vim mode and many features. In my view, it has better syntax support too. I am not sure it have pluggins or not.</p> <p>I am sure you have read the answers of DNS and tim-white</p>
0
2014-08-22T05:13:15Z
[ "python", "ide" ]
No code completion and syntax highlighting in Pydev
491,053
<p>I just configured Eclipse with PyDev latest version, but when I import external modules, neither code completion nor syntax highlighting works. How do I enable it?</p> <p>Komodo Edit does a better synax highlighting, apparently. - But Ctrl+R doesnt run the program. </p> <p>I prefer a SciTE kind of editor with similar highlighting and fonts (aesthetics) and F5 working but with display of folder and files dynamically like Komodo Edit and a better code completion and vi emulation. Suggestions, please.</p> <p>If I want to buy a Py IDE, Komodo or Wingware, which is better?-- Wrt syntax highlighting and code completion</p>
12
2009-01-29T09:50:56Z
35,208,736
<p>When syntax highlighting was not working for me using PyDev, I discovered that there were somehow two 'Python Editor' associations defined for .py files in my installation of Eclipse/PyDev. From the Eclipse Main Menu, go to Window > Preferences > General > Editors > FileAssociations to see the file extension &lt;-> editor mapping. I set a different one as default for .py files at the bottom of the dialog, and got syntax highlighting working again.</p>
0
2016-02-04T18:24:59Z
[ "python", "ide" ]
How can I pass a filename as a parameter into my module?
491,085
<p>I have the following code in .py file:</p> <pre><code>import re regex = re.compile( r"""ULLAT:\ (?P&lt;ullat&gt;-?[\d.]+).*? ULLON:\ (?P&lt;ullon&gt;-?[\d.]+).*? LRLAT:\ (?P&lt;lrlat&gt;-?[\d.]+)""", re.DOTALL|re.VERBOSE) </code></pre> <p>I have the data in .txt file as a sequence:</p> <pre><code>QUADNAME: rockport_colony_SD RESOLUTION: 10 ULLAT: 43.625 ULLON: -97.87527466 LRLAT: 43.5 LRLON: -97.75027466 HDATUM: 27 ZMIN: 361.58401489 ZMAX: 413.38400269 ZMEAN: 396.1293335 ZSIGMA: 12.36359215 PMETHOD: 5 QUADDATE: 20001001 </code></pre> <p>How can I use the Python -file to process the .txt -file? </p> <p>I guess that we need a parameter in the .py file, so that we can use a syntax like in terminal: </p> <pre><code>$ py-file file-to-be-processed </code></pre> <p>This question was raised by the post <a href="http://stackoverflow.com/questions/489901/how-can-i-extract-x-y-and-z-coordinates-from-geographical-data-by-python/490347#490347">here</a>.</p>
5
2009-01-29T10:04:13Z
491,189
<p>You need to read the file in and then search the contents using the regular expression. The sys module contains a list, argv, which contains all the command line parameters. We pull out the second one (the first is the file name used to run the script), open the file, and then read in the contents.</p> <pre> import re import sys file_name = sys.argv[1] fp = open(file_name) contents = fp.read() regex = re.compile( r"""ULLAT:\ (?P-?[\d.]+).*? ULLON:\ (?P-?[\d.]+).*? LRLAT:\ (?P-?[\d.]+)""", re.DOTALL|re.VERBOSE) match = regex.search(contents) </pre> <p>See the <a href="http://docs.python.org/library/re.html#id1" rel="nofollow">Python regular expression documentation</a> for details on what you can do with the match object. See <a href="http://docs.python.org/library/re.html#search-vs-match" rel="nofollow">this part of the documentation</a> for why we need search rather than match when scanning the file.</p> <p>This code will allow you to use the syntax you specified in your question.</p>
14
2009-01-29T10:50:05Z
[ "python", "command-line", "parameters", "module" ]
Can you recommend a Python SOAP client that can accept WS-Attachments?
491,404
<p>I've read mixed reviews of both <a href="https://fedorahosted.org/suds/" rel="nofollow">Suds</a> and <a href="http://pywebsvcs.sourceforge.net/" rel="nofollow">ZSI</a> -- two Python SOAP libraries. However, I'm unclear whether either of them can support WS-Attachments. I'd prefer to use Suds (appears to be more straightforward), but I'll defer to whichever library suits my needs.</p>
3
2009-01-29T12:27:47Z
557,079
<p>For your requirements I'd have to recommend ZSI. From its documentation,</p> <blockquote> It can also be used to build applications using SOAP Messages with Attachments. </blockquote> <p>Their website is not as pretty as Suds but the package includes promising documentation.</p> <p>SOAPpy has support for attachments on its TODO list. Suds does not mention the word "attachments" anywhere. If you need attachments and don't want to implement them yourself, then ZSI is your choice.</p>
1
2009-02-17T14:33:38Z
[ "python", "soap" ]
Can you recommend a Python SOAP client that can accept WS-Attachments?
491,404
<p>I've read mixed reviews of both <a href="https://fedorahosted.org/suds/" rel="nofollow">Suds</a> and <a href="http://pywebsvcs.sourceforge.net/" rel="nofollow">ZSI</a> -- two Python SOAP libraries. However, I'm unclear whether either of them can support WS-Attachments. I'd prefer to use Suds (appears to be more straightforward), but I'll defer to whichever library suits my needs.</p>
3
2009-01-29T12:27:47Z
557,164
<p>I believe <a href="http://trac.optio.webfactional.com/" rel="nofollow">soaplib</a> can handle attachments. I'm just not sure exactly how compliant it is with WS-Attachments because they don't trumpet it.</p> <p>Here's a sample client that, their words, allows "multi-part mime payloads":</p> <p><a href="http://trac.optio.webfactional.com/browser/soaplib/trunk/examples/helloworld_attach.py" rel="nofollow">helloworld_attach.py</a></p>
1
2009-02-17T14:49:03Z
[ "python", "soap" ]
Can you recommend a Python SOAP client that can accept WS-Attachments?
491,404
<p>I've read mixed reviews of both <a href="https://fedorahosted.org/suds/" rel="nofollow">Suds</a> and <a href="http://pywebsvcs.sourceforge.net/" rel="nofollow">ZSI</a> -- two Python SOAP libraries. However, I'm unclear whether either of them can support WS-Attachments. I'd prefer to use Suds (appears to be more straightforward), but I'll defer to whichever library suits my needs.</p>
3
2009-01-29T12:27:47Z
563,207
<p>In my experience Suds was the only Python package that actually works. I did not use attachments.</p>
0
2009-02-18T22:50:52Z
[ "python", "soap" ]
Python: Problem with local modules shadowing global modules
491,705
<p>I've got a package set up like so:</p> <pre><code>packagename/ __init__.py numbers.py tools.py ...other stuff </code></pre> <p>Now inside <code>tools.py</code>, I'm trying to import the standard library module <code>fractions</code>. However, the <code>fractions</code> module itself imports the <code>numbers</code> module, which is supposed to be the one in the standard library.</p> <p>The problem is that it tries to import the <code>numbers</code> modules from <em>my</em> package instead (ie my <code>numbers.py</code> is shadowing the stdlib <code>numbers</code> module), and then complains about it, instead of importing the stdlib module.</p> <p>My question is, is there a workaround so that I can keep the current structure of my package, or is the only solution to rename my own offending module (<code>numbers.py</code>)?</p>
9
2009-01-29T14:04:51Z
491,813
<p><a href="http://www.python.org/dev/peps/pep-0328/">absolute and relative imports</a> can be used since python2.5 (with <code>__future__</code> import) and seem to be what you're looking for.</p>
8
2009-01-29T14:33:14Z
[ "python" ]
Python: Problem with local modules shadowing global modules
491,705
<p>I've got a package set up like so:</p> <pre><code>packagename/ __init__.py numbers.py tools.py ...other stuff </code></pre> <p>Now inside <code>tools.py</code>, I'm trying to import the standard library module <code>fractions</code>. However, the <code>fractions</code> module itself imports the <code>numbers</code> module, which is supposed to be the one in the standard library.</p> <p>The problem is that it tries to import the <code>numbers</code> modules from <em>my</em> package instead (ie my <code>numbers.py</code> is shadowing the stdlib <code>numbers</code> module), and then complains about it, instead of importing the stdlib module.</p> <p>My question is, is there a workaround so that I can keep the current structure of my package, or is the only solution to rename my own offending module (<code>numbers.py</code>)?</p>
9
2009-01-29T14:04:51Z
492,041
<p>I try to avoid shadowing the standard library. How about renaming your module to "_numbers.py" ?</p> <p>And of course, you could still do:</p> <pre><code>import _numbers as numbers </code></pre>
4
2009-01-29T15:25:15Z
[ "python" ]
Using the input collected from raw_input in Python
491,837
<p>If I do the following in python,</p> <pre><code>string = raw_input('Enter the value') </code></pre> <p>it will return </p> <blockquote> <p>Enter the value</p> </blockquote> <p>and wait until I enter something into the prompt.</p> <p>Is there a way to retrieve/collect the input I entered in a variable <code>string</code>?</p> <p>I would like to use the entered value in the following way :</p> <pre><code>if dict.has_key('string'): print dict[string] </code></pre> <p><sub>Note: <em>I previously made the error of using <code>raw_string</code> but I meant to say <code>raw_input</code></em></sub></p>
0
2009-01-29T14:39:54Z
491,868
<p>This is very confusing ... I'm not familiar with a raw_string function in Python, but perhaps it's application-specific? </p> <p>Reading a line of input in Python can be done like this:</p> <pre><code>import sys line = sys.stdin.readline() </code></pre> <p>Then you have that line, terminating linefeed and all, in the variable line, so you can work with it, e.g. use it has a hash key:</p> <pre><code>line = line.strip() if line in dict: print dict[line] </code></pre> <p>The first line strips away that trailing newline, since you hash keys probably don't have them.</p> <p>I hope this helps, otherwise please try being a bit clearer in your question.</p>
4
2009-01-29T14:46:31Z
[ "python", "raw-input" ]
Using the input collected from raw_input in Python
491,837
<p>If I do the following in python,</p> <pre><code>string = raw_input('Enter the value') </code></pre> <p>it will return </p> <blockquote> <p>Enter the value</p> </blockquote> <p>and wait until I enter something into the prompt.</p> <p>Is there a way to retrieve/collect the input I entered in a variable <code>string</code>?</p> <p>I would like to use the entered value in the following way :</p> <pre><code>if dict.has_key('string'): print dict[string] </code></pre> <p><sub>Note: <em>I previously made the error of using <code>raw_string</code> but I meant to say <code>raw_input</code></em></sub></p>
0
2009-01-29T14:39:54Z
491,874
<p>there's no <code>raw_string</code> function in python's stdlib. do you mean raw_input?</p> <pre><code>string = raw_input("Enter the value") # or just input in python3.0 print(string) </code></pre>
5
2009-01-29T14:47:52Z
[ "python", "raw-input" ]
Using the input collected from raw_input in Python
491,837
<p>If I do the following in python,</p> <pre><code>string = raw_input('Enter the value') </code></pre> <p>it will return </p> <blockquote> <p>Enter the value</p> </blockquote> <p>and wait until I enter something into the prompt.</p> <p>Is there a way to retrieve/collect the input I entered in a variable <code>string</code>?</p> <p>I would like to use the entered value in the following way :</p> <pre><code>if dict.has_key('string'): print dict[string] </code></pre> <p><sub>Note: <em>I previously made the error of using <code>raw_string</code> but I meant to say <code>raw_input</code></em></sub></p>
0
2009-01-29T14:39:54Z
491,882
<p>Is this what you want to do?</p> <pre><code>string = raw_input('Enter a value: ') string = string.strip() if string in dict: print dict[string] </code></pre>
3
2009-01-29T14:49:30Z
[ "python", "raw-input" ]
Using the input collected from raw_input in Python
491,837
<p>If I do the following in python,</p> <pre><code>string = raw_input('Enter the value') </code></pre> <p>it will return </p> <blockquote> <p>Enter the value</p> </blockquote> <p>and wait until I enter something into the prompt.</p> <p>Is there a way to retrieve/collect the input I entered in a variable <code>string</code>?</p> <p>I would like to use the entered value in the following way :</p> <pre><code>if dict.has_key('string'): print dict[string] </code></pre> <p><sub>Note: <em>I previously made the error of using <code>raw_string</code> but I meant to say <code>raw_input</code></em></sub></p>
0
2009-01-29T14:39:54Z
11,109,771
<p><code>import readline</code> provides a full terminal prompt to the <code>raw_input</code> function. You get control keys and history this way. Otherwise, it's no better than the <code>sys.stdin.readline()</code> option.</p> <pre><code>import readline while True: value = raw_input('Enter a value: ') value = value.strip() if value.lower() == 'quit': break </code></pre>
0
2012-06-19T21:32:50Z
[ "python", "raw-input" ]
Unicode (utf8) reading and writing to files in python
491,921
<p>I'm having some brain failure in understanding reading and writing text to a file (Python 2.4).</p> <pre><code># the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) </code></pre> <blockquote> <p>("u'Capit\xe1n'", "'Capit\xc3\xa1n'")</p> </blockquote> <pre><code>print ss, ss8 print &gt;&gt; open('f1','w'), ss8 &gt;&gt;&gt; file('f1').read() 'Capit\xc3\xa1n\n' </code></pre> <p>So I type in <code>Capit\xc3\xa1n</code> into my favorite editor, in file f2.</p> <p>then:</p> <pre><code>&gt;&gt;&gt; open('f1').read() 'Capit\xc3\xa1n\n' &gt;&gt;&gt; open('f2').read() 'Capit\\xc3\\xa1n\n' &gt;&gt;&gt; open('f1').read().decode('utf8') u'Capit\xe1n\n' &gt;&gt;&gt; open('f2').read().decode('utf8') u'Capit\\xc3\\xa1n\n' </code></pre> <p>What am I not understanding here? Clearly there is some vital bit of magic (or good sense) that I'm missing. What does one type into text files to get proper conversions.</p> <p><strong>Edit</strong>: What I'm truly failing to grok here, is what the point of the UTF-8 representation is, if you can't actually get Python to recognize it, when it comes from outside. Maybe I should just JSON dump the string, and use that instead, since that has an asciiable representation! More to the point, is there an ascii representation of this unicode object that Python will recognize and decode, when coming in from a file? If so, how do I get it?</p> <pre><code>&gt;&gt;&gt; print simplejson.dumps(ss) '"Capit\u00e1n"' &gt;&gt;&gt; print &gt;&gt; file('f3','w'), simplejson.dumps(ss) &gt;&gt;&gt; simplejson.load(open('f3')) u'Capit\xe1n' </code></pre>
189
2009-01-29T15:01:15Z
491,956
<p>the \x.. sequence is something that's specific to python. It's not a universal byte escape sequence. </p> <p>How you actually enter in utf8-encoded non-ascii depends on your OS and/or your editor. <a href="http://tlt.its.psu.edu/suggestions/international/accents/codealt.html" rel="nofollow">Here's how you do it in Windows</a>. For OS X to enter <em>a</em> with an acute accent you can just hit option-e, then a, and almost all text editors in OS X support utf8.</p>
3
2009-01-29T15:10:26Z
[ "python", "unicode", "utf-8", "io" ]
Unicode (utf8) reading and writing to files in python
491,921
<p>I'm having some brain failure in understanding reading and writing text to a file (Python 2.4).</p> <pre><code># the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) </code></pre> <blockquote> <p>("u'Capit\xe1n'", "'Capit\xc3\xa1n'")</p> </blockquote> <pre><code>print ss, ss8 print &gt;&gt; open('f1','w'), ss8 &gt;&gt;&gt; file('f1').read() 'Capit\xc3\xa1n\n' </code></pre> <p>So I type in <code>Capit\xc3\xa1n</code> into my favorite editor, in file f2.</p> <p>then:</p> <pre><code>&gt;&gt;&gt; open('f1').read() 'Capit\xc3\xa1n\n' &gt;&gt;&gt; open('f2').read() 'Capit\\xc3\\xa1n\n' &gt;&gt;&gt; open('f1').read().decode('utf8') u'Capit\xe1n\n' &gt;&gt;&gt; open('f2').read().decode('utf8') u'Capit\\xc3\\xa1n\n' </code></pre> <p>What am I not understanding here? Clearly there is some vital bit of magic (or good sense) that I'm missing. What does one type into text files to get proper conversions.</p> <p><strong>Edit</strong>: What I'm truly failing to grok here, is what the point of the UTF-8 representation is, if you can't actually get Python to recognize it, when it comes from outside. Maybe I should just JSON dump the string, and use that instead, since that has an asciiable representation! More to the point, is there an ascii representation of this unicode object that Python will recognize and decode, when coming in from a file? If so, how do I get it?</p> <pre><code>&gt;&gt;&gt; print simplejson.dumps(ss) '"Capit\u00e1n"' &gt;&gt;&gt; print &gt;&gt; file('f3','w'), simplejson.dumps(ss) &gt;&gt;&gt; simplejson.load(open('f3')) u'Capit\xe1n' </code></pre>
189
2009-01-29T15:01:15Z
491,967
<p>In the notation</p> <pre><code>u'Capit\xe1n\n' </code></pre> <p>the "\xe1" represents just one byte. "\x" tells you that "e1" is in hexadecimal. When you write</p> <pre><code>Capit\xc3\xa1n </code></pre> <p>into your file you have "\xc3" in it. Those are 4 bytes and in your code you read them all. You can see this when you display them:</p> <pre><code>&gt;&gt;&gt; open('f2').read() 'Capit\\xc3\\xa1n\n' </code></pre> <p>You can see that the backslash is escaped by a backslash. So you have four bytes in your string: "\", "x", "c" and "3".</p> <p>Edit:</p> <p>As others pointed out in their answers you should just enter the characters in the editor and your editor should then handle the conversion to UTF-8 and save it.</p> <p>If you actually have a string in this format you can use the <code>string_escape</code> codec to decode it into a normal string:</p> <pre><code>In [15]: print 'Capit\\xc3\\xa1n\n'.decode('string_escape') Capitán </code></pre> <p>The result is a string that is encoded in UTF-8 where the accented character is represented by the two bytes that were written <code>\\xc3\\xa1</code> in the original string. If you want to have a unicode string you have to decode again with UTF-8.</p> <p>To your edit: you don't have UTF-8 in your file. To actually see how it would look like:</p> <pre><code>s = u'Capit\xe1n\n' sutf8 = s.encode('UTF-8') open('utf-8.out', 'w').write(sutf8) </code></pre> <p>Compare the content of the file <code>utf-8.out</code> to the content of the file you saved with your editor.</p>
69
2009-01-29T15:11:59Z
[ "python", "unicode", "utf-8", "io" ]
Unicode (utf8) reading and writing to files in python
491,921
<p>I'm having some brain failure in understanding reading and writing text to a file (Python 2.4).</p> <pre><code># the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) </code></pre> <blockquote> <p>("u'Capit\xe1n'", "'Capit\xc3\xa1n'")</p> </blockquote> <pre><code>print ss, ss8 print &gt;&gt; open('f1','w'), ss8 &gt;&gt;&gt; file('f1').read() 'Capit\xc3\xa1n\n' </code></pre> <p>So I type in <code>Capit\xc3\xa1n</code> into my favorite editor, in file f2.</p> <p>then:</p> <pre><code>&gt;&gt;&gt; open('f1').read() 'Capit\xc3\xa1n\n' &gt;&gt;&gt; open('f2').read() 'Capit\\xc3\\xa1n\n' &gt;&gt;&gt; open('f1').read().decode('utf8') u'Capit\xe1n\n' &gt;&gt;&gt; open('f2').read().decode('utf8') u'Capit\\xc3\\xa1n\n' </code></pre> <p>What am I not understanding here? Clearly there is some vital bit of magic (or good sense) that I'm missing. What does one type into text files to get proper conversions.</p> <p><strong>Edit</strong>: What I'm truly failing to grok here, is what the point of the UTF-8 representation is, if you can't actually get Python to recognize it, when it comes from outside. Maybe I should just JSON dump the string, and use that instead, since that has an asciiable representation! More to the point, is there an ascii representation of this unicode object that Python will recognize and decode, when coming in from a file? If so, how do I get it?</p> <pre><code>&gt;&gt;&gt; print simplejson.dumps(ss) '"Capit\u00e1n"' &gt;&gt;&gt; print &gt;&gt; file('f3','w'), simplejson.dumps(ss) &gt;&gt;&gt; simplejson.load(open('f3')) u'Capit\xe1n' </code></pre>
189
2009-01-29T15:01:15Z
491,974
<p>Well, your favorite text editor does not realize that <code>\xc3\xa1</code> are supposed to be character literals, but interprets them as text. That's why you get the double backslashes in the last line -- it's now a real backslash + <code>xc3</code> etc in your file.</p> <p>If you want to read and write encoded files in Python, best use the <a href="http://docs.python.org/library/codecs.html#module-codecs" rel="nofollow">codecs</a> module.</p> <p>Pasting text between the terminal and applications is difficult, because you don't know which program will interpret your text using which encoding. You could try the following:</p> <pre><code>&gt;&gt;&gt; s = file("f1").read() &gt;&gt;&gt; print unicode(s, "Latin-1") Capitán </code></pre> <p>Then paste this string into your editor and make sure that it stores it using Latin-1. Under the assumption that the clipboard does not garble the string, the roundtrip should work.</p>
4
2009-01-29T15:13:11Z
[ "python", "unicode", "utf-8", "io" ]
Unicode (utf8) reading and writing to files in python
491,921
<p>I'm having some brain failure in understanding reading and writing text to a file (Python 2.4).</p> <pre><code># the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) </code></pre> <blockquote> <p>("u'Capit\xe1n'", "'Capit\xc3\xa1n'")</p> </blockquote> <pre><code>print ss, ss8 print &gt;&gt; open('f1','w'), ss8 &gt;&gt;&gt; file('f1').read() 'Capit\xc3\xa1n\n' </code></pre> <p>So I type in <code>Capit\xc3\xa1n</code> into my favorite editor, in file f2.</p> <p>then:</p> <pre><code>&gt;&gt;&gt; open('f1').read() 'Capit\xc3\xa1n\n' &gt;&gt;&gt; open('f2').read() 'Capit\\xc3\\xa1n\n' &gt;&gt;&gt; open('f1').read().decode('utf8') u'Capit\xe1n\n' &gt;&gt;&gt; open('f2').read().decode('utf8') u'Capit\\xc3\\xa1n\n' </code></pre> <p>What am I not understanding here? Clearly there is some vital bit of magic (or good sense) that I'm missing. What does one type into text files to get proper conversions.</p> <p><strong>Edit</strong>: What I'm truly failing to grok here, is what the point of the UTF-8 representation is, if you can't actually get Python to recognize it, when it comes from outside. Maybe I should just JSON dump the string, and use that instead, since that has an asciiable representation! More to the point, is there an ascii representation of this unicode object that Python will recognize and decode, when coming in from a file? If so, how do I get it?</p> <pre><code>&gt;&gt;&gt; print simplejson.dumps(ss) '"Capit\u00e1n"' &gt;&gt;&gt; print &gt;&gt; file('f3','w'), simplejson.dumps(ss) &gt;&gt;&gt; simplejson.load(open('f3')) u'Capit\xe1n' </code></pre>
189
2009-01-29T15:01:15Z
492,470
<p>You have stumbled over the general problem with encodings: How can I tell in which encoding a file is?</p> <p>Answer: You can't <em>unless</em> the file format provides for this. XML, for example, begins with:</p> <pre><code>&lt;?xml encoding="utf-8"?&gt; </code></pre> <p>This header was carefully chosen so that it can be read no matter the encoding. In your case, there is no such hint, hence neither your editor nor python has any idea what is going on. Therefore, you must use the <code>codecs</code> module and use <code>codecs.open(path,mode,encoding)</code> which provides the missing bit in Python.</p> <p>As for your editor, you must check if it offers some way to set the encoding of a file.</p> <p>The point of utf-8 is to be able to encode 21bit characters (Unicode) as an 8bit data stream (because that's the only thing all computers in the world can handle). But since most OSs predate the unicode era, they don't have suitable tools to attach the encoding information to files on the hard disk.</p> <p>The next issue is the representation in Python. This is explained perfectly in the <a href="http://stackoverflow.com/questions/491921/unicode-utf8-reading-and-writing-to-files-in-python/491967#491967">comment by heikogerlach</a>. You must understand that your console can only display ASCII. In order to display unicode or anything >= charcode 128, it must use some means of escaping. In your editor, you must not type the escaped display string but what the string means (in this case, you must enter the umlaut and save the file).</p> <p>That said, you can use the Python function eval() to turn an escaped string into a string:</p> <pre><code>&gt;&gt;&gt; x = eval("'Capit\\xc3\\xa1n\\n'") &gt;&gt;&gt; x 'Capit\xc3\xa1n\n' &gt;&gt;&gt; x[5] '\xc3' &gt;&gt;&gt; len(x[5]) 1 </code></pre> <p>As you can see, the string "\xc3" has been turned into a single character. This is now an 8bit string, utf-8 encoded. To get unicode:</p> <pre><code>&gt;&gt;&gt; x.decode('utf-8') u'Capit\xe1n\n' </code></pre> <p>[EDIT] <a href="http://stackoverflow.com/users/15842/gregg-lind">Gregg Lind</a> asked: I think there are some pieces missing here: the file f2 contains: hex: </p> <pre><code>0000000: 4361 7069 745c 7863 335c 7861 316e Capit\xc3\xa1n </code></pre> <p><code>codecs.open('f2','rb', 'utf-8')</code>, for example, reads them all in a separate chars (expected) Is there any way to write to a file in ascii that would work?</p> <p>Answer: That depends on what you mean. ASCII can't represent characters > 127. So you need some way to say "the next few characters mean something special" which is what the sequence "\x" does. It says: The next two characters are the code of a single character. "\u" does the same using four characters to encode unicode up to 0xffff (65535).</p> <p>So you can't directly write unicode to ascii (because ascii simply doesn't contain the same characters). What you can do is write it as string escapes (as in f2); in this case, the file can be represented as ASCII. Or you can write it as utf-8, in which case, you need an 8bit safe stream.</p> <p>Your solution using <code>decode('string-escape')</code> does work but you must be aware how much memory you use: Three times the amount of using <code>codecs.open()</code>.</p> <p>Remember that a file is just a sequence of bytes with 8 bits. Neither the bits nor the bytes have a meaning. It's you who says "65 means 'A'". Since <code>\xc3\xa1</code> should become "à" but the computer has no means to know, you must tell it by specifying the encoding which was used when writing the file.</p>
4
2009-01-29T16:54:42Z
[ "python", "unicode", "utf-8", "io" ]
Unicode (utf8) reading and writing to files in python
491,921
<p>I'm having some brain failure in understanding reading and writing text to a file (Python 2.4).</p> <pre><code># the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) </code></pre> <blockquote> <p>("u'Capit\xe1n'", "'Capit\xc3\xa1n'")</p> </blockquote> <pre><code>print ss, ss8 print &gt;&gt; open('f1','w'), ss8 &gt;&gt;&gt; file('f1').read() 'Capit\xc3\xa1n\n' </code></pre> <p>So I type in <code>Capit\xc3\xa1n</code> into my favorite editor, in file f2.</p> <p>then:</p> <pre><code>&gt;&gt;&gt; open('f1').read() 'Capit\xc3\xa1n\n' &gt;&gt;&gt; open('f2').read() 'Capit\\xc3\\xa1n\n' &gt;&gt;&gt; open('f1').read().decode('utf8') u'Capit\xe1n\n' &gt;&gt;&gt; open('f2').read().decode('utf8') u'Capit\\xc3\\xa1n\n' </code></pre> <p>What am I not understanding here? Clearly there is some vital bit of magic (or good sense) that I'm missing. What does one type into text files to get proper conversions.</p> <p><strong>Edit</strong>: What I'm truly failing to grok here, is what the point of the UTF-8 representation is, if you can't actually get Python to recognize it, when it comes from outside. Maybe I should just JSON dump the string, and use that instead, since that has an asciiable representation! More to the point, is there an ascii representation of this unicode object that Python will recognize and decode, when coming in from a file? If so, how do I get it?</p> <pre><code>&gt;&gt;&gt; print simplejson.dumps(ss) '"Capit\u00e1n"' &gt;&gt;&gt; print &gt;&gt; file('f3','w'), simplejson.dumps(ss) &gt;&gt;&gt; simplejson.load(open('f3')) u'Capit\xe1n' </code></pre>
189
2009-01-29T15:01:15Z
493,152
<p>So, I've found a solution for what I'm looking for, which is:</p> <pre><code>print open('f2').read().decode('string-escape').decode("utf-8") </code></pre> <p>There are some unusual codecs that are useful here. This particular reading allows one to take utf-8 representations from within python, copy them into an ascii file, and have them be read in to unicode. Under the "string-escape" decode, the slashes won't be doubled.</p> <p>This allows for the sort of round trip that I was imagining. </p>
12
2009-01-29T20:01:27Z
[ "python", "unicode", "utf-8", "io" ]
Unicode (utf8) reading and writing to files in python
491,921
<p>I'm having some brain failure in understanding reading and writing text to a file (Python 2.4).</p> <pre><code># the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) </code></pre> <blockquote> <p>("u'Capit\xe1n'", "'Capit\xc3\xa1n'")</p> </blockquote> <pre><code>print ss, ss8 print &gt;&gt; open('f1','w'), ss8 &gt;&gt;&gt; file('f1').read() 'Capit\xc3\xa1n\n' </code></pre> <p>So I type in <code>Capit\xc3\xa1n</code> into my favorite editor, in file f2.</p> <p>then:</p> <pre><code>&gt;&gt;&gt; open('f1').read() 'Capit\xc3\xa1n\n' &gt;&gt;&gt; open('f2').read() 'Capit\\xc3\\xa1n\n' &gt;&gt;&gt; open('f1').read().decode('utf8') u'Capit\xe1n\n' &gt;&gt;&gt; open('f2').read().decode('utf8') u'Capit\\xc3\\xa1n\n' </code></pre> <p>What am I not understanding here? Clearly there is some vital bit of magic (or good sense) that I'm missing. What does one type into text files to get proper conversions.</p> <p><strong>Edit</strong>: What I'm truly failing to grok here, is what the point of the UTF-8 representation is, if you can't actually get Python to recognize it, when it comes from outside. Maybe I should just JSON dump the string, and use that instead, since that has an asciiable representation! More to the point, is there an ascii representation of this unicode object that Python will recognize and decode, when coming in from a file? If so, how do I get it?</p> <pre><code>&gt;&gt;&gt; print simplejson.dumps(ss) '"Capit\u00e1n"' &gt;&gt;&gt; print &gt;&gt; file('f3','w'), simplejson.dumps(ss) &gt;&gt;&gt; simplejson.load(open('f3')) u'Capit\xe1n' </code></pre>
189
2009-01-29T15:01:15Z
844,443
<p>Rather than mess with the encode, decode methods I find it easier to use the open method from the codecs module.</p> <pre><code>&gt;&gt;&gt;import codecs &gt;&gt;&gt;f = codecs.open("test", "r", "utf-8") </code></pre> <p>Then after calling f's read() function, an encoded unicode object is returned.</p> <pre><code>&gt;&gt;&gt;f.read() u'Capit\xe1l\n\n' </code></pre> <p>If you know the encoding of a file, using the codecs package is going to be much less confusing.</p> <p>See <a href="http://docs.python.org/library/codecs.html#codecs.open">http://docs.python.org/library/codecs.html#codecs.open</a></p>
468
2009-05-10T00:45:58Z
[ "python", "unicode", "utf-8", "io" ]
Unicode (utf8) reading and writing to files in python
491,921
<p>I'm having some brain failure in understanding reading and writing text to a file (Python 2.4).</p> <pre><code># the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) </code></pre> <blockquote> <p>("u'Capit\xe1n'", "'Capit\xc3\xa1n'")</p> </blockquote> <pre><code>print ss, ss8 print &gt;&gt; open('f1','w'), ss8 &gt;&gt;&gt; file('f1').read() 'Capit\xc3\xa1n\n' </code></pre> <p>So I type in <code>Capit\xc3\xa1n</code> into my favorite editor, in file f2.</p> <p>then:</p> <pre><code>&gt;&gt;&gt; open('f1').read() 'Capit\xc3\xa1n\n' &gt;&gt;&gt; open('f2').read() 'Capit\\xc3\\xa1n\n' &gt;&gt;&gt; open('f1').read().decode('utf8') u'Capit\xe1n\n' &gt;&gt;&gt; open('f2').read().decode('utf8') u'Capit\\xc3\\xa1n\n' </code></pre> <p>What am I not understanding here? Clearly there is some vital bit of magic (or good sense) that I'm missing. What does one type into text files to get proper conversions.</p> <p><strong>Edit</strong>: What I'm truly failing to grok here, is what the point of the UTF-8 representation is, if you can't actually get Python to recognize it, when it comes from outside. Maybe I should just JSON dump the string, and use that instead, since that has an asciiable representation! More to the point, is there an ascii representation of this unicode object that Python will recognize and decode, when coming in from a file? If so, how do I get it?</p> <pre><code>&gt;&gt;&gt; print simplejson.dumps(ss) '"Capit\u00e1n"' &gt;&gt;&gt; print &gt;&gt; file('f3','w'), simplejson.dumps(ss) &gt;&gt;&gt; simplejson.load(open('f3')) u'Capit\xe1n' </code></pre>
189
2009-01-29T15:01:15Z
9,200,843
<pre><code># -*- encoding: utf-8 -*- # converting a unknown formatting file in utf-8 import codecs import commands file_location = "jumper.sub" file_encoding = commands.getoutput('file -b --mime-encoding %s' % file_location) file_stream = codecs.open(file_location, 'r', file_encoding) file_output = codecs.open(file_location+"b", 'w', 'utf-8') for l in file_stream: file_output.write(l) file_stream.close() file_output.close() </code></pre>
12
2012-02-08T20:24:46Z
[ "python", "unicode", "utf-8", "io" ]
Unicode (utf8) reading and writing to files in python
491,921
<p>I'm having some brain failure in understanding reading and writing text to a file (Python 2.4).</p> <pre><code># the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) </code></pre> <blockquote> <p>("u'Capit\xe1n'", "'Capit\xc3\xa1n'")</p> </blockquote> <pre><code>print ss, ss8 print &gt;&gt; open('f1','w'), ss8 &gt;&gt;&gt; file('f1').read() 'Capit\xc3\xa1n\n' </code></pre> <p>So I type in <code>Capit\xc3\xa1n</code> into my favorite editor, in file f2.</p> <p>then:</p> <pre><code>&gt;&gt;&gt; open('f1').read() 'Capit\xc3\xa1n\n' &gt;&gt;&gt; open('f2').read() 'Capit\\xc3\\xa1n\n' &gt;&gt;&gt; open('f1').read().decode('utf8') u'Capit\xe1n\n' &gt;&gt;&gt; open('f2').read().decode('utf8') u'Capit\\xc3\\xa1n\n' </code></pre> <p>What am I not understanding here? Clearly there is some vital bit of magic (or good sense) that I'm missing. What does one type into text files to get proper conversions.</p> <p><strong>Edit</strong>: What I'm truly failing to grok here, is what the point of the UTF-8 representation is, if you can't actually get Python to recognize it, when it comes from outside. Maybe I should just JSON dump the string, and use that instead, since that has an asciiable representation! More to the point, is there an ascii representation of this unicode object that Python will recognize and decode, when coming in from a file? If so, how do I get it?</p> <pre><code>&gt;&gt;&gt; print simplejson.dumps(ss) '"Capit\u00e1n"' &gt;&gt;&gt; print &gt;&gt; file('f3','w'), simplejson.dumps(ss) &gt;&gt;&gt; simplejson.load(open('f3')) u'Capit\xe1n' </code></pre>
189
2009-01-29T15:01:15Z
25,378,530
<p>Actually this is worked for me for reading a file with utf-8 encodeing in Py 3.2</p> <pre><code>import codecs f = codecs.open('file_name.txt', 'r', 'UTF-8') for line in f: print(line) </code></pre>
11
2014-08-19T08:09:28Z
[ "python", "unicode", "utf-8", "io" ]
Unicode (utf8) reading and writing to files in python
491,921
<p>I'm having some brain failure in understanding reading and writing text to a file (Python 2.4).</p> <pre><code># the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) </code></pre> <blockquote> <p>("u'Capit\xe1n'", "'Capit\xc3\xa1n'")</p> </blockquote> <pre><code>print ss, ss8 print &gt;&gt; open('f1','w'), ss8 &gt;&gt;&gt; file('f1').read() 'Capit\xc3\xa1n\n' </code></pre> <p>So I type in <code>Capit\xc3\xa1n</code> into my favorite editor, in file f2.</p> <p>then:</p> <pre><code>&gt;&gt;&gt; open('f1').read() 'Capit\xc3\xa1n\n' &gt;&gt;&gt; open('f2').read() 'Capit\\xc3\\xa1n\n' &gt;&gt;&gt; open('f1').read().decode('utf8') u'Capit\xe1n\n' &gt;&gt;&gt; open('f2').read().decode('utf8') u'Capit\\xc3\\xa1n\n' </code></pre> <p>What am I not understanding here? Clearly there is some vital bit of magic (or good sense) that I'm missing. What does one type into text files to get proper conversions.</p> <p><strong>Edit</strong>: What I'm truly failing to grok here, is what the point of the UTF-8 representation is, if you can't actually get Python to recognize it, when it comes from outside. Maybe I should just JSON dump the string, and use that instead, since that has an asciiable representation! More to the point, is there an ascii representation of this unicode object that Python will recognize and decode, when coming in from a file? If so, how do I get it?</p> <pre><code>&gt;&gt;&gt; print simplejson.dumps(ss) '"Capit\u00e1n"' &gt;&gt;&gt; print &gt;&gt; file('f3','w'), simplejson.dumps(ss) &gt;&gt;&gt; simplejson.load(open('f3')) u'Capit\xe1n' </code></pre>
189
2009-01-29T15:01:15Z
25,915,686
<p>To read in an Unicode string and then send to HTML, I did this:</p> <pre><code>fileline.decode("utf-8").encode('ascii', 'xmlcharrefreplace') </code></pre> <p>Useful for python powered http servers.</p>
4
2014-09-18T14:38:14Z
[ "python", "unicode", "utf-8", "io" ]
Unicode (utf8) reading and writing to files in python
491,921
<p>I'm having some brain failure in understanding reading and writing text to a file (Python 2.4).</p> <pre><code># the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) </code></pre> <blockquote> <p>("u'Capit\xe1n'", "'Capit\xc3\xa1n'")</p> </blockquote> <pre><code>print ss, ss8 print &gt;&gt; open('f1','w'), ss8 &gt;&gt;&gt; file('f1').read() 'Capit\xc3\xa1n\n' </code></pre> <p>So I type in <code>Capit\xc3\xa1n</code> into my favorite editor, in file f2.</p> <p>then:</p> <pre><code>&gt;&gt;&gt; open('f1').read() 'Capit\xc3\xa1n\n' &gt;&gt;&gt; open('f2').read() 'Capit\\xc3\\xa1n\n' &gt;&gt;&gt; open('f1').read().decode('utf8') u'Capit\xe1n\n' &gt;&gt;&gt; open('f2').read().decode('utf8') u'Capit\\xc3\\xa1n\n' </code></pre> <p>What am I not understanding here? Clearly there is some vital bit of magic (or good sense) that I'm missing. What does one type into text files to get proper conversions.</p> <p><strong>Edit</strong>: What I'm truly failing to grok here, is what the point of the UTF-8 representation is, if you can't actually get Python to recognize it, when it comes from outside. Maybe I should just JSON dump the string, and use that instead, since that has an asciiable representation! More to the point, is there an ascii representation of this unicode object that Python will recognize and decode, when coming in from a file? If so, how do I get it?</p> <pre><code>&gt;&gt;&gt; print simplejson.dumps(ss) '"Capit\u00e1n"' &gt;&gt;&gt; print &gt;&gt; file('f3','w'), simplejson.dumps(ss) &gt;&gt;&gt; simplejson.load(open('f3')) u'Capit\xe1n' </code></pre>
189
2009-01-29T15:01:15Z
35,320,036
<p>Now all you need in Python3 is <code>open(Filename, 'r', encoding='utf-8')</code></p> <p><em>[Edit on 2016-02-10 for requested clarification]</em></p> <p>Python3 added the <strong>encoding</strong> parameter to its open function. The following information about the open function is gathered from here: <a href="https://docs.python.org/3/library/functions.html#open">https://docs.python.org/3/library/functions.html#open</a></p> <p><code>open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)</code></p> <blockquote> <p>Encoding is the name of the encoding used to decode or encode the file. This should only be used in text mode. The default encoding is platform dependent (whatever <a href="https://docs.python.org/3/library/locale.html#locale.getpreferredencoding">locale.getpreferredencoding()</a> returns), but any <a href="https://docs.python.org/3/glossary.html#term-text-encoding">text encoding</a> supported by Python can be used. See the <a href="https://docs.python.org/3/library/codecs.html#module-codecs">codecs</a> module for the list of supported encodings.</p> </blockquote> <p>So by adding <code>encoding='utf-8'</code> as a parameter to the open function, the file reading and writing is all done as utf8 (which is also now the default encoding of everything done in Python.)</p>
6
2016-02-10T16:03:00Z
[ "python", "unicode", "utf-8", "io" ]
Unicode (utf8) reading and writing to files in python
491,921
<p>I'm having some brain failure in understanding reading and writing text to a file (Python 2.4).</p> <pre><code># the string, which has an a-acute in it. ss = u'Capit\xe1n' ss8 = ss.encode('utf8') repr(ss), repr(ss8) </code></pre> <blockquote> <p>("u'Capit\xe1n'", "'Capit\xc3\xa1n'")</p> </blockquote> <pre><code>print ss, ss8 print &gt;&gt; open('f1','w'), ss8 &gt;&gt;&gt; file('f1').read() 'Capit\xc3\xa1n\n' </code></pre> <p>So I type in <code>Capit\xc3\xa1n</code> into my favorite editor, in file f2.</p> <p>then:</p> <pre><code>&gt;&gt;&gt; open('f1').read() 'Capit\xc3\xa1n\n' &gt;&gt;&gt; open('f2').read() 'Capit\\xc3\\xa1n\n' &gt;&gt;&gt; open('f1').read().decode('utf8') u'Capit\xe1n\n' &gt;&gt;&gt; open('f2').read().decode('utf8') u'Capit\\xc3\\xa1n\n' </code></pre> <p>What am I not understanding here? Clearly there is some vital bit of magic (or good sense) that I'm missing. What does one type into text files to get proper conversions.</p> <p><strong>Edit</strong>: What I'm truly failing to grok here, is what the point of the UTF-8 representation is, if you can't actually get Python to recognize it, when it comes from outside. Maybe I should just JSON dump the string, and use that instead, since that has an asciiable representation! More to the point, is there an ascii representation of this unicode object that Python will recognize and decode, when coming in from a file? If so, how do I get it?</p> <pre><code>&gt;&gt;&gt; print simplejson.dumps(ss) '"Capit\u00e1n"' &gt;&gt;&gt; print &gt;&gt; file('f3','w'), simplejson.dumps(ss) &gt;&gt;&gt; simplejson.load(open('f3')) u'Capit\xe1n' </code></pre>
189
2009-01-29T15:01:15Z
37,139,074
<p>I was trying to parse ical using python 2.7.9:<br></p> <blockquote> <p>from icalendar import Calendar<br></p> </blockquote> <p>but was getting:</p> <pre><code> Traceback (most recent call last): File "ical.py", line 92, in parse print "{}".format(e[attr]) UnicodeEncodeError: 'ascii' codec can't encode character u'\xe1' in position 7: ordinal not in range(128) </code></pre> <p>and it was fixed with just:</p> <pre><code>print "{}".format(e[attr].encode("utf-8")) </code></pre> <p>(Now it can print liké á böss.)</p>
0
2016-05-10T12:49:41Z
[ "python", "unicode", "utf-8", "io" ]
How can I order objects according to some attribute of the child in sqlalchemy?
492,223
<p>Here is the situation: I have a parent model say <code>BlogPost</code>. It has many <code>Comment</code>s. What I want is the list of <code>BlogPost</code>s ordered by the creation date of its' <code>Comment</code>s. I.e. the blog post which has the most newest comment should be on top of the list. Is this possible with SQLAlchemy?</p>
3
2009-01-29T16:01:51Z
492,389
<p><a href="http://www.sqlalchemy.org/docs/05/mappers.html#controlling-ordering" rel="nofollow">http://www.sqlalchemy.org/docs/05/mappers.html#controlling-ordering</a></p> <blockquote> <p>As of version 0.5, the ORM does not generate ordering for any query unless explicitly configured.</p> <p>The “default” ordering for a collection, which applies to list-based collections, can be configured using the order_by keyword argument on relation():</p> </blockquote>
3
2009-01-29T16:35:02Z
[ "python", "sqlalchemy" ]
How can I order objects according to some attribute of the child in sqlalchemy?
492,223
<p>Here is the situation: I have a parent model say <code>BlogPost</code>. It has many <code>Comment</code>s. What I want is the list of <code>BlogPost</code>s ordered by the creation date of its' <code>Comment</code>s. I.e. the blog post which has the most newest comment should be on top of the list. Is this possible with SQLAlchemy?</p>
3
2009-01-29T16:01:51Z
1,227,979
<p>I had the same question as the parent when using the ORM, and GHZ's link contained the answer on how it's possible. In sqlalchemy, assuming BlogPost.comments is a mapped relation to the Comments table, you can't do:</p> <blockquote> <p>session.query(BlogPost).order_by(BlogPost.comments.creationDate.desc())</p> </blockquote> <p>, but you can do:</p> <blockquote> <p>session.query(BlogPost).join(Comments).order_by(Comments.creationDate.desc())</p> </blockquote>
1
2009-08-04T14:53:02Z
[ "python", "sqlalchemy" ]
How do I use ctypes to set a library's extern function pointer to a Python callback function?
492,377
<p>Some C libraries export function pointers such that the user of the library sets that function pointer to the address of their own function to implement a hook or callback.</p> <p>In this example library <code>liblibrary.so</code>, how do I set library_hook to a Python function using ctypes?</p> <p>library.h:</p> <pre><code>typedef int exported_function_t(char**, int); extern exported_function_t *library_hook; </code></pre>
3
2009-01-29T16:31:41Z
492,640
<p>This is tricky in ctypes because ctypes function pointers do not implement the <code>.value</code> property used to set other pointers. Instead, cast your callback function and the extern function pointer to <code>void *</code> with the <code>c_void_p</code> function. After setting the function pointer as <code>void *</code> as shown, C can call your Python function, and you can retrieve the function as a function pointer and call it with normal ctypes calls.</p> <pre><code>from ctypes import * liblibrary = cdll.LoadLibrary('liblibrary.so') def py_library_hook(strings, n): return 0 # First argument to CFUNCTYPE is the return type: LIBRARY_HOOK_FUNC = CFUNCTYPE(c_int, POINTER(c_char_p), c_int) hook = LIBRARY_HOOK_FUNC(py_library_Hook) ptr = c_void_p.in_dll(liblibrary, 'library_hook') ptr.value = cast(hook, c_void_p).value </code></pre>
9
2009-01-29T17:39:14Z
[ "python", "ctypes" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
492,399
<p>EDIT: Other posters are probably correct...there might be spaces mixed in with your tabs. Try doing a search&amp;replace to replace all tabs with a few spaces.</p> <p>Try this:</p> <pre><code>import sys def Factorial(n): # return factorial result = 1 for i in range (1,n): result = result * i print "factorial is ",result return result print Factorial(10) </code></pre>
282
2009-01-29T16:37:18Z
[ "python", "indentation" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
492,402
<p>The line: <code>result = result * i</code> should be indented (it is the body of the for-loop).</p> <p>Or - you have mixed space and tab characters</p>
6
2009-01-29T16:38:04Z
[ "python", "indentation" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
492,419
<p>Are you sure you are not mixing tabs and spaces in your indentation white space? (That will cause that error.)</p> <p>Note, it is recommended that you don't use tabs in Python code. See the <a href="http://www.python.org/dev/peps/pep-0008/">style guide</a>. You should configure Notepad++ to insert spaces for tabs.</p>
26
2009-01-29T16:41:15Z
[ "python", "indentation" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
492,437
<p>Whenever I've encountered this error, it's because I've somehow mixed up tabs and spaces in my editor. </p>
12
2009-01-29T16:45:19Z
[ "python", "indentation" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
513,524
<p>To easily check for problems with tabs/spaces you can actually do this:</p> <pre><code>python -m tabnanny yourfile.py </code></pre> <p>or you can just set up your editor correctly of course :-)</p>
97
2009-02-04T21:50:28Z
[ "python", "indentation" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
11,748,465
<p>Looks to be an indentation problem. You don't have to match curly brackets in Python but you <em>do</em> have to match indentation levels.</p> <p>The best way to prevent space/tab problems is to display invisible characters within your text editor. This will give you a quick way to prevent and/or resolve indentation-related errors.</p> <p>Also, injecting copy-pasted code is a common source for this type of problem.</p>
3
2012-07-31T20:27:51Z
[ "python", "indentation" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
17,070,370
<p>After setting up your editor following pep8, you still have problems. A good trick to solve this is replacing your four spaces by one tab. Actually python does not support 4 spaces in place of 1 tab. </p>
-4
2013-06-12T16:12:26Z
[ "python", "indentation" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
17,091,012
<p>If you use Python's IDLE editor you can do as it suggests in one of similar error messages:</p> <p>1) select all, e.g. Ctrl + A</p> <p>2) Go to Format -> Untabify Region</p> <p>3) Double check your indenting is still correct, save and rerun your program.</p> <p>I'm using Python 2.5.4</p>
7
2013-06-13T15:26:00Z
[ "python", "indentation" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
21,769,961
<p>It could be because the function above it is not indented the same way. i.e.</p> <pre><code>class a: def blah: print("Hello world") def blah1: print("Hello world") </code></pre>
0
2014-02-14T02:52:13Z
[ "python", "indentation" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
22,199,531
<p>This is because there is a mix-up of both tabs and spaces. You can either remove all the spaces and replace them with tabs.</p> <p>Or, Try writing this:</p> <pre><code>#!/usr/bin/python -tt </code></pre> <p>at the beginning of the code. This line resolves any differences between tabs and spaces.</p>
0
2014-03-05T13:43:15Z
[ "python", "indentation" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
22,268,518
<p>in my case, the problem was the configuration of pydev on Eclipse</p> <p><img src="http://i.stack.imgur.com/Ve5TD.png" alt="pydev @ Eclipse"></p>
0
2014-03-08T11:13:10Z
[ "python", "indentation" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
22,540,604
<p>If you use notepad++, do a "replace" with extended search mode to find \t and replace with four spaces.</p>
2
2014-03-20T17:23:01Z
[ "python", "indentation" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
23,540,812
<p><strong>IMPORTANT</strong>: <strong><em>Spaces are the preferred method</em></strong> - see PEP008 <a href="https://www.python.org/dev/peps/pep-0008/#indentation">Indentation</a> and <a href="https://www.python.org/dev/peps/pep-0008/#tabs-or-spaces">Tabs or Spaces?</a>. (Thanks to @Siha for this.)</p> <p>For <code>Sublime Text</code> users:</p> <p>Set <code>Sublime Text</code> to use tabs for indentation: <code>View</code> --> <code>Indentation</code> --> <code>Convert Indentation to Tabs</code></p> <p>Uncheck the <code>Indent Using Spaces</code> option as well in the same sub-menu above. This will immediately resolve this issue.</p>
86
2014-05-08T11:44:49Z
[ "python", "indentation" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
24,435,179
<p>I had the same issue yesterday, it was indentation error, was using sublime text editor. took my hours trying to fix it and at the end I ended up copying the code into VI text editor and it just worked fine. ps python is too whitespace sensitive, make sure not to mix space and tab.</p>
1
2014-06-26T15:57:37Z
[ "python", "indentation" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
27,257,674
<p>If you use Komodo editor you can do as it suggests in one of similar error messages:</p> <p>1) select all, e.g. Ctrl + A</p> <p>2) Go to Code -> Untabify Region</p> <p>3) Double check your indenting is still correct, save and rerun your program.</p> <p>I'm using Python 3.4.2</p>
0
2014-12-02T19:47:04Z
[ "python", "indentation" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
28,186,679
<p>If you are using Sublime text for python development,you can avoid the error by using the package Anaconda.After installing Anaconda,</p> <blockquote> <ol> <li>open your file in sublime</li> <li>right click on the open spaces</li> <li>choose anaconda</li> <li>click on autoformat</li> <li>DONE Or Press CTRL+ALT+R.</li> </ol> </blockquote>
0
2015-01-28T07:18:27Z
[ "python", "indentation" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
28,989,269
<p>On <a href="https://atom.io/" rel="nofollow">Atom</a></p> <p>go to </p> <pre><code>Packages &gt; Whitespace &gt; Convert Spaces to Tabs </code></pre> <p>Then check again your file indentation:</p> <pre><code>python -m tabnanny yourFile.py </code></pre> <p>or</p> <pre><code>&gt;python &gt;&gt;&gt; help("yourFile.py") </code></pre>
2
2015-03-11T14:27:23Z
[ "python", "indentation" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
30,097,361
<p>If you are using Vim, hit escape and then type </p> <p>gg=G</p> <p>This auto indents everything and will clear up any spaces you have thrown in.</p>
2
2015-05-07T09:43:20Z
[ "python", "indentation" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
31,676,628
<p>for Atom Users, <code>Packages -&gt;whitspace -&gt; remove trailing whitespaces</code> this worked for me </p>
0
2015-07-28T12:41:15Z
[ "python", "indentation" ]
IndentationError: unindent does not match any outer indentation level
492,387
<p>When I compile the Python code below, I get </p> <blockquote> <p>IndentationError: unindent does not match any outer indentation level</p> </blockquote> <hr> <pre><code>import sys def Factorial(n): # Return factorial result = 0 for i in range (1,n): result = result * i print "factorial is ",result return result </code></pre> <p>Why?</p>
243
2009-01-29T16:34:46Z
33,681,996
<p>Just a addition. I had a similar problem with the both indentations in Notepad++.</p> <ol> <li>Unexcepted indentation</li> <li><p>Outer Indentation Level</p> <p>Go to ----> Search tab ----> tap on <strong>replace</strong> ----> hit the radio button <strong>Extended</strong> below ---> Now replace \t with four spaces</p> <p>Go to ----> Search tab ----> tap on <strong>replace</strong> ----> hit the radio button <strong>Extended</strong> below ---> Now replace \n with nothing</p></li> </ol>
0
2015-11-12T21:42:44Z
[ "python", "indentation" ]
Using Python split to splice a variable together
492,452
<p>I have this list </p> <pre><code>["camilla_farnestam@hotmail.com : martin00", ""], </code></pre> <p>How do I split so it only be left with:</p> <pre><code>camilla_farnestam@hotmail.com:martin00 </code></pre>
1
2009-01-29T16:49:56Z
492,456
<p>Do you want to have: <code>aList[0]</code> ? </p> <p><strong>EDIT::</strong><br /> Oh, you have a tuple with the list in it! Now I see:</p> <pre><code>al = ["camilla_farnestam@hotmail.com : martin00", ""], #type(al) == tuple #len(al) == 1 aList = al[0] #type(aList) == list #len(aList) == 2 #Now you can type: aList[0] #and you get: "camilla_farnestam@hotmail.com : martin00" </code></pre> <p>You can use <code>aList[0].replace(' : ', ':')</code> if you wish to remove spaces before and after colon, suit your needs. I think that the most confusing thing here is the coma ending the first line. It creates a new tuple, that contains your list.</p>
3
2009-01-29T16:51:45Z
[ "python", "split" ]
Using Python split to splice a variable together
492,452
<p>I have this list </p> <pre><code>["camilla_farnestam@hotmail.com : martin00", ""], </code></pre> <p>How do I split so it only be left with:</p> <pre><code>camilla_farnestam@hotmail.com:martin00 </code></pre>
1
2009-01-29T16:49:56Z
492,464
<p>Exactly. </p> <pre> $ python Python 2.6 (r26:66714, Dec 4 2008, 11:34:15) [GCC 4.0.1 (Apple Inc. build 5488)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> al = ["camilla_farnestam@hotmail.com : martin00", ""] >>> print al[0] camilla_farnestam@hotmail.com : martin00 >>> </pre>
1
2009-01-29T16:53:49Z
[ "python", "split" ]
Using Python split to splice a variable together
492,452
<p>I have this list </p> <pre><code>["camilla_farnestam@hotmail.com : martin00", ""], </code></pre> <p>How do I split so it only be left with:</p> <pre><code>camilla_farnestam@hotmail.com:martin00 </code></pre>
1
2009-01-29T16:49:56Z
492,465
<p>Abgan, is probably correct, although if you still want a list, ie., </p> <pre><code>["camilla_farnestam@hotmail.com : martin00"] </code></pre> <p>you'd want:</p> <pre><code>the_list[:1] </code></pre>
0
2009-01-29T16:54:02Z
[ "python", "split" ]
Using Python split to splice a variable together
492,452
<p>I have this list </p> <pre><code>["camilla_farnestam@hotmail.com : martin00", ""], </code></pre> <p>How do I split so it only be left with:</p> <pre><code>camilla_farnestam@hotmail.com:martin00 </code></pre>
1
2009-01-29T16:49:56Z
492,467
<p>lists can be accessed by index or sliced into smaller lists.<br> <a href="http://diveintopython3.ep.io/native-datatypes.html" rel="nofollow">http://diveintopython3.ep.io/native-datatypes.html</a></p>
0
2009-01-29T16:54:16Z
[ "python", "split" ]
Using Python split to splice a variable together
492,452
<p>I have this list </p> <pre><code>["camilla_farnestam@hotmail.com : martin00", ""], </code></pre> <p>How do I split so it only be left with:</p> <pre><code>camilla_farnestam@hotmail.com:martin00 </code></pre>
1
2009-01-29T16:49:56Z
492,477
<p>comma at the end means that list is first member of a tuple, but to your question:</p> <pre><code>in_list = ["camilla_farnestam@hotmail.com : martin00", ""] result = ''.join(in_list[0].split(' ')) </code></pre>
2
2009-01-29T16:56:37Z
[ "python", "split" ]
Using Python split to splice a variable together
492,452
<p>I have this list </p> <pre><code>["camilla_farnestam@hotmail.com : martin00", ""], </code></pre> <p>How do I split so it only be left with:</p> <pre><code>camilla_farnestam@hotmail.com:martin00 </code></pre>
1
2009-01-29T16:49:56Z
492,502
<pre><code>al = ["camilla_farnestam@hotmail.com : martin00", ""], print al[0][0].replace(" : ", ":") </code></pre>
3
2009-01-29T17:03:32Z
[ "python", "split" ]
Setting the correct encoding when piping stdout in Python
492,483
<p>When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this:</p> <pre><code># -*- coding: utf-8 -*- print u"åäö" </code></pre> <p>will work fine when run normally, but fail with:</p> <blockquote> <p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)</p> </blockquote> <p>when used in a pipe sequence.</p> <p>What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using? </p> <p>The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack:</p> <pre><code># -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') print u"åäö" </code></pre> <p>Is there a better way to make piping work?</p>
224
2009-01-29T16:57:59Z
492,711
<p>Your code works when run in an script because Python encodes the output to whatever encoding your terminal application is using. If you are piping you must encode it yourself.</p> <p>A rule of thumb is: Always use Unicode internally. Decode what you receive, and encode what you send.</p> <pre><code># -*- coding: utf-8 -*- print u"åäö".encode('utf-8') </code></pre> <p>Another didactic example is a Python program to convert between ISO-8859-1 and UTF-8, making everything uppercase in between.</p> <pre><code>import sys for line in sys.stdin: # Decode what you receive: line = line.decode('iso8859-1') # Work with Unicode internally: line = line.upper() # Encode what you send: line = line.encode('utf-8') sys.stdout.write(line) </code></pre> <p>Setting the system default encoding is a bad idea, because some modules and libraries you use can rely on the fact it is ASCII. Don't do it.</p>
120
2009-01-29T18:03:18Z
[ "python", "encoding", "terminal", "stdout", "python-2.x" ]
Setting the correct encoding when piping stdout in Python
492,483
<p>When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this:</p> <pre><code># -*- coding: utf-8 -*- print u"åäö" </code></pre> <p>will work fine when run normally, but fail with:</p> <blockquote> <p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)</p> </blockquote> <p>when used in a pipe sequence.</p> <p>What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using? </p> <p>The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack:</p> <pre><code># -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') print u"åäö" </code></pre> <p>Is there a better way to make piping work?</p>
224
2009-01-29T16:57:59Z
1,169,209
<p>First, regarding this solution:</p> <pre><code># -*- coding: utf-8 -*- print u"åäö".encode('utf-8') </code></pre> <p>It's not practical to explicitly print with a given encoding every time. That would be repetitive and error-prone.</p> <p>A better solution is to change <strong><code>sys.stdout</code></strong> at the start of your program, to encode with a selected encoding. Here is one solution I found on <a href="http://drj11.wordpress.com/2007/05/14/python-how-is-sysstdoutencoding-chosen/">Python: How is sys.stdout.encoding chosen?</a>, in particular a comment by "toka":</p> <pre><code>import sys import codecs sys.stdout = codecs.getwriter('utf8')(sys.stdout) </code></pre>
129
2009-07-23T02:05:58Z
[ "python", "encoding", "terminal", "stdout", "python-2.x" ]
Setting the correct encoding when piping stdout in Python
492,483
<p>When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this:</p> <pre><code># -*- coding: utf-8 -*- print u"åäö" </code></pre> <p>will work fine when run normally, but fail with:</p> <blockquote> <p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)</p> </blockquote> <p>when used in a pipe sequence.</p> <p>What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using? </p> <p>The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack:</p> <pre><code># -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') print u"åäö" </code></pre> <p>Is there a better way to make piping work?</p>
224
2009-01-29T16:57:59Z
4,027,726
<p>You may want to try changing the environment variable "PYTHONIOENCODING" to "utf_8." I have written a <a href="http://daveagp.wordpress.com/2010/10/26/what-a-character/">page on my ordeal with this problem</a>.</p> <p>Tl;dr of the blog post:</p> <pre class="lang-python prettyprint-override"><code>import sys, locale, os print(sys.stdout.encoding) print(sys.stdout.isatty()) print(locale.getpreferredencoding()) print(sys.getfilesystemencoding()) print(os.environ["PYTHONIOENCODING"]) print(chr(246), chr(9786), chr(9787)) </code></pre> <p>gives you</p> <pre class="lang-none prettyprint-override"><code>utf_8 False ANSI_X3.4-1968 ascii utf_8 ö ☺ ☻ </code></pre>
81
2010-10-26T20:30:35Z
[ "python", "encoding", "terminal", "stdout", "python-2.x" ]
Setting the correct encoding when piping stdout in Python
492,483
<p>When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this:</p> <pre><code># -*- coding: utf-8 -*- print u"åäö" </code></pre> <p>will work fine when run normally, but fail with:</p> <blockquote> <p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)</p> </blockquote> <p>when used in a pipe sequence.</p> <p>What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using? </p> <p>The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack:</p> <pre><code># -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') print u"åäö" </code></pre> <p>Is there a better way to make piping work?</p>
224
2009-01-29T16:57:59Z
6,362,647
<pre><code>export PYTHONIOENCODING=utf-8 </code></pre> <p>do the job, but can't set it on python itself ...</p> <p>what we can do is verify if isn't setting and tell the user to set it before call script with :</p> <pre><code>if __name__ == '__main__': if (sys.stdout.encoding is None): print &gt;&gt; sys.stderr, "please set python env PYTHONIOENCODING=UTF-8, example: export PYTHONIOENCODING=UTF-8, when write to stdout." exit(1) </code></pre>
38
2011-06-15T18:40:18Z
[ "python", "encoding", "terminal", "stdout", "python-2.x" ]
Setting the correct encoding when piping stdout in Python
492,483
<p>When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this:</p> <pre><code># -*- coding: utf-8 -*- print u"åäö" </code></pre> <p>will work fine when run normally, but fail with:</p> <blockquote> <p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)</p> </blockquote> <p>when used in a pipe sequence.</p> <p>What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using? </p> <p>The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack:</p> <pre><code># -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') print u"åäö" </code></pre> <p>Is there a better way to make piping work?</p>
224
2009-01-29T16:57:59Z
9,717,454
<p>I could "automate" it with a call to:</p> <pre><code>def __fix_io_encoding(last_resort_default='UTF-8'): import sys if [x for x in (sys.stdin,sys.stdout,sys.stderr) if x.encoding is None] : import os defEnc = None if defEnc is None : try: import locale defEnc = locale.getpreferredencoding() except: pass if defEnc is None : try: defEnc = sys.getfilesystemencoding() except: pass if defEnc is None : try: defEnc = sys.stdin.encoding except: pass if defEnc is None : defEnc = last_resort_default os.environ['PYTHONIOENCODING'] = os.environ.get("PYTHONIOENCODING",defEnc) os.execvpe(sys.argv[0],sys.argv,os.environ) __fix_io_encoding() ; del __fix_io_encoding </code></pre> <p>Yes, it's possible to get an infinite loop here if this "setenv" fails.</p>
2
2012-03-15T09:59:11Z
[ "python", "encoding", "terminal", "stdout", "python-2.x" ]
Setting the correct encoding when piping stdout in Python
492,483
<p>When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this:</p> <pre><code># -*- coding: utf-8 -*- print u"åäö" </code></pre> <p>will work fine when run normally, but fail with:</p> <blockquote> <p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)</p> </blockquote> <p>when used in a pipe sequence.</p> <p>What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using? </p> <p>The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack:</p> <pre><code># -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') print u"åäö" </code></pre> <p>Is there a better way to make piping work?</p>
224
2009-01-29T16:57:59Z
15,556,504
<p>There's one simple answer: switch to Python 3!</p>
0
2013-03-21T19:36:30Z
[ "python", "encoding", "terminal", "stdout", "python-2.x" ]
Setting the correct encoding when piping stdout in Python
492,483
<p>When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this:</p> <pre><code># -*- coding: utf-8 -*- print u"åäö" </code></pre> <p>will work fine when run normally, but fail with:</p> <blockquote> <p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)</p> </blockquote> <p>when used in a pipe sequence.</p> <p>What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using? </p> <p>The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack:</p> <pre><code># -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') print u"åäö" </code></pre> <p>Is there a better way to make piping work?</p>
224
2009-01-29T16:57:59Z
21,384,318
<p>On Ubuntu 12.10 and GNOME Terminal, no error is produced when the program is printing to stdout or hooked to a pipe for other programs. Both file encoding and terminal encoding is <a href="http://en.wikipedia.org/wiki/UTF-8" rel="nofollow">UTF-8</a>.</p> <pre><code>$ cat a.py # -*- coding: utf-8 -*- print "åäö" $ python a.py åäö $ python a.py | tee out åäö </code></pre> <p>What OS and terminal emulator are you using? I heard some of my colleagues have similar problems when using <a href="http://iterm2.com/" rel="nofollow">iTerm&nbsp;2</a> and OS X; iTerm&nbsp;2 may be the culprit.</p> <p><strong>Update: This answer is wrong - see comments for details</strong></p>
0
2014-01-27T15:09:25Z
[ "python", "encoding", "terminal", "stdout", "python-2.x" ]
Setting the correct encoding when piping stdout in Python
492,483
<p>When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this:</p> <pre><code># -*- coding: utf-8 -*- print u"åäö" </code></pre> <p>will work fine when run normally, but fail with:</p> <blockquote> <p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)</p> </blockquote> <p>when used in a pipe sequence.</p> <p>What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using? </p> <p>The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack:</p> <pre><code># -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') print u"åäö" </code></pre> <p>Is there a better way to make piping work?</p>
224
2009-01-29T16:57:59Z
22,260,303
<p>I just thought I'd mention something here which I had to spent a long time experimenting with before I finally realised what was going on. This may be so obvious to everyone here that they haven't bothered mentioning it. But it would've helped me if they had, so on that principle...!</p> <p>NB: I am using <a href="http://en.wikipedia.org/wiki/Jython" rel="nofollow">Jython</a> specifically, v 2.7, so just possibly this may not apply to <a href="http://en.wikipedia.org/wiki/CPython" rel="nofollow">CPython</a>...</p> <p>NB2: the first two lines of my .py file here are:</p> <pre><code># -*- coding: utf-8 -*- from __future__ import print_function </code></pre> <p>The "%" (AKA "interpolation operator") string construction mechanism causes ADDITIONAL problems too... If the default encoding of the "environment" is ASCII and you try to do something like</p> <pre><code>print( "bonjour, %s" % "fréd" ) # Call this "print A" </code></pre> <p>You will have no difficulty running in Eclipse... In a Windows CLI (DOS window) you will find that the encoding is <a href="http://en.wikipedia.org/wiki/Code_page_850" rel="nofollow">code page 850</a> (my Windows&nbsp;7 OS) or something similar, which can handle European accented characters at least, so it'll work.</p> <pre><code>print( u"bonjour, %s" % "fréd" ) # Call this "print B" </code></pre> <p>will also work.</p> <p>If, OTOH, you direct to a file from the CLI, the stdout encoding will be None, which will default to ASCII (on my OS anyway), which will not be able to handle either of the above prints... (dreaded encoding error).</p> <p>So then you might think of redirecting your stdout by using</p> <pre><code>sys.stdout = codecs.getwriter('utf8')(sys.stdout) </code></pre> <p>and try running in the CLI piping to a file... Very oddly, print A above will work... But print B above will throw the encoding error! The following will however work OK:</p> <pre><code>print( u"bonjour, " + "fréd" ) # Call this "print C" </code></pre> <p>The conclusion I have come to (provisionally) is that if a string which is specified to be a <a href="http://en.wikipedia.org/wiki/Unicode" rel="nofollow">Unicode</a> string using the "u" prefix is submitted to the %-handling mechanism it appears to involve the use of the default environment encoding, <strong>regardless of whether you have set stdout to redirect!</strong></p> <p>How people deal with this is a matter of choice. I would welcome a Unicode expert to say why this happens, whether I've got it wrong in some way, what the preferred solution to this, whether it also applies to <a href="http://en.wikipedia.org/wiki/CPython" rel="nofollow">CPython</a>, whether it happens in Python 3, etc., etc.</p>
0
2014-03-07T20:44:05Z
[ "python", "encoding", "terminal", "stdout", "python-2.x" ]
Setting the correct encoding when piping stdout in Python
492,483
<p>When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this:</p> <pre><code># -*- coding: utf-8 -*- print u"åäö" </code></pre> <p>will work fine when run normally, but fail with:</p> <blockquote> <p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)</p> </blockquote> <p>when used in a pipe sequence.</p> <p>What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using? </p> <p>The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack:</p> <pre><code># -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') print u"åäö" </code></pre> <p>Is there a better way to make piping work?</p>
224
2009-01-29T16:57:59Z
29,603,050
<p>An arguable sanitized version of Craig McQueen's answer.</p> <pre><code>import sys, codecs class EncodedOut: def __init__(self, enc): self.enc = enc self.stdout = sys.stdout def __enter__(self): if sys.stdout.encoding is None: w = codecs.getwriter(self.enc) sys.stdout = w(sys.stdout) def __exit__(self, exc_ty, exc_val, tb): sys.stdout = self.stdout </code></pre> <p>Usage:</p> <pre><code>with EncodedOut('utf-8'): print u'ÅÄÖåäö' </code></pre>
0
2015-04-13T10:24:12Z
[ "python", "encoding", "terminal", "stdout", "python-2.x" ]
Setting the correct encoding when piping stdout in Python
492,483
<p>When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this:</p> <pre><code># -*- coding: utf-8 -*- print u"åäö" </code></pre> <p>will work fine when run normally, but fail with:</p> <blockquote> <p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)</p> </blockquote> <p>when used in a pipe sequence.</p> <p>What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using? </p> <p>The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack:</p> <pre><code># -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') print u"åäö" </code></pre> <p>Is there a better way to make piping work?</p>
224
2009-01-29T16:57:59Z
30,960,847
<p>I had a <a href="https://stackoverflow.com/questions/30857027/youtube-api-unicodeencodeerror-in-python-3-4">similar issue last week</a>. It was easy to fix in my IDE (PyCharm).</p> <p>Here was my fix:</p> <p>Starting from PyCharm menu bar: File -> Settings... -> Editor -> File Encodings, then set: "IDE Encoding", "Project Encoding" and "Default encoding for properties files" ALL to UTF-8 and she now works like a charm.</p> <p>Hope this helps!</p>
4
2015-06-21T02:54:18Z
[ "python", "encoding", "terminal", "stdout", "python-2.x" ]
Setting the correct encoding when piping stdout in Python
492,483
<p>When piping the output of a Python program, the Python interpreter gets confused about encoding and sets it to None. This means a program like this:</p> <pre><code># -*- coding: utf-8 -*- print u"åäö" </code></pre> <p>will work fine when run normally, but fail with:</p> <blockquote> <p>UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 0: ordinal not in range(128)</p> </blockquote> <p>when used in a pipe sequence.</p> <p>What is the best way to make this work when piping? Can I just tell it to use whatever encoding the shell/filesystem/whatever is using? </p> <p>The suggestions I have seen thus far is to modify your site.py directly, or hardcoding the defaultencoding using this hack:</p> <pre><code># -*- coding: utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') print u"åäö" </code></pre> <p>Is there a better way to make piping work?</p>
224
2009-01-29T16:57:59Z
38,927,473
<p>For all the people who still not have working her code all because a Ñ comes in the string: use this <code>string.encode( "cp850" )</code> instead of <code>string.encode( "utf8" )</code></p>
0
2016-08-12T22:54:13Z
[ "python", "encoding", "terminal", "stdout", "python-2.x" ]
Timeout on a function call
492,519
<p>I'm calling a function in Python which I know may stall and force me to restart the script. </p> <p>How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?</p>
95
2009-01-29T17:08:29Z
492,620
<p>If this is some kind of network or file operation, you might also consider using nonblocking IO. This can be a better option if you're doing a lot of these types of operations at once (otherwise, you can bog your system down fairly quickly with a lot of threads). <a href="http://www.amk.ca/python/howto/sockets/sockets.html#SECTION000600000000000000000" rel="nofollow">Here</a>'s a socket howto that covers nonblocking IO (in the context of network operations).</p> <p>The downside? Well, it can be a pain to program. Sometimes even moreso than just using a thread.</p>
3
2009-01-29T17:32:29Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
Timeout on a function call
492,519
<p>I'm calling a function in Python which I know may stall and force me to restart the script. </p> <p>How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?</p>
95
2009-01-29T17:08:29Z
494,273
<p>You may use the <a href="http://docs.python.org/library/signal.html">signal</a> package if you are running on UNIX:</p> <pre><code>In [1]: import signal # Register an handler for the timeout In [2]: def handler(signum, frame): ...: print "Forever is over!" ...: raise Exception("end of time") ...: # This function *may* run for an indetermined time... In [3]: def loop_forever(): ...: import time ...: while 1: ...: print "sec" ...: time.sleep(1) ...: ...: # Register the signal function handler In [4]: signal.signal(signal.SIGALRM, handler) Out[4]: 0 # Define a timeout for your function In [5]: signal.alarm(10) Out[5]: 0 In [6]: try: ...: loop_forever() ...: except Exception, exc: ...: print exc ....: sec sec sec sec sec sec sec sec Forever is over! end of time # Cancel the timer if the function returned before timeout # (ok, mine won't but yours maybe will :) In [7]: signal.alarm(0) Out[7]: 0 </code></pre> <p>10 seconds after the call <code>alarm.alarm(10)</code>, the handler is called. This raises an exception that you can intercept from the regular Python code.</p> <p>This module doesn't play well with threads (but then, who does?)</p> <p><strong>Note that</strong> since we raise an exception when timeout happens, it may end up caught and ignored inside the function, for example of one such function:</p> <pre><code>def loop_forever(): while 1: print 'sec' try: time.sleep(10) except: continue </code></pre>
92
2009-01-30T02:14:04Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
Timeout on a function call
492,519
<p>I'm calling a function in Python which I know may stall and force me to restart the script. </p> <p>How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?</p>
95
2009-01-29T17:08:29Z
12,295,927
<p>Here is a slight improvement to the given thread-based solution.</p> <p>The code below supports <strong>exceptions</strong>:</p> <pre><code>def runFunctionCatchExceptions(func, *args, **kwargs): try: result = func(*args, **kwargs) except Exception, message: return ["exception", message] return ["RESULT", result] def runFunctionWithTimeout(func, args=(), kwargs={}, timeout_duration=10, default=None): import threading class InterruptableThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.result = default def run(self): self.result = runFunctionCatchExceptions(func, *args, **kwargs) it = InterruptableThread() it.start() it.join(timeout_duration) if it.isAlive(): return default if it.result[0] == "exception": raise it.result[1] return it.result[1] </code></pre> <p>Invoking it with a 5 second timeout:</p> <pre><code>result = timeout(remote_calculate, (myarg,), timeout_duration=5) </code></pre>
0
2012-09-06T08:25:33Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
Timeout on a function call
492,519
<p>I'm calling a function in Python which I know may stall and force me to restart the script. </p> <p>How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?</p>
95
2009-01-29T17:08:29Z
13,821,695
<p>I have a different proposal which is a pure function (with the same API as the threading suggestion) and seems to work fine (based on suggestions on this thread)</p> <pre><code>def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None): import signal class TimeoutError(Exception): pass def handler(signum, frame): raise TimeoutError() # set the timeout handler signal.signal(signal.SIGALRM, handler) signal.alarm(timeout_duration) try: result = func(*args, **kwargs) except TimeoutError as exc: result = default finally: signal.alarm(0) return result </code></pre>
26
2012-12-11T13:41:31Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
Timeout on a function call
492,519
<p>I'm calling a function in Python which I know may stall and force me to restart the script. </p> <p>How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?</p>
95
2009-01-29T17:08:29Z
14,924,210
<p>You can use <code>multiprocessing.Process</code> to do exactly that.</p> <p><strong>Code</strong></p> <pre><code>import multiprocessing import time # bar def bar(): for i in range(100): print "Tick" time.sleep(1) if __name__ == '__main__': # Start bar as a process p = multiprocessing.Process(target=bar) p.start() # Wait for 10 seconds or until process finishes p.join(10) # If thread is still active if p.is_alive(): print "running... let's kill it..." # Terminate p.terminate() p.join() </code></pre>
58
2013-02-17T18:00:10Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
Timeout on a function call
492,519
<p>I'm calling a function in Python which I know may stall and force me to restart the script. </p> <p>How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?</p>
95
2009-01-29T17:08:29Z
17,808,494
<p>We can use signals for the same. I think the below example will be useful for you. It is very simple compared to threads. </p> <pre><code>import signal def timeout(signum, frame): raise myException #this is an infinite loop, never ending under normal circumstances def main(): print 'Starting Main ', while 1: print 'in main ', #SIGALRM is only usable on a unix platform signal.signal(signal.SIGALRM, timeout) #change 5 to however many seconds you need signal.alarm(5) try: main() except myException: print "whoops" </code></pre>
0
2013-07-23T11:10:10Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
Timeout on a function call
492,519
<p>I'm calling a function in Python which I know may stall and force me to restart the script. </p> <p>How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?</p>
95
2009-01-29T17:08:29Z
28,526,150
<p>The <code>stopit</code> package, found on pypi, seems to handle timeouts well.</p> <p>I like the <code>@stopit.threading_timeoutable</code> decorator, which adds a <code>timeout</code> parameter to the decorated function, which does what you expect, it stops the function.</p> <p>Check it out on pypi: <a href="https://pypi.python.org/pypi/stopit" rel="nofollow">https://pypi.python.org/pypi/stopit</a></p>
0
2015-02-15T12:43:32Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
Timeout on a function call
492,519
<p>I'm calling a function in Python which I know may stall and force me to restart the script. </p> <p>How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?</p>
95
2009-01-29T17:08:29Z
31,667,005
<blockquote> <h1>How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it?</h1> </blockquote> <p>I posted a <a href="https://gist.github.com/aaronchall/6331661fe0185c30a0b4" rel="nofollow">gist</a> that solves this question/problem with a decorator and a <code>threading.Timer</code>. Here it is with a breakdown. </p> <h2>Imports and setups for compatibility</h2> <p>It was tested with Python 2 and 3. It should also work under Unix/Linux and Windows.</p> <p>First the imports. These attempt to keep the code consistent regardless of the Python version:</p> <pre><code>from __future__ import print_function import sys import threading from time import sleep try: import thread except ImportError: import _thread as thread </code></pre> <p>Use version independent code:</p> <pre><code>try: range, _print = xrange, print def print(*args, **kwargs): flush = kwargs.pop('flush', False) _print(*args, **kwargs) if flush: kwargs.get('file', sys.stdout).flush() except NameError: pass </code></pre> <p>Now we have imported our functionality from the standard library. </p> <h2><code>exit_after</code> decorator</h2> <p>Next we need a function to terminate the <code>main()</code> from the child thread:</p> <pre><code>def cdquit(fn_name): # print to stderr, unbuffered in Python 2. print('{0} took too long'.format(fn_name), file=sys.stderr) sys.stderr.flush() # Python 3 stderr is likely buffered. thread.interrupt_main() # raises KeyboardInterrupt </code></pre> <p>And here is the decorator itself:</p> <pre><code>def exit_after(s): ''' use as decorator to exit process if function takes longer than s seconds ''' def outer(fn): def inner(*args, **kwargs): timer = threading.Timer(s, cdquit, args=[fn.__name__]) timer.start() try: result = fn(*args, **kwargs) finally: timer.cancel() return result return inner return outer </code></pre> <h2>Usage</h2> <p>And here's the usage, modified from my gist, that directly answers your question about exiting after 5 seconds!:</p> <pre><code>@exit_after(5) def countdown(n): print('countdown started', flush=True) for i in range(n, -1, -1): print(i, end=', ', flush=True) sleep(1) print('countdown finished') </code></pre> <p>Demo:</p> <pre><code>&gt;&gt;&gt; countdown(3) countdown started 3, 2, 1, 0, countdown finished &gt;&gt;&gt; countdown(10) countdown started 10, 9, 8, 7, 6, countdown took too long Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 11, in inner File "&lt;stdin&gt;", line 6, in countdown KeyboardInterrupt </code></pre> <p>The second function call will not finish, instead the process should exit with a traceback!</p> <h2><code>KeyboardInterrupt</code> does not always stop a sleeping thread</h2> <p>Note that sleep will not always be interrupted by a keyboard interrupt, on Python 2 on Windows, e.g.:</p> <pre><code>@exit_after(1) def sleep10(): sleep(10) print('slept 10 seconds') &gt;&gt;&gt; sleep10() sleep10 took too long # Note that it hangs here about 9 more seconds Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; File "&lt;stdin&gt;", line 11, in inner File "&lt;stdin&gt;", line 3, in sleep10 KeyboardInterrupt </code></pre> <p>nor is it likely to interrupt code running in extensions unless it explicitly checks for <code>PyErr_CheckSignals()</code>, see <a href="http://stackoverflow.com/q/16769870/541136">Cython, Python and KeyboardInterrupt ignored</a></p> <blockquote> <p>How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it <strong>and does something else?</strong></p> </blockquote> <p>To catch it and do something else, you can catch the KeyboardInterrupt.</p> <pre><code>&gt;&gt;&gt; try: ... countdown(10) ... except KeyboardInterrupt: ... print('do something else') ... countdown started 10, 9, 8, 7, 6, countdown took too long do something else </code></pre> <p>Credits: </p> <ul> <li><a href="http://stackoverflow.com/users/3059812">Morgan Thrapp</a> for testing</li> <li><a href="http://stackoverflow.com/users/922130">Sherlock85</a> for finding a bug</li> <li><a href="http://stackoverflow.com/users/4279">J.F.Sebastian</a> for pointing out that, depending on platform and version, sleep isn't interrupted by <code>KeyboardInterrupt</code>.</li> </ul>
10
2015-07-28T03:43:52Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
Timeout on a function call
492,519
<p>I'm calling a function in Python which I know may stall and force me to restart the script. </p> <p>How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?</p>
95
2009-01-29T17:08:29Z
34,999,808
<p>I had a need for <strong>nestable</strong> timed interrupts (which SIGALARM can't do) that won't get blocked by time.sleep (which the thread-based approach can't do). I ended up copying and lightly modifying code from here: <a href="http://code.activestate.com/recipes/577600-queue-for-managing-multiple-sigalrm-alarms-concurr/" rel="nofollow">http://code.activestate.com/recipes/577600-queue-for-managing-multiple-sigalrm-alarms-concurr/</a></p> <p>The code itself:</p> <pre><code>#!/usr/bin/python # lightly modified version of http://code.activestate.com/recipes/577600-queue-for-managing-multiple-sigalrm-alarms-concurr/ """alarm.py: Permits multiple SIGALRM events to be queued. Uses a `heapq` to store the objects to be called when an alarm signal is raised, so that the next alarm is always at the top of the heap. """ import heapq import signal from time import time __version__ = '$Revision: 2539 $'.split()[1] alarmlist = [] __new_alarm = lambda t, f, a, k: (t + time(), f, a, k) __next_alarm = lambda: int(round(alarmlist[0][0] - time())) if alarmlist else None __set_alarm = lambda: signal.alarm(max(__next_alarm(), 1)) class TimeoutError(Exception): def __init__(self, message, id_=None): self.message = message self.id_ = id_ class Timeout: ''' id_ allows for nested timeouts. ''' def __init__(self, id_=None, seconds=1, error_message='Timeout'): self.seconds = seconds self.error_message = error_message self.id_ = id_ def handle_timeout(self): raise TimeoutError(self.error_message, self.id_) def __enter__(self): self.this_alarm = alarm(self.seconds, self.handle_timeout) def __exit__(self, type, value, traceback): try: cancel(self.this_alarm) except ValueError: pass def __clear_alarm(): """Clear an existing alarm. If the alarm signal was set to a callable other than our own, queue the previous alarm settings. """ oldsec = signal.alarm(0) oldfunc = signal.signal(signal.SIGALRM, __alarm_handler) if oldsec &gt; 0 and oldfunc != __alarm_handler: heapq.heappush(alarmlist, (__new_alarm(oldsec, oldfunc, [], {}))) def __alarm_handler(*zargs): """Handle an alarm by calling any due heap entries and resetting the alarm. Note that multiple heap entries might get called, especially if calling an entry takes a lot of time. """ try: nextt = __next_alarm() while nextt is not None and nextt &lt;= 0: (tm, func, args, keys) = heapq.heappop(alarmlist) func(*args, **keys) nextt = __next_alarm() finally: if alarmlist: __set_alarm() def alarm(sec, func, *args, **keys): """Set an alarm. When the alarm is raised in `sec` seconds, the handler will call `func`, passing `args` and `keys`. Return the heap entry (which is just a big tuple), so that it can be cancelled by calling `cancel()`. """ __clear_alarm() try: newalarm = __new_alarm(sec, func, args, keys) heapq.heappush(alarmlist, newalarm) return newalarm finally: __set_alarm() def cancel(alarm): """Cancel an alarm by passing the heap entry returned by `alarm()`. It is an error to try to cancel an alarm which has already occurred. """ __clear_alarm() try: alarmlist.remove(alarm) heapq.heapify(alarmlist) finally: if alarmlist: __set_alarm() </code></pre> <p>and a usage example:</p> <pre><code>import alarm from time import sleep try: with alarm.Timeout(id_='a', seconds=5): try: with alarm.Timeout(id_='b', seconds=2): sleep(3) except alarm.TimeoutError as e: print 'raised', e.id_ sleep(30) except alarm.TimeoutError as e: print 'raised', e.id_ else: print 'nope.' </code></pre>
1
2016-01-25T18:36:02Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
Timeout on a function call
492,519
<p>I'm calling a function in Python which I know may stall and force me to restart the script. </p> <p>How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?</p>
95
2009-01-29T17:08:29Z
35,139,284
<p>I ran across this thread when searching for a timeout call on unit tests. I didn't find anything simple in the answers or 3rd party packages so I wrote the decorator below you can drop right into code:</p> <pre><code>import multiprocessing.pool import functools def timeout(max_timeout): """Timeout decorator, parameter in seconds.""" def timeout_decorator(item): """Wrap the original function.""" @functools.wraps(item) def func_wrapper(*args, **kwargs): """Closure for function.""" pool = multiprocessing.pool.ThreadPool(processes=1) async_result = pool.apply_async(item, args, kwargs) # raises a TimeoutError if execution exceeds max_timeout return async_result.get(max_timeout) return func_wrapper return timeout_decorator </code></pre> <p>Then it's as simple as this to timeout a test or any function you like:</p> <pre><code>@timeout(5.0) # if execution takes longer than 5 seconds, raise a TimeoutError def test_base_regression(self): ... </code></pre>
14
2016-02-01T20:02:32Z
[ "python", "multithreading", "timeout", "python-multithreading" ]
Timeout on a function call
492,519
<p>I'm calling a function in Python which I know may stall and force me to restart the script. </p> <p>How do I call the function or what do I wrap it in so that if it takes longer than 5 seconds the script cancels it and does something else?</p>
95
2009-01-29T17:08:29Z
36,891,240
<pre><code>#!/usr/bin/python2 import sys, subprocess, threading proc = subprocess.Popen(sys.argv[2:]) timer = threading.Timer(float(sys.argv[1]), proc.terminate) timer.start() proc.wait() timer.cancel() exit(proc.returncode) </code></pre>
0
2016-04-27T13:27:21Z
[ "python", "multithreading", "timeout", "python-multithreading" ]