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
return eats exception
517,060
<p>I found the following behavior at least <em>weird</em>:</p> <pre><code>def errors(): try: ErrorErrorError finally: return 10 print errors() # prints: 10 # It should raise: NameError: name 'ErrorErrorError' is not defined </code></pre> <p>The exception disappears when you use <code>return</code> inside a <code>finally</code> clause. Is that a bug? Is that documented anywhere?</p> <p>But the real question (and the answer I will mark as correct) is:<br> What is the python developers' reason to allow that odd behavior?</p>
13
2009-02-05T17:59:35Z
517,082
<blockquote> <p>The exception disappears when you use <code>return</code> inside a <code>finally</code> clause. .. Is that documented anywhere?</p> </blockquote> <p><a href="http://docs.python.org/reference/compound_stmts.html#the-try-statement" rel="nofollow">It is:</a></p> <blockquote> <p>If finally is present, it specifies a ‘cleanup’ handler. The try clause is executed, including any except and else clauses. If an exception occurs in any of the clauses and is not handled, the exception is temporarily saved. The finally clause is executed. If there is a saved exception, it is re-raised at the end of the finally clause. <strong>If the finally clause raises another exception or executes a return or break statement, the saved exception is lost.</strong></p> </blockquote>
40
2009-02-05T18:03:39Z
[ "python", "exception", "return", "finally" ]
return eats exception
517,060
<p>I found the following behavior at least <em>weird</em>:</p> <pre><code>def errors(): try: ErrorErrorError finally: return 10 print errors() # prints: 10 # It should raise: NameError: name 'ErrorErrorError' is not defined </code></pre> <p>The exception disappears when you use <code>return</code> inside a <code>finally</code> clause. Is that a bug? Is that documented anywhere?</p> <p>But the real question (and the answer I will mark as correct) is:<br> What is the python developers' reason to allow that odd behavior?</p>
13
2009-02-05T17:59:35Z
518,359
<p>Here is an interesting comparison for return in finally block, among - Java/C#/Python/JavaScript: <a href="http://www.gettingclever.com/2008/07/return-from-finally.html" rel="nofollow">http://www.gettingclever.com/2008/07/return-from-finally.html</a></p>
5
2009-02-05T22:52:30Z
[ "python", "exception", "return", "finally" ]
return eats exception
517,060
<p>I found the following behavior at least <em>weird</em>:</p> <pre><code>def errors(): try: ErrorErrorError finally: return 10 print errors() # prints: 10 # It should raise: NameError: name 'ErrorErrorError' is not defined </code></pre> <p>The exception disappears when you use <code>return</code> inside a <code>finally</code> clause. Is that a bug? Is that documented anywhere?</p> <p>But the real question (and the answer I will mark as correct) is:<br> What is the python developers' reason to allow that odd behavior?</p>
13
2009-02-05T17:59:35Z
525,967
<p>You asked about the Python developers' reasoning. I can't speak for them, but no other behavior makes sense. A function can either return a value, or it can raise an exception; it can't do both. The purpose of a "finally" clause is to provide cleanup code that is "guaranteed" to be run, regardless of exceptions. By putting a return statement in a finally clause, you have declared that you want to return a value, no matter what, regardless of exceptions. If Python behaved as you are asking and raised the exception, it would be breaking the contract of the "finally" clause (because it would fail to return the value you told it to return).</p>
23
2009-02-08T16:15:35Z
[ "python", "exception", "return", "finally" ]
How do I write output in same place on the console?
517,127
<p>I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as:</p> <p>output:</p> <blockquote> <p>Downloading File FooFile.txt [47%]</p> </blockquote> <p>I'm trying to avoid something like this:</p> <pre><code> Downloading File FooFile.txt [47%] Downloading File FooFile.txt [48%] Downloading File FooFile.txt [49%] </code></pre> <p>How should I go about doing this?</p> <p><hr /></p> <p><strong>Duplicate</strong>: <a href="http://stackoverflow.com/questions/465348/how-can-i-print-over-the-current-line-in-a-command-line-application/465360#465360">http://stackoverflow.com/questions/465348/how-can-i-print-over-the-current-line-in-a-command-line-application/465360#465360</a></p>
82
2009-02-05T18:11:47Z
517,148
<p>Print the backspace character <code>\b</code> several times, and then overwrite the old number with the new number.</p>
10
2009-02-05T18:14:06Z
[ "python", "console-output" ]
How do I write output in same place on the console?
517,127
<p>I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as:</p> <p>output:</p> <blockquote> <p>Downloading File FooFile.txt [47%]</p> </blockquote> <p>I'm trying to avoid something like this:</p> <pre><code> Downloading File FooFile.txt [47%] Downloading File FooFile.txt [48%] Downloading File FooFile.txt [49%] </code></pre> <p>How should I go about doing this?</p> <p><hr /></p> <p><strong>Duplicate</strong>: <a href="http://stackoverflow.com/questions/465348/how-can-i-print-over-the-current-line-in-a-command-line-application/465360#465360">http://stackoverflow.com/questions/465348/how-can-i-print-over-the-current-line-in-a-command-line-application/465360#465360</a></p>
82
2009-02-05T18:11:47Z
517,179
<p>Use a terminal-handling library like the <a href="http://docs.python.org/library/curses.html">curses module</a>:</p> <blockquote> <p>The curses module provides an interface to the curses library, the de-facto standard for portable advanced terminal handling.</p> </blockquote>
19
2009-02-05T18:19:09Z
[ "python", "console-output" ]
How do I write output in same place on the console?
517,127
<p>I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as:</p> <p>output:</p> <blockquote> <p>Downloading File FooFile.txt [47%]</p> </blockquote> <p>I'm trying to avoid something like this:</p> <pre><code> Downloading File FooFile.txt [47%] Downloading File FooFile.txt [48%] Downloading File FooFile.txt [49%] </code></pre> <p>How should I go about doing this?</p> <p><hr /></p> <p><strong>Duplicate</strong>: <a href="http://stackoverflow.com/questions/465348/how-can-i-print-over-the-current-line-in-a-command-line-application/465360#465360">http://stackoverflow.com/questions/465348/how-can-i-print-over-the-current-line-in-a-command-line-application/465360#465360</a></p>
82
2009-02-05T18:11:47Z
517,207
<p>You can also use the carriage return:</p> <pre><code>sys.stdout.write("Download progress: %d%% \r" % (progress) ) sys.stdout.flush() </code></pre>
142
2009-02-05T18:22:47Z
[ "python", "console-output" ]
How do I write output in same place on the console?
517,127
<p>I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as:</p> <p>output:</p> <blockquote> <p>Downloading File FooFile.txt [47%]</p> </blockquote> <p>I'm trying to avoid something like this:</p> <pre><code> Downloading File FooFile.txt [47%] Downloading File FooFile.txt [48%] Downloading File FooFile.txt [49%] </code></pre> <p>How should I go about doing this?</p> <p><hr /></p> <p><strong>Duplicate</strong>: <a href="http://stackoverflow.com/questions/465348/how-can-i-print-over-the-current-line-in-a-command-line-application/465360#465360">http://stackoverflow.com/questions/465348/how-can-i-print-over-the-current-line-in-a-command-line-application/465360#465360</a></p>
82
2009-02-05T18:11:47Z
517,523
<p>I like the following:</p> <pre><code>print 'Downloading File FooFile.txt [%d%%]\r'%i, </code></pre> <p>Demo:</p> <pre><code>import time for i in range(100): time.sleep(0.1) print 'Downloading File FooFile.txt [%d%%]\r'%i, </code></pre>
8
2009-02-05T19:29:23Z
[ "python", "console-output" ]
How do I write output in same place on the console?
517,127
<p>I am new to python and am writing some scripts to automate downloading files from FTP servers, etc. I want to show the progress of the download, but I want it to stay in the same position, such as:</p> <p>output:</p> <blockquote> <p>Downloading File FooFile.txt [47%]</p> </blockquote> <p>I'm trying to avoid something like this:</p> <pre><code> Downloading File FooFile.txt [47%] Downloading File FooFile.txt [48%] Downloading File FooFile.txt [49%] </code></pre> <p>How should I go about doing this?</p> <p><hr /></p> <p><strong>Duplicate</strong>: <a href="http://stackoverflow.com/questions/465348/how-can-i-print-over-the-current-line-in-a-command-line-application/465360#465360">http://stackoverflow.com/questions/465348/how-can-i-print-over-the-current-line-in-a-command-line-application/465360#465360</a></p>
82
2009-02-05T18:11:47Z
7,975,759
<pre><code>#kinda like the one above but better :P from __future__ import print_function from time import sleep for i in range(101): str1="Downloading File FooFile.txt [{}%]".format(i) back="\b"*len(str1) print(str1, end="") sleep(0.1) print(back, end="") </code></pre>
7
2011-11-02T04:14:27Z
[ "python", "console-output" ]
HOWTO: Write Python API wrapper?
517,237
<p>I'd like to write a python library to wrap a REST-style API offered by a particular Web service. Does anyone know of any good learning resources for such work, preferably aimed at intermediate Python programmers?</p> <p>I'd like a good article on the subject, but I'd settle for nice, clear code examples.</p> <p><strong>CLARIFICATION:</strong> What I'm looking to do is write a Python client to interact with a Web service -- something to construct HTTP requests and parse XML/JSON responses, all wrapped up in Python objects.</p>
21
2009-02-05T18:29:07Z
517,457
<p>I can't point you to any article on how to do it, but I think there are a few libraries that can be good models on how to design your own.</p> <p><a href="http://pyaws.sourceforge.net/" rel="nofollow">PyAws</a> for example. I didn't see the source code so I can't tell you how good it is as code example, but the features and the usage examples in their website should be a useful design model</p> <p><a href="http://www.feedparser.org/" rel="nofollow">Universal Feed Parser</a> is not a wrapper for a webservice (it's an RSS parser library), but it's a great example of a design that prioritizes usage flexibility and hiding implementation details. I think you can get very good usage ideas for your wrapper there.</p>
2
2009-02-05T19:14:52Z
[ "python", "web-services", "api", "rest" ]
HOWTO: Write Python API wrapper?
517,237
<p>I'd like to write a python library to wrap a REST-style API offered by a particular Web service. Does anyone know of any good learning resources for such work, preferably aimed at intermediate Python programmers?</p> <p>I'd like a good article on the subject, but I'd settle for nice, clear code examples.</p> <p><strong>CLARIFICATION:</strong> What I'm looking to do is write a Python client to interact with a Web service -- something to construct HTTP requests and parse XML/JSON responses, all wrapped up in Python objects.</p>
21
2009-02-05T18:29:07Z
518,161
<p>My favorite combination is httplib2 (or pycurl for performance) and simplejson. As REST is more "a way of design" then a real "protocol" there is not really a reusable thing (that I know of). On Ruby you have something like ActiveResource. And to be honest, even that would just expose some tables as a webservice, whereas the power of xml/json is that they are more like "views" that can contain multiple objects optimized for your application. I hope this makes sense :-)</p>
2
2009-02-05T22:01:01Z
[ "python", "web-services", "api", "rest" ]
HOWTO: Write Python API wrapper?
517,237
<p>I'd like to write a python library to wrap a REST-style API offered by a particular Web service. Does anyone know of any good learning resources for such work, preferably aimed at intermediate Python programmers?</p> <p>I'd like a good article on the subject, but I'd settle for nice, clear code examples.</p> <p><strong>CLARIFICATION:</strong> What I'm looking to do is write a Python client to interact with a Web service -- something to construct HTTP requests and parse XML/JSON responses, all wrapped up in Python objects.</p>
21
2009-02-05T18:29:07Z
523,376
<p><a href="http://learn-rest.blogspot.com/2008/02/using-rest-in-python.html" rel="nofollow">This tutorial page</a> could be a good starting place (but it doesn't contain everything you need).</p>
1
2009-02-07T07:19:31Z
[ "python", "web-services", "api", "rest" ]
HOWTO: Write Python API wrapper?
517,237
<p>I'd like to write a python library to wrap a REST-style API offered by a particular Web service. Does anyone know of any good learning resources for such work, preferably aimed at intermediate Python programmers?</p> <p>I'd like a good article on the subject, but I'd settle for nice, clear code examples.</p> <p><strong>CLARIFICATION:</strong> What I'm looking to do is write a Python client to interact with a Web service -- something to construct HTTP requests and parse XML/JSON responses, all wrapped up in Python objects.</p>
21
2009-02-05T18:29:07Z
981,474
<p>You should take a look at PyFacebook. This is a python wrapper for the Facebook API, and it's one of the most nicely done API's I have ever used.</p>
0
2009-06-11T14:34:57Z
[ "python", "web-services", "api", "rest" ]
HOWTO: Write Python API wrapper?
517,237
<p>I'd like to write a python library to wrap a REST-style API offered by a particular Web service. Does anyone know of any good learning resources for such work, preferably aimed at intermediate Python programmers?</p> <p>I'd like a good article on the subject, but I'd settle for nice, clear code examples.</p> <p><strong>CLARIFICATION:</strong> What I'm looking to do is write a Python client to interact with a Web service -- something to construct HTTP requests and parse XML/JSON responses, all wrapped up in Python objects.</p>
21
2009-02-05T18:29:07Z
3,374,030
<p>You could checkout <a href="http://github.com/ryanmcgrath/pythentic_jobs" rel="nofollow">pythenic jobs</a>, a nice, simple, but well-formed "Python wrapper around the Authentic Jobs ... API" as a good example. That's what I'm doing now :)</p>
0
2010-07-30T17:37:50Z
[ "python", "web-services", "api", "rest" ]
Storing a binary hash value in a Django model field
517,349
<p>I have a twenty byte hex hash that I would like to store in a django model. If I use a text field, it's interpreted as unicode and it comes back garbled. </p> <p>Currently I'm encoding it and decoding it, which really clutters up the code, because I have to be able to filter by it.</p> <pre><code>def get_changeset(self): return bin(self._changeset) def set_changeset(self, value): self._changeset = hex(value) changeset = property(get_changeset, set_changeset) </code></pre> <p>Here's an example for filtering</p> <pre><code>Change.objects.get(_changeset=hex(ctx.node())) </code></pre> <p>This is the approach that was recommended by a django developer, but I'm really struggling to come to terms with the fact that it's this ugly to just store twenty bytes.</p> <p>Maybe I'm too much of a purist, but ideally I would be able to write</p> <pre><code>Change.objects.get(changeset=ctx.node()) </code></pre> <p>The properties allow me to write:</p> <pre><code>change.changeset = ctx.node() </code></pre> <p>So that's as good as I can ask.</p>
6
2009-02-05T18:51:49Z
517,492
<p>I'm assuming if you were writing raw SQL you'd be using a Postgres bytea or a MySQL VARBINARY. There's a <a href="http://code.djangoproject.com/ticket/2417" rel="nofollow">ticket with a patch</a> (marked "needs testing") that purportedly makes a field like this (Ticket 2417: Support for binary type fields (aka: bytea in postgres and VARBINARY in mysql)). </p> <p>Otherwise, you could probably try your hand at writing a <a href="http://docs.djangoproject.com/en/dev/howto/custom-model-fields/" rel="nofollow">custom field type</a>.</p>
4
2009-02-05T19:23:07Z
[ "python", "django", "encoding", "django-models", "binary-data" ]
Storing a binary hash value in a Django model field
517,349
<p>I have a twenty byte hex hash that I would like to store in a django model. If I use a text field, it's interpreted as unicode and it comes back garbled. </p> <p>Currently I'm encoding it and decoding it, which really clutters up the code, because I have to be able to filter by it.</p> <pre><code>def get_changeset(self): return bin(self._changeset) def set_changeset(self, value): self._changeset = hex(value) changeset = property(get_changeset, set_changeset) </code></pre> <p>Here's an example for filtering</p> <pre><code>Change.objects.get(_changeset=hex(ctx.node())) </code></pre> <p>This is the approach that was recommended by a django developer, but I'm really struggling to come to terms with the fact that it's this ugly to just store twenty bytes.</p> <p>Maybe I'm too much of a purist, but ideally I would be able to write</p> <pre><code>Change.objects.get(changeset=ctx.node()) </code></pre> <p>The properties allow me to write:</p> <pre><code>change.changeset = ctx.node() </code></pre> <p>So that's as good as I can ask.</p>
6
2009-02-05T18:51:49Z
517,632
<p>You could also write your own custom <a href="http://docs.djangoproject.com/en/dev/topics/db/managers/#topics-db-managers" rel="nofollow">Model Manager</a> that does the escaping and unescaping for you.</p>
3
2009-02-05T19:52:58Z
[ "python", "django", "encoding", "django-models", "binary-data" ]
Storing a binary hash value in a Django model field
517,349
<p>I have a twenty byte hex hash that I would like to store in a django model. If I use a text field, it's interpreted as unicode and it comes back garbled. </p> <p>Currently I'm encoding it and decoding it, which really clutters up the code, because I have to be able to filter by it.</p> <pre><code>def get_changeset(self): return bin(self._changeset) def set_changeset(self, value): self._changeset = hex(value) changeset = property(get_changeset, set_changeset) </code></pre> <p>Here's an example for filtering</p> <pre><code>Change.objects.get(_changeset=hex(ctx.node())) </code></pre> <p>This is the approach that was recommended by a django developer, but I'm really struggling to come to terms with the fact that it's this ugly to just store twenty bytes.</p> <p>Maybe I'm too much of a purist, but ideally I would be able to write</p> <pre><code>Change.objects.get(changeset=ctx.node()) </code></pre> <p>The properties allow me to write:</p> <pre><code>change.changeset = ctx.node() </code></pre> <p>So that's as good as I can ask.</p>
6
2009-02-05T18:51:49Z
518,704
<p>"I have a twenty byte hex hash that I would like to store in a django model."</p> <p>Django does this. They use hex digests, which are -- technically -- strings. Not bytes.</p> <p>Do not use <code>someHash.digest()</code> -- you get bytes, which you cannot easily store.</p> <p>Use <code>someHash.hexdigest()</code> -- you get a string, which you can easily store.</p> <p><strong>Edit</strong> -- The code is nearly identical. </p> <p>See <a href="http://docs.python.org/library/hashlib.html" rel="nofollow">http://docs.python.org/library/hashlib.html</a></p>
3
2009-02-06T00:59:44Z
[ "python", "django", "encoding", "django-models", "binary-data" ]
Storing a binary hash value in a Django model field
517,349
<p>I have a twenty byte hex hash that I would like to store in a django model. If I use a text field, it's interpreted as unicode and it comes back garbled. </p> <p>Currently I'm encoding it and decoding it, which really clutters up the code, because I have to be able to filter by it.</p> <pre><code>def get_changeset(self): return bin(self._changeset) def set_changeset(self, value): self._changeset = hex(value) changeset = property(get_changeset, set_changeset) </code></pre> <p>Here's an example for filtering</p> <pre><code>Change.objects.get(_changeset=hex(ctx.node())) </code></pre> <p>This is the approach that was recommended by a django developer, but I'm really struggling to come to terms with the fact that it's this ugly to just store twenty bytes.</p> <p>Maybe I'm too much of a purist, but ideally I would be able to write</p> <pre><code>Change.objects.get(changeset=ctx.node()) </code></pre> <p>The properties allow me to write:</p> <pre><code>change.changeset = ctx.node() </code></pre> <p>So that's as good as I can ask.</p>
6
2009-02-05T18:51:49Z
12,496,786
<p>If this issue is still of interest, Disqus' <code>django-bitfield</code> fits the bill:</p> <p><a href="https://github.com/disqus/django-bitfield" rel="nofollow">https://github.com/disqus/django-bitfield</a></p> <p>... the example code on GitHub is a little confusing at first w/r/t the modules' actual function, because of the asinine variable names -- generally I am hardly the sort of person with either the wherewithal or the high ground to take someone elses' goofy identifiers to task... but <code>flaggy_foo</code>?? Srsly, U guys. </p> <p>If that project isn't to your taste, and you're on Postgres, you have a lot of excellent options as many people have written and released code for an assortment of Django fields that take advantage of Postgres' native type. Here's an <code>hstore</code> model field:</p> <p><a href="https://github.com/jordanm/django-hstore" rel="nofollow">https://github.com/jordanm/django-hstore</a> -- I have used this and it works well. </p> <p>Here's a full-text search implementation that uses Postgres' termvector types: </p> <p><a href="https://github.com/aino/django-pgindex" rel="nofollow">https://github.com/aino/django-pgindex</a></p> <p>And while I cannot vouch for this specific project, there are Django <code>bytea</code> fields as well:</p> <p><a href="https://github.com/aino/django-arrayfields" rel="nofollow">https://github.com/aino/django-arrayfields</a></p>
1
2012-09-19T14:22:44Z
[ "python", "django", "encoding", "django-models", "binary-data" ]
String formatting in Python
517,355
<p>I want to do something like String.Format ("[{0}, {1}, {2}]", 1, 2, 3) which returns:</p> <pre><code>[1, 2, 3] </code></pre> <p>How do I do this in Python?</p>
21
2009-02-05T18:53:29Z
517,363
<p>You haven't formulated yourself very commendably, but I'll venture a guess this is what you're looking for:</p> <pre><code>foo = "Hello" bar = "world" baz = 2 print "%s, %s number %d" % (foo, bar, baz) </code></pre>
1
2009-02-05T18:56:15Z
[ "python", "string", "formatting" ]
String formatting in Python
517,355
<p>I want to do something like String.Format ("[{0}, {1}, {2}]", 1, 2, 3) which returns:</p> <pre><code>[1, 2, 3] </code></pre> <p>How do I do this in Python?</p>
21
2009-02-05T18:53:29Z
517,372
<p>You're looking for string formatting, which in python is based on the sprintf function in C.</p> <pre><code>print "[%s, %s, %s]" % (1, 2, 3) </code></pre> <p>For a complete reference look here: <a href="http://docs.python.org/library/stdtypes.html#string-formatting" rel="nofollow">http://docs.python.org/library/stdtypes.html#string-formatting</a></p>
16
2009-02-05T18:59:07Z
[ "python", "string", "formatting" ]
String formatting in Python
517,355
<p>I want to do something like String.Format ("[{0}, {1}, {2}]", 1, 2, 3) which returns:</p> <pre><code>[1, 2, 3] </code></pre> <p>How do I do this in Python?</p>
21
2009-02-05T18:53:29Z
517,471
<p>The previous answers have used % formatting, which is being phased out in Python 3.0+. Assuming you're using Python 2.6+, a more future-proof formatting system is described here:</p> <p><a href="http://docs.python.org/library/string.html#formatstrings">http://docs.python.org/library/string.html#formatstrings</a></p> <p>Although there are more advanced features as well, the simplest form ends up looking very close to what you wrote:</p> <pre><code>&gt;&gt;&gt; "[{0}, {1}, {2}]".format(1, 2, 3) [1, 2, 3] </code></pre>
53
2009-02-05T19:16:29Z
[ "python", "string", "formatting" ]
String formatting in Python
517,355
<p>I want to do something like String.Format ("[{0}, {1}, {2}]", 1, 2, 3) which returns:</p> <pre><code>[1, 2, 3] </code></pre> <p>How do I do this in Python?</p>
21
2009-02-05T18:53:29Z
628,974
<p>You can do it three ways:</p> <p><hr /></p> <p>Use Python's automatic pretty printing:</p> <pre><code>print [1, 2, 3] # Prints [1, 2, 3] </code></pre> <p>Showing the same thing with a variable:</p> <pre><code>numberList = [1, 2] numberList.append(3) print numberList # Prints [1, 2, 3] </code></pre> <p><hr /></p> <p>Use 'classic' string substitutions (ala C's printf). Note the different meanings here of % as the string-format specifier, and the % to apply the list (actually a tuple) to the formatting string. (And note the % is used as the modulo(remainder) operator for arithmetic expressions.)</p> <pre><code>print "[%i, %i, %i]" % (1, 2, 3) </code></pre> <p>Note if we use our pre-defined variable, we'll need to turn it into a tuple to do this:</p> <pre><code>print "[%i, %i, %i]" % tuple(numberList) </code></pre> <p><hr /></p> <p>Use Python 3 string formatting. This is still available in earlier versions (from 2.6), but is the 'new' way of doing it in Py 3. Note you can either use positional (ordinal) arguments, or named arguments (for the heck of it I've put them in reverse order. </p> <pre><code>print "[{0}, {1}, {2}]".format(1, 2, 3) </code></pre> <p>Note the names 'one' ,'two' and 'three' can be whatever makes sense.)</p> <pre><code>print "[{one}, {two}, {three}]".format(three=3, two=2, one=1) </code></pre>
25
2009-03-10T04:54:35Z
[ "python", "string", "formatting" ]
String formatting in Python
517,355
<p>I want to do something like String.Format ("[{0}, {1}, {2}]", 1, 2, 3) which returns:</p> <pre><code>[1, 2, 3] </code></pre> <p>How do I do this in Python?</p>
21
2009-02-05T18:53:29Z
11,404,948
<p>To print elements sequentially use {} without specifying the index</p> <pre><code>print('[{},{},{}]'.format(1,2,3)) </code></pre> <p>(works since python 2.7 and python 3.1)</p>
3
2012-07-10T00:05:15Z
[ "python", "string", "formatting" ]
String formatting in Python
517,355
<p>I want to do something like String.Format ("[{0}, {1}, {2}]", 1, 2, 3) which returns:</p> <pre><code>[1, 2, 3] </code></pre> <p>How do I do this in Python?</p>
21
2009-02-05T18:53:29Z
19,296,530
<p>If you don't know how many items are in list, this aproach is the most universal</p> <pre><code>&gt;&gt;&gt; '[{0}]'.format(', '.join([str(i) for i in [1,2,3]])) '[1, 2, 3]' </code></pre> <p>It is mouch simplier for list of strings</p> <pre><code>&gt;&gt;&gt; '[{0}]'.format(', '.join(['a','b','c'])) '[a, b, c]' </code></pre>
0
2013-10-10T13:03:32Z
[ "python", "string", "formatting" ]
String formatting in Python
517,355
<p>I want to do something like String.Format ("[{0}, {1}, {2}]", 1, 2, 3) which returns:</p> <pre><code>[1, 2, 3] </code></pre> <p>How do I do this in Python?</p>
21
2009-02-05T18:53:29Z
28,747,429
<p>I think that this combination is missing :P</p> <pre><code>"[{0}, {1}, {2}]".format(*[1, 2, 3]) </code></pre>
1
2015-02-26T16:18:20Z
[ "python", "string", "formatting" ]
Execute a string as a command in python
517,491
<p>I am developing my stuff in python. In this process I encountered a situation where I have a string called "import django". And I want to validate this string. Which means, I want to check whether the module mentioned('django' in this case) is in the python-path. How can I do it?</p>
1
2009-02-05T19:23:05Z
517,530
<p>I doub't that it's safe, but it's the most naïve solution:</p> <pre><code>try: exec('import django') except ImportError: print('no django') </code></pre>
1
2009-02-05T19:30:45Z
[ "python", "django", "path" ]
Execute a string as a command in python
517,491
<p>I am developing my stuff in python. In this process I encountered a situation where I have a string called "import django". And I want to validate this string. Which means, I want to check whether the module mentioned('django' in this case) is in the python-path. How can I do it?</p>
1
2009-02-05T19:23:05Z
517,592
<p>My previous answer was wrong -- i didn't think to test my code. This actually works, though: look at the <a href="http://docs.python.org/library/imp.html" rel="nofollow">imp</a> module.</p> <p>To just check for the module's importability in the current sys.path: </p> <pre><code>try: imp.find_module('django', sys.path) except ImportError: print "Boo! no django for you!" </code></pre>
14
2009-02-05T19:44:22Z
[ "python", "django", "path" ]
Execute a string as a command in python
517,491
<p>I am developing my stuff in python. In this process I encountered a situation where I have a string called "import django". And I want to validate this string. Which means, I want to check whether the module mentioned('django' in this case) is in the python-path. How can I do it?</p>
1
2009-02-05T19:23:05Z
522,135
<p>If a module's name is available as string you can import it using the built-in <code>__import__</code> function.</p> <pre><code>module = __import__("module name", {}, {}, [], -1) </code></pre> <p>For example,</p> <pre><code>os = __import__("os", {}, {}, [], -1) </code></pre>
1
2009-02-06T20:55:26Z
[ "python", "django", "path" ]
What is the best way to remove accents in a Python unicode string?
517,923
<p>I have a Unicode string in Python, and I would like to remove all the accents (diacritics).</p> <p>I found on the Web an elegant way to do this in Java:</p> <ol> <li>convert the Unicode string to its long normalized form (with a separate character for letters and diacritics)</li> <li>remove all the characters whose Unicode type is "diacritic".</li> </ol> <p>Do I need to install a library such as pyICU or is this possible with just the python standard library? And what about python 3?</p> <p>Important note: I would like to avoid code with an explicit mapping from accented characters to their non-accented counterpart.</p>
230
2009-02-05T21:10:40Z
517,974
<p>I just found this answer on the Web:</p> <pre><code>import unicodedata def remove_accents(input_str): nfkd_form = unicodedata.normalize('NFKD', input_str) only_ascii = nfkd_form.encode('ASCII', 'ignore') return only_ascii </code></pre> <p>It works fine (for French, for example), but I think the second step (removing the accents) could be handled better than dropping the non-ASCII characters, because this will fail for some languages (Greek, for example). The best solution would probably be to explicitly remove the unicode characters that are tagged as being diacritics.</p> <p><strong>Edit</strong>: this does the trick:</p> <pre><code>import unicodedata def remove_accents(input_str): nfkd_form = unicodedata.normalize('NFKD', input_str) return u"".join([c for c in nfkd_form if not unicodedata.combining(c)]) </code></pre> <p><code>unicodedata.combining(c)</code> will return true if the character <code>c</code> can be combined with the preceding character, that is mainly if it's a diacritic.</p> <p><strong>Edit 2</strong>: <code>remove_accents</code> expects a <em>unicode</em> string, not a byte string. If you have a byte string, then you must decode it into a unicode string like this:</p> <pre><code>encoding = "utf-8" # or iso-8859-15, or cp1252, or whatever encoding you use byte_string = b"café" # or simply "café" before python 3. unicode_string = byte_string.decode(encoding) </code></pre>
83
2009-02-05T21:19:34Z
[ "python", "python-3.x", "unicode", "python-2.x", "diacritics" ]
What is the best way to remove accents in a Python unicode string?
517,923
<p>I have a Unicode string in Python, and I would like to remove all the accents (diacritics).</p> <p>I found on the Web an elegant way to do this in Java:</p> <ol> <li>convert the Unicode string to its long normalized form (with a separate character for letters and diacritics)</li> <li>remove all the characters whose Unicode type is "diacritic".</li> </ol> <p>Do I need to install a library such as pyICU or is this possible with just the python standard library? And what about python 3?</p> <p>Important note: I would like to avoid code with an explicit mapping from accented characters to their non-accented counterpart.</p>
230
2009-02-05T21:10:40Z
518,232
<p>How about this:</p> <pre><code>import unicodedata def strip_accents(s): return ''.join(c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn') </code></pre> <p>This works on greek letters, too:</p> <pre><code>&gt;&gt;&gt; strip_accents(u"A \u00c0 \u0394 \u038E") u'A A \u0394 \u03a5' &gt;&gt;&gt; </code></pre> <p>The <a href="http://www.unicode.org/reports/tr44/#GC_Values_Table" rel="nofollow">character category</a> "Mn" stands for <code>Nonspacing_Mark</code>, which is similar to unicodedata.combining in MiniQuark's answer (I didn't think of unicodedata.combining, but it is probably the better solution, because it's more explicit).</p> <p>And keep in mind, these manipulations may significantly alter the meaning of the text. Accents, Umlauts etc. are not "decoration".</p>
164
2009-02-05T22:17:22Z
[ "python", "python-3.x", "unicode", "python-2.x", "diacritics" ]
What is the best way to remove accents in a Python unicode string?
517,923
<p>I have a Unicode string in Python, and I would like to remove all the accents (diacritics).</p> <p>I found on the Web an elegant way to do this in Java:</p> <ol> <li>convert the Unicode string to its long normalized form (with a separate character for letters and diacritics)</li> <li>remove all the characters whose Unicode type is "diacritic".</li> </ol> <p>Do I need to install a library such as pyICU or is this possible with just the python standard library? And what about python 3?</p> <p>Important note: I would like to avoid code with an explicit mapping from accented characters to their non-accented counterpart.</p>
230
2009-02-05T21:10:40Z
2,633,310
<p><a href="https://pypi.python.org/pypi/Unidecode">Unidecode</a> is the correct answer for this. It transliterates any unicode string into the closest possible representation in ascii text.</p>
155
2010-04-13T21:21:14Z
[ "python", "python-3.x", "unicode", "python-2.x", "diacritics" ]
What is the best way to remove accents in a Python unicode string?
517,923
<p>I have a Unicode string in Python, and I would like to remove all the accents (diacritics).</p> <p>I found on the Web an elegant way to do this in Java:</p> <ol> <li>convert the Unicode string to its long normalized form (with a separate character for letters and diacritics)</li> <li>remove all the characters whose Unicode type is "diacritic".</li> </ol> <p>Do I need to install a library such as pyICU or is this possible with just the python standard library? And what about python 3?</p> <p>Important note: I would like to avoid code with an explicit mapping from accented characters to their non-accented counterpart.</p>
230
2009-02-05T21:10:40Z
15,547,803
<p>This handles not only accents, but also "strokes" (as in ø etc.):</p> <pre><code>import unicodedata as ud def rmdiacritics(char): ''' Return the base character of char, by "removing" any diacritics like accents or curls and strokes and the like. ''' desc = ud.name(unicode(char)) cutoff = desc.find(' WITH ') if cutoff != -1: desc = desc[:cutoff] return ud.lookup(desc) </code></pre> <p>This is the most elegant way I can think of (and it has been mentioned by alexis in a comment on this page), although I don't think it is very elegant indeed.</p> <p>There are still special letters that are not handled by this, such as turned and inverted letters, since their unicode name does not contain 'WITH'. It depends on what you want to do anyway. I sometimes needed accent stripping for achieving dictionary sort order.</p>
9
2013-03-21T12:39:18Z
[ "python", "python-3.x", "unicode", "python-2.x", "diacritics" ]
What is the best way to remove accents in a Python unicode string?
517,923
<p>I have a Unicode string in Python, and I would like to remove all the accents (diacritics).</p> <p>I found on the Web an elegant way to do this in Java:</p> <ol> <li>convert the Unicode string to its long normalized form (with a separate character for letters and diacritics)</li> <li>remove all the characters whose Unicode type is "diacritic".</li> </ol> <p>Do I need to install a library such as pyICU or is this possible with just the python standard library? And what about python 3?</p> <p>Important note: I would like to avoid code with an explicit mapping from accented characters to their non-accented counterpart.</p>
230
2009-02-05T21:10:40Z
17,069,876
<p>In response to @MiniQuark's answer:</p> <p>I was trying to read in a csv file that was half-French (containing accents) and also some strings which would eventually become integers and floats. As a test, I created a <code>test.txt</code> file that looked like this:</p> <blockquote> <p>Montréal, über, 12.89, Mère, Françoise, noël, 889</p> </blockquote> <p>I had to include lines <code>2</code> and <code>3</code> to get it to work (which I found in a python ticket), as well as incorporate @Jabba's comment:</p> <pre><code>import sys reload(sys) sys.setdefaultencoding("utf-8") import csv import unicodedata def remove_accents(input_str): nkfd_form = unicodedata.normalize('NFKD', unicode(input_str)) return u"".join([c for c in nkfd_form if not unicodedata.combining(c)]) with open('test.txt') as f: read = csv.reader(f) for row in read: for element in row: print remove_accents(element) </code></pre> <p>The result:</p> <pre><code>Montreal uber 12.89 Mere Francoise noel 889 </code></pre> <p>(Note: I am on Mac OS X 10.8.4 and using Python 2.7.3)</p>
8
2013-06-12T15:48:48Z
[ "python", "python-3.x", "unicode", "python-2.x", "diacritics" ]
What is the best way to remove accents in a Python unicode string?
517,923
<p>I have a Unicode string in Python, and I would like to remove all the accents (diacritics).</p> <p>I found on the Web an elegant way to do this in Java:</p> <ol> <li>convert the Unicode string to its long normalized form (with a separate character for letters and diacritics)</li> <li>remove all the characters whose Unicode type is "diacritic".</li> </ol> <p>Do I need to install a library such as pyICU or is this possible with just the python standard library? And what about python 3?</p> <p>Important note: I would like to avoid code with an explicit mapping from accented characters to their non-accented counterpart.</p>
230
2009-02-05T21:10:40Z
31,607,735
<p>Actually I work on project compatible python 2.6, 2.7 and 3.4 and I have to create IDs from free user entries. </p> <p>Thanks to you, I have created this function that works wonders.</p> <pre><code>import re import unicodedata def strip_accents(text): """ Strip accents from input String. :param text: The input string. :type text: String. :returns: The processed String. :rtype: String. """ try: text = unicode(text, 'utf-8') except NameError: # unicode is a default on python 3 pass text = unicodedata.normalize('NFD', text) text = text.encode('ascii', 'ignore') text = text.decode("utf-8") return str(text) def text_to_id(text): """ Convert input text to id. :param text: The input string. :type text: String. :returns: The processed String. :rtype: String. """ text = strip_accents(text.lower()) text = re.sub('[ ]+', '_', text) text = re.sub('[^0-9a-zA-Z_-]', '', text) return text </code></pre> <p>result:</p> <pre><code>text_to_id("Montréal, über, 12.89, Mère, Françoise, noël, 889") &gt;&gt;&gt; 'montreal_uber_1289_mere_francoise_noel_889' </code></pre>
6
2015-07-24T10:08:14Z
[ "python", "python-3.x", "unicode", "python-2.x", "diacritics" ]
What is the best way to remove accents in a Python unicode string?
517,923
<p>I have a Unicode string in Python, and I would like to remove all the accents (diacritics).</p> <p>I found on the Web an elegant way to do this in Java:</p> <ol> <li>convert the Unicode string to its long normalized form (with a separate character for letters and diacritics)</li> <li>remove all the characters whose Unicode type is "diacritic".</li> </ol> <p>Do I need to install a library such as pyICU or is this possible with just the python standard library? And what about python 3?</p> <p>Important note: I would like to avoid code with an explicit mapping from accented characters to their non-accented counterpart.</p>
230
2009-02-05T21:10:40Z
31,609,516
<p>Some languages have combining diacritics as language letters and accent diacritics to specify accent.</p> <p>I think it is more safe to specify explicitly what diactrics you want to strip:</p> <pre><code>def strip_accents(string, accents=('COMBINING ACUTE ACCENT', 'COMBINING GRAVE ACCENT', 'COMBINING TILDE')): accents = set(map(unicodedata.lookup, accents)) chars = [c for c in unicodedata.normalize('NFD', string) if c not in accents] return unicodedata.normalize('NFC', ''.join(chars)) </code></pre>
0
2015-07-24T11:34:02Z
[ "python", "python-3.x", "unicode", "python-2.x", "diacritics" ]
What is the best way to remove accents in a Python unicode string?
517,923
<p>I have a Unicode string in Python, and I would like to remove all the accents (diacritics).</p> <p>I found on the Web an elegant way to do this in Java:</p> <ol> <li>convert the Unicode string to its long normalized form (with a separate character for letters and diacritics)</li> <li>remove all the characters whose Unicode type is "diacritic".</li> </ol> <p>Do I need to install a library such as pyICU or is this possible with just the python standard library? And what about python 3?</p> <p>Important note: I would like to avoid code with an explicit mapping from accented characters to their non-accented counterpart.</p>
230
2009-02-05T21:10:40Z
39,059,237
<p>I'm surprised no one suggested a simple: </p> <pre><code>from unidecode import unidecode s="Montréal, über, 12.89, Mère, Françoise, noël, 889" #s.encode("ascii") #doesn't work - traceback t=unidecode(s) t.encode("ascii") #works fine, because all non-ASCII from s are replaced with their equivalents print(t) #gives: 'Montreal, uber, 12.89, Mere, Francoise, noel, 889' </code></pre> <p>You can download unidecode lib <a href="https://pypi.python.org/pypi/Unidecode" rel="nofollow">here</a>.</p>
3
2016-08-20T22:28:03Z
[ "python", "python-3.x", "unicode", "python-2.x", "diacritics" ]
What is the best way to remove accents in a Python unicode string?
517,923
<p>I have a Unicode string in Python, and I would like to remove all the accents (diacritics).</p> <p>I found on the Web an elegant way to do this in Java:</p> <ol> <li>convert the Unicode string to its long normalized form (with a separate character for letters and diacritics)</li> <li>remove all the characters whose Unicode type is "diacritic".</li> </ol> <p>Do I need to install a library such as pyICU or is this possible with just the python standard library? And what about python 3?</p> <p>Important note: I would like to avoid code with an explicit mapping from accented characters to their non-accented counterpart.</p>
230
2009-02-05T21:10:40Z
39,612,904
<p>import unicodedata</p> <p>s = 'Émission'</p> <p>search_string = ''.join((c for c in unicodedata.normalize('NFD', s) if unicodedata.category(c) != 'Mn'))</p> <p>For PYTHON 3.X print (search_string) For PYTHON 2.X print search_string</p>
0
2016-09-21T09:41:47Z
[ "python", "python-3.x", "unicode", "python-2.x", "diacritics" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
517,992
<p>Well, here's a quick hack:</p> <pre><code>&gt;&gt;&gt; clear = "\n" * 100 &gt;&gt;&gt; print clear &gt;&gt;&gt; ...do some other stuff... &gt;&gt;&gt; print clear </code></pre> <p>Or to save some typing, put this file in your python search path:</p> <pre><code># wiper.py class Wipe(object): def __repr__(self): return '\n'*1000 wipe = Wipe() </code></pre> <p>Then you can do this from the interpreter all you like :)</p> <pre><code>&gt;&gt;&gt; from wiper import wipe &gt;&gt;&gt; wipe &gt;&gt;&gt; wipe &gt;&gt;&gt; wipe </code></pre>
56
2009-02-05T21:22:43Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
518,007
<p>As you mentioned, you can do a system call:</p> <pre><code>&gt;&gt;&gt; import os &gt;&gt;&gt; clear = lambda: os.system('cls') &gt;&gt;&gt; clear() </code></pre> <p>I am not sure of any other way in Windows.</p>
218
2009-02-05T21:25:08Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
518,401
<p>Use idle. It has many handy features. <kbd>Ctrl+F6</kbd>, for example, resets the console. Closing and opening the console are good ways to clear it.</p>
5
2009-02-05T23:03:55Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
518,540
<p>EDIT: I've just read "windows", this is for linux users, sorry.</p> <p><hr /></p> <p>In bash:</p> <pre><code>#!/bin/bash while [ "0" == "0" ]; do clear $@ while [ "$input" == "" ]; do read -p "Do you want to quit? (y/n): " -n 1 -e input if [ "$input" == "y" ]; then exit 1 elif [ "$input" == "n" ]; then echo "Ok, keep working ;)" fi done input="" done </code></pre> <p>Save it as "whatyouwant.sh", chmod +x it then run:</p> <pre><code>./whatyouwant.sh python </code></pre> <p>or something other than python (idle, whatever). This will ask you if you actually want to exit, if not it rerun python (or the command you gave as parameter).</p> <p>This will clear all, the screen and all the variables/object/anything you created/imported in python. </p> <p>In python just type exit() when you want to exit.</p>
1
2009-02-05T23:51:51Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
684,344
<p>here something handy that is a little more cross-platform</p> <pre><code>import os def cls(): os.system('cls' if os.name=='nt' else 'clear') # now, to clear the screen cls() </code></pre>
111
2009-03-26T02:42:42Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
759,084
<p>Wiper is cool, good thing about it is I don't have to type '()' around it. Here is slight variation to it</p> <pre><code># wiper.py import os class Cls(object): def __repr__(self):         os.system('cls') return '' </code></pre> <p>The usage is quite simple:</p> <pre><code>&gt;&gt;&gt; cls = Cls() &gt;&gt;&gt; cls # this will clear console. </code></pre>
6
2009-04-17T04:58:19Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
3,917,856
<p>Although this is an older question, I thought I'd contribute something summing up what I think were the best of the other answers and add a wrinkle of my own by suggesting that you put these command(s) into a file and set your PYTHONSTARTUP environment variable to point to it. Since I'm on Windows at the moment, it's slightly biased that way, but could easily be slanted some other direction.</p> <p>Here's some articles I found that describe how to set environment variables on Windows:<br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="http://stackoverflow.com/a/4209102/355230">When to use sys.path.append and when modifying %PYTHONPATH% is enough</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="http://support.microsoft.com/kb/310519">How To Manage Environment Variables in Windows XP</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="http://technet.microsoft.com/en-us/library/bb726962.aspx">Configuring System and User Environment Variables</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="http://www.howtogeek.com/51807/how-to-create-and-use-global-system-environment-variables/">How to Use Global System Environment Variables in Windows</a><br/></p> <p>BTW, don't put quotes around the path to the file even if it has spaces in it.</p> <p>Anyway, here's my take on the code to put in (or add to your existing) Python startup script:</p> <pre><code># ==== pythonstartup.py ==== # add something to clear the screen class cls(object): def __repr__(self): import os os.system('cls' if os.name == 'nt' else 'clear') return '' cls = cls() # ==== end pythonstartup.py ==== </code></pre> <p>BTW, you can also use @<a href="http://stackoverflow.com/questions/517970/how-to-clear-python-interpreter-console/517992#517992">Triptych's</a> <code>__repr__</code> trick to change <code>exit()</code> into just <code>exit</code> (and ditto for its alias <code>quit</code>):</p> <pre><code>class exit(object): exit = exit # original object def __repr__(self): self.exit() # call original return '' quit = exit = exit() </code></pre> <p>Lastly, here's something else that changes the primary interpreter prompt from <code>&gt;&gt;&gt;</code> to <em>cwd</em>+<code>&gt;&gt;&gt;</code>:</p> <pre><code>class Prompt: def __str__(self): import os return '%s &gt;&gt;&gt; ' % os.getcwd() import sys sys.ps1 = Prompt() del sys del Prompt </code></pre>
22
2010-10-12T18:36:11Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
5,369,197
<p>This should be cross platform, and also uses the preferred <code>subprocess.call</code> instead of <code>os.system</code> as per <a href="http://docs.python.org/library/os.html#os.system" rel="nofollow">the <code>os.system</code> docs</a>. Should work in Python >= 2.4.</p> <pre><code>import subprocess import os if os.name == 'nt': def clearscreen(): subprocess.call("cls", shell=True) return else: def clearscreen(): subprocess.call("clear", shell=True) return </code></pre>
1
2011-03-20T14:51:23Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
7,265,491
<p><strong>Here are two nice ways of doing that:</strong></p> <p><strong>1.</strong> </p> <pre><code>import os # Clear Windows command prompt. if (os.name in ('ce', 'nt', 'dos')): os.system('cls') # Clear the Linux terminal. elif ('posix' in os.name): os.system('clear') </code></pre> <p><strong>2.</strong></p> <pre><code>import os def clear(): if os.name == 'posix': os.system('clear') elif os.name in ('ce', 'nt', 'dos'): os.system('cls') clear() </code></pre>
1
2011-09-01T02:13:46Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
7,987,728
<p>How about this for a clear</p> <pre><code>- os.system('cls') </code></pre> <p>That is about as short as could be!</p>
1
2011-11-02T21:48:09Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
8,055,652
<p>I'm using MINGW/BASH on Windows XP, SP3.</p> <p>(stick this in .pythonstartup)<br> # My ctrl-l already kind of worked, but this might help someone else<br> # leaves prompt at bottom of the window though...<br> import readline<br> readline.parse_and_bind('\C-l: clear-screen') </p> <p># This works in BASH because I have it in .inputrc as well, but for some<br> # reason it gets dropped when I go into Python<br> readline.parse_and_bind('\C-y: kill-whole-line') </p> <hr> <p>I couldn't stand typing 'exit()' anymore and was delighted with martineau's/Triptych's tricks:</p> <p>I slightly doctored it though (stuck it in .pythonstartup) </p> <pre><code>class exxxit(): """Shortcut for exit() function, use 'x' now""" quit_now = exit # original object def __repr__(self): self.quit_now() # call original x = exxxit() </code></pre> <hr> <pre><code>Py2.7.1&gt;help(x) Help on instance of exxxit in module __main__: class exxxit | Shortcut for exit() function, use 'x' now | | Methods defined here: | | __repr__(self) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | quit_now = Use exit() or Ctrl-Z plus Return to exit </code></pre>
3
2011-11-08T18:56:43Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
8,463,527
<p>The OS command <code>clear</code> in Linux and <code>cls</code> in Windows outputs a "magic string" which you can just print. To get the string, execute the command with popen and save it in a variable for later use:</p> <pre><code>from os import popen with popen('clear') as f: clear = f.read() print clear </code></pre> <p>On my machine the string is <code>'\x1b[H\x1b[2J'</code>.</p>
1
2011-12-11T11:19:25Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
9,751,966
<pre><code>&gt;&gt;&gt; ' '*80*25 </code></pre> <p><strong>UPDATE</strong>: 80x25 is unlikely to be the size of console windows, so to get the real console dimensions, use functions from <a href="https://pypi.python.org/pypi/pager" rel="nofollow">pager</a> module. Python doesn't provide anything similar from core distribution.</p> <pre><code>&gt;&gt;&gt; from pager import getheight &gt;&gt;&gt; '\n' * getheight() </code></pre>
-1
2012-03-17T17:08:50Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
11,526,998
<p>Here's <a href="https://gist.github.com/3130325" rel="nofollow">the definitive solution</a> that merges <strong>all other answers</strong>. Features:</p> <ol> <li>You can <strong>copy-paste</strong> the code into your shell or script.</li> <li><p>You can <strong>use</strong> it as you like:</p> <pre><code>&gt;&gt;&gt; clear() &gt;&gt;&gt; -clear &gt;&gt;&gt; clear # &lt;- but this will only work on a shell </code></pre></li> <li><p>You can <strong>import</strong> it as a module:</p> <pre><code>&gt;&gt;&gt; from clear import clear &gt;&gt;&gt; -clear </code></pre></li> <li><p>You can <strong>call</strong> it as a script:</p> <pre><code>$ python clear.py </code></pre></li> <li><p>It is <strong>truly multiplatform</strong>; if it can't recognize your system<br> (<code>ce</code>, <code>nt</code>, <code>dos</code> or <code>posix</code>) it will fall back to printing blank lines.</p></li> </ol> <hr> <p>You can download the [full] file here: <a href="https://gist.github.com/3130325" rel="nofollow">https://gist.github.com/3130325</a><br> Or if you are just looking for the code:</p> <pre><code>class clear: def __call__(self): import os if os.name==('ce','nt','dos'): os.system('cls') elif os.name=='posix': os.system('clear') else: print('\n'*120) def __neg__(self): self() def __repr__(self): self();return '' clear=clear() </code></pre>
5
2012-07-17T16:38:19Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
15,623,297
<p>I'm new to python (really really new) and in one of the books I'm reading to get acquainted with the language they teach how to create this little function to clear the console of the visible backlog and past commands and prints:</p> <p>Open shell / Create new document / Create function as follows:</p> <pre><code>def clear(): print('\n' * 50) </code></pre> <p>Save it inside the lib folder in you python directory (mine is C:\Python33\Lib) Next time you nedd to clear your console just call the function with:</p> <pre><code>clear() </code></pre> <p>that's it. PS: you can name you function anyway you want. Iv' seen people using "wiper" "wipe" and variations.</p>
1
2013-03-25T19:41:24Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
17,536,224
<p>OK, so this is a much less technical answer, but I'm using the Python plugin for Notepad++ and it turns out you can just clear the console manually by right-clicking on it and clicking "clear". Hope this helps someone out there!</p>
0
2013-07-08T21:24:28Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
17,711,382
<p>In Spyder, when you want to clear all the variables in you Variable explorer, simply type <em>global().clear()</em> in the Console, and they will all be gone.</p>
-2
2013-07-17T22:28:54Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
18,846,817
<p>I found the simplest way is just to close the window and run a module/script to reopen the shell.</p>
2
2013-09-17T10:00:57Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
21,210,375
<p>Magic strings are mentioned above - I believe they come from the terminfo database:</p> <p><a href="http://www.google.com/?q=x#q=terminfo" rel="nofollow">http://www.google.com/?q=x#q=terminfo</a></p> <p><a href="http://www.google.com/?q=x#q=tput+command+in+unix" rel="nofollow">http://www.google.com/?q=x#q=tput+command+in+unix</a></p> <p>$ tput clear| od -t x1z 0000000 1b 5b 48 1b 5b 32 4a >.[H.[2J&lt; 0000007</p>
1
2014-01-18T21:54:03Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
23,730,811
<p>just use this..</p> <p><code>print '\n'*1000</code></p>
2
2014-05-19T06:15:17Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
29,520,444
<p>I am using Spyder (Python 2.7) and to clean the interpreter console I use either </p> <p>%clear </p> <p>that forces the command line to go to the top and I will not see the previous old commands.</p> <p>or I click "option" on the Console environment and select "Restart kernel" that removes everything.</p>
0
2015-04-08T16:35:45Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
30,619,161
<p>my way of doing this is to write a function like so:</p> <pre><code>import os,subprocess def clear(): if os.name = ('nt','dos'): subprocess.call("cls") elif os.name = ('linux','osx','posix'): subprocess.call("clear") else: print "\n"*120 </code></pre> <p>then call <code>clear()</code> to clear the screen. this works on windows, osx, linux, bsd... all OSes.</p>
5
2015-06-03T11:44:59Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
31,104,446
<p>I'm not sure if Windows' "shell" supports this, but on Linux:</p> <p><code>print "\033[2J"</code></p> <p><a href="https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes" rel="nofollow">https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes</a></p> <p>In my opinion calling <code>cls</code> with <code>os</code> is a bad idea generally. Imagine if I manage to change the cls or clear command on your system, and you run your script as admin or root.</p>
1
2015-06-28T20:31:32Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
31,640,548
<p>If its on mac a simple cmd + k does the trick</p>
0
2015-07-26T18:37:17Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
32,280,047
<p>Quickest and easiest way without a doubt is <kbd>Ctrl</kbd>+<kbd>L</kbd>.</p> <p>This is the same for OS X on the terminal. </p>
5
2015-08-28T21:32:00Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
37,106,601
<p>I use <a href="https://www.iterm2.com/" rel="nofollow">iTerm</a> and the native terminal app for Mac OS.</p> <p>I just press ⌘ + k</p>
3
2016-05-09T01:19:38Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
37,925,455
<p>You have number of ways doing it on Windows:</p> <h1>1. Using Keyboard shortcut:</h1> <pre><code>Press CTRL + L </code></pre> <h1>2. Using system invoke method:</h1> <pre><code>import os cls = lambda: os.system('cls') cls() </code></pre> <h1>3. Using new line print 100 times:</h1> <pre><code>cls = lambda: print('\n'*100) cls() </code></pre>
4
2016-06-20T14:46:29Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
38,758,248
<p>At the prompt type in "cls" and hit enter. </p>
-1
2016-08-04T03:57:18Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
38,986,254
<p>I might be late to the part but here is a very easy way to do it</p> <p>Type:</p> <pre><code>def cls(): os.system("cls") </code></pre> <p>So what ever you want to clear the screen just type in your code</p> <pre><code>cls() </code></pre> <p>Best way possible! (Credit : <a href="https://www.youtube.com/watch?annotation_id=annotation_3770292585&amp;feature=iv&amp;src_vid=bguKhMnvmb8&amp;v=LtGEp9c6Z-U" rel="nofollow">https://www.youtube.com/watch?annotation_id=annotation_3770292585&amp;feature=iv&amp;src_vid=bguKhMnvmb8&amp;v=LtGEp9c6Z-U</a>)</p>
-1
2016-08-17T00:05:00Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
39,801,391
<p><a href="https://github.com/adoxa/ansicon/releases" rel="nofollow">https://github.com/adoxa/ansicon/releases</a></p> <p>There is a tool you can install for Windows and then use the following print: print "\x1b[2J"</p> <p>See link for tool below:</p>
-1
2016-09-30T23:22:47Z
[ "windows", "console", "clear", "python" ]
How to clear python interpreter console?
517,970
<p>Like most Python developers, I typically keep a console window open with the Python interpreter running to test commands, dir() stuff, help() stuff, etc.</p> <p>Like any console, after a while the visible backlog of past commands and prints gets to be cluttered, and sometimes confusing when re-running the same command several times. I'm wondering if, and how, to clear the Python interpreter console.</p> <p>I've heard about doing a system call and either calling <code>cls</code> on Windows or <code>clear</code> on Linux, but I was hoping there was something I could command the interpreter itself to do.</p> <p><strong>Note:</strong> I'm running on Windows, so Ctrl+L doesn't work.</p>
169
2009-02-05T21:19:20Z
40,116,016
<p>Stumbled upon this: Just keep pressing <kbd>page down</kbd> till the screen is cleared!</p> <p>Then press <kbd>enter</kbd> for the <code>&gt;&gt;&gt;</code> prompt.</p> <p>Surprised nobody has mentioned this yet.</p>
0
2016-10-18T19:00:00Z
[ "windows", "console", "clear", "python" ]
Getting the length of an array in Python
518,021
<p>In <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>, is the following the only way to get the number of elements?</p> <pre><code>arr.__len__() </code></pre> <p>If so, why the strange syntax?</p>
400
2009-02-05T21:26:47Z
518,038
<pre><code>my_list = [1,2,3,4,5] len(my_list) </code></pre> <p>The same works for tuples:</p> <pre><code>my_tuple = (1,2,3,4,5) len(my_tuple) </code></pre> <p>And strings, which are really just arrays of characters:</p> <pre><code>my_string = 'hello world' len(my_string) </code></pre> <p>It was <a href="http://effbot.org/pyfaq/why-does-python-use-methods-for-some-functionality-e-g-list-index-but-functions-for-other-e-g-len-list.htm">intentionally done this way</a> so that lists, tuples and other container types didn't all need to explicitly implement a public <code>.length()</code> method, instead you can just check the <code>len()</code> of anything that implements the 'magic' <code>__len__()</code> method.</p> <p>Sure, this may seem redundant, but length checking implementations can vary considerably, even within the same language. It's not uncommon to see one collection type use a <code>.length()</code> method while another type uses a <code>.length</code> property, while yet another uses <code>.count()</code>. Having a language-level keyword unifies the entry point for all these types. So even objects you may not consider to be lists of elements could still be length-checked. This includes strings, queues, trees, etc.</p>
718
2009-02-05T21:29:48Z
[ "python", "arrays" ]
Getting the length of an array in Python
518,021
<p>In <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>, is the following the only way to get the number of elements?</p> <pre><code>arr.__len__() </code></pre> <p>If so, why the strange syntax?</p>
400
2009-02-05T21:26:47Z
518,039
<p>Just use len(arr):</p> <pre><code>&gt;&gt;&gt; import array &gt;&gt;&gt; arr = array.array('i') &gt;&gt;&gt; arr.append('2') &gt;&gt;&gt; arr.__len__() 1 &gt;&gt;&gt; len(arr) 1 </code></pre>
13
2009-02-05T21:30:05Z
[ "python", "arrays" ]
Getting the length of an array in Python
518,021
<p>In <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>, is the following the only way to get the number of elements?</p> <pre><code>arr.__len__() </code></pre> <p>If so, why the strange syntax?</p>
400
2009-02-05T21:26:47Z
518,053
<p>The preferred way to get the length of any python object is to pass it as an argument to the <code>len</code> function. Internally, python will then try to call the special <code>__len__</code> method of the object that was passed.</p>
19
2009-02-05T21:32:43Z
[ "python", "arrays" ]
Getting the length of an array in Python
518,021
<p>In <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>, is the following the only way to get the number of elements?</p> <pre><code>arr.__len__() </code></pre> <p>If so, why the strange syntax?</p>
400
2009-02-05T21:26:47Z
518,061
<p>The way you take a length of anything for which that makes sense (a list, dictionary, tuple, string, ...) is to call <code>len</code> on it.</p> <pre><code>l = [1,2,3,4] s = 'abcde' len(l) #returns 4 len(s) #returns 5 </code></pre> <p>The reason for the "strange" syntax is that internally python translates <code>len(object)</code> into <code>object.__len__()</code>. This applies to any object. So, if you are defining some class and it makes sense for it to have a length, just define a <code>__len__()</code> method on it and then one can call <code>len</code> on those instances.</p>
32
2009-02-05T21:34:00Z
[ "python", "arrays" ]
Getting the length of an array in Python
518,021
<p>In <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>, is the following the only way to get the number of elements?</p> <pre><code>arr.__len__() </code></pre> <p>If so, why the strange syntax?</p>
400
2009-02-05T21:26:47Z
519,644
<p>Python uses <a href="http://en.wikipedia.org/wiki/Duck_typing">duck typing</a>: it doesn't care about what an object <em>is</em>, as long as it has the appropriate interface for the situation at hand. When you call the built-in function len() on an object, you are actually calling its internal __len__ method. A custom object can implement this interface and len() will return the answer, even if the object is not conceptually a sequence.</p> <p>For a complete list of interfaces, have a look here: <a href="http://docs.python.org/reference/datamodel.html#basic-customization">http://docs.python.org/reference/datamodel.html#basic-customization</a></p>
18
2009-02-06T09:15:37Z
[ "python", "arrays" ]
Getting the length of an array in Python
518,021
<p>In <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>, is the following the only way to get the number of elements?</p> <pre><code>arr.__len__() </code></pre> <p>If so, why the strange syntax?</p>
400
2009-02-05T21:26:47Z
33,226,444
<p>you can use <code>len(arr)</code> as suggested in previous answers to get the length of the array. In case you want the dimensions of a 2D array you could use <code>arr.shape</code> returns height and width</p>
3
2015-10-20T01:10:57Z
[ "python", "arrays" ]
Getting the length of an array in Python
518,021
<p>In <a href="http://en.wikipedia.org/wiki/Python_%28programming_language%29">Python</a>, is the following the only way to get the number of elements?</p> <pre><code>arr.__len__() </code></pre> <p>If so, why the strange syntax?</p>
400
2009-02-05T21:26:47Z
36,571,771
<p><code>len(list_name)</code> function takes list as a parameter and it calls list's <code>__len__()</code> function.</p>
2
2016-04-12T11:20:13Z
[ "python", "arrays" ]
How to work with unsaved many-to-many relations in django?
518,162
<p>I have a couple of models in django which are connected many-to-many. I want to create instances of these models <em>in memory</em>, present them to the user (via custom method-calls inside the view-templates) and if the user is satisfied, save them to the database.</p> <p>However, if I try to do anything on the model-instances (call rendering methods, e.g.), I get an error message that says that I have to save the instances first. The documentation says that this is because the models are in a many-to-many relationship.</p> <p>How do I present objects to the user and allowing him/her to save or discard them without cluttering my database?</p> <p>(I guess I could turn off transactions-handling and do them myself throughout the whole project, but this sounds like a potentially error-prone measure...)</p> <p>Thx!</p>
4
2009-02-05T22:01:17Z
518,290
<p>I would add a field which indicates whether the objects are "draft" or "live". That way they are persisted across requests, sessions, etc. and django stops complaining.</p> <p>You can then filter your objects to only show "live" objects in public views and only show "draft" objects to the user that created them. This can also be extended to allow "archived" objects (or any other state that makes sense).</p>
6
2009-02-05T22:34:11Z
[ "python", "django", "django-models", "many-to-many" ]
How to work with unsaved many-to-many relations in django?
518,162
<p>I have a couple of models in django which are connected many-to-many. I want to create instances of these models <em>in memory</em>, present them to the user (via custom method-calls inside the view-templates) and if the user is satisfied, save them to the database.</p> <p>However, if I try to do anything on the model-instances (call rendering methods, e.g.), I get an error message that says that I have to save the instances first. The documentation says that this is because the models are in a many-to-many relationship.</p> <p>How do I present objects to the user and allowing him/her to save or discard them without cluttering my database?</p> <p>(I guess I could turn off transactions-handling and do them myself throughout the whole project, but this sounds like a potentially error-prone measure...)</p> <p>Thx!</p>
4
2009-02-05T22:01:17Z
519,483
<p>I think that using django forms may be the answer, as outlined in <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/" rel="nofollow">this</a> documentation (search for m2m...).</p> <p>Edited to add some explanation for other people who might have the same problem:</p> <p>say you have a model like this:</p> <pre><code>from django.db import models from django.forms import ModelForm class Foo(models.Model): name = models.CharField(max_length = 30) class Bar(models.Model): foos = models.ManyToManyField(Foo) def __unicode__(self): return " ".join([x.name for x in foos]) </code></pre> <p>then you cannot call unicode() on an unsaved Bar object. If you do want to print things out before they will be saved, you have to do this:</p> <pre><code>class BarForm(ModelForm): class Meta: model = Bar def example(): f1 = Foo(name = 'sue') f1.save() f2 = foo(name = 'wendy') f2.save() bf = BarForm({'foos' : [f1.id, f2.id]}) b = bf.save(commit = false) # unfortunately, unicode(b) doesn't work before it is saved properly, # so we need to do it this way: if(not bf.is_valid()): print bf.errors else: for (key, value) in bf.cleaned_data.items(): print key + " =&gt; " + str(value) </code></pre> <p>So, in this case, you have to have saved Foo objects (which you might validate before saving those, using their own form), and before saving the models with many to many keys, you can validate those as well. All without the need to save data too early and mess up the database or dealing with transactions...</p>
4
2009-02-06T07:52:11Z
[ "python", "django", "django-models", "many-to-many" ]
How can I manipulate lists?
518,679
<p>In the computer algebra system <a href="http://www.sagemath.org/" rel="nofollow">Sage</a>, I need to multiply a list by 2.</p> <p>I tried the code</p> <pre><code>sage: list = [1, 2, 3]; sage: 2 * list </code></pre> <p>which returns</p> <pre><code>[1, 2, 3, 1, 2, 3] </code></pre> <p>How can I just multiply each element by two?</p>
1
2009-02-06T00:48:23Z
518,895
<p>Do you want to multiply each element by 2? That would be:</p> <pre><code>[2*i for i in List] </code></pre>
3
2009-02-06T02:35:43Z
[ "python", "list" ]
How can I manipulate lists?
518,679
<p>In the computer algebra system <a href="http://www.sagemath.org/" rel="nofollow">Sage</a>, I need to multiply a list by 2.</p> <p>I tried the code</p> <pre><code>sage: list = [1, 2, 3]; sage: 2 * list </code></pre> <p>which returns</p> <pre><code>[1, 2, 3, 1, 2, 3] </code></pre> <p>How can I just multiply each element by two?</p>
1
2009-02-06T00:48:23Z
1,262,098
<p>Or:</p> <pre><code>import numpy numpy.multiply(List, 2) </code></pre>
1
2009-08-11T18:19:49Z
[ "python", "list" ]
How can I manipulate lists?
518,679
<p>In the computer algebra system <a href="http://www.sagemath.org/" rel="nofollow">Sage</a>, I need to multiply a list by 2.</p> <p>I tried the code</p> <pre><code>sage: list = [1, 2, 3]; sage: 2 * list </code></pre> <p>which returns</p> <pre><code>[1, 2, 3, 1, 2, 3] </code></pre> <p>How can I just multiply each element by two?</p>
1
2009-02-06T00:48:23Z
8,599,183
<p>You manipulate lists in Sage just how you would manipulate them in Python because Sage is based on Python. So, read about Python lists and you will learn to do whatever you want with lists in Sage. Here:</p> <p><a href="http://docs.python.org/tutorial/datastructures.html" rel="nofollow">http://docs.python.org/tutorial/datastructures.html</a></p>
0
2011-12-22T03:39:36Z
[ "python", "list" ]
How can I manipulate lists?
518,679
<p>In the computer algebra system <a href="http://www.sagemath.org/" rel="nofollow">Sage</a>, I need to multiply a list by 2.</p> <p>I tried the code</p> <pre><code>sage: list = [1, 2, 3]; sage: 2 * list </code></pre> <p>which returns</p> <pre><code>[1, 2, 3, 1, 2, 3] </code></pre> <p>How can I just multiply each element by two?</p>
1
2009-02-06T00:48:23Z
11,052,812
<p>Or convert the list to a vector first:</p> <pre><code>a = vector([1,2,3]) 2*a </code></pre> <p>which returns</p> <pre><code>(2, 4, 6) </code></pre> <p>Vectors can be used in matrix-multiplication, and have methods which might be useful such as ".dot_product".</p> <p>Btw, it is probably not a good idea in Sage or Python to call your variable "list".</p>
1
2012-06-15T14:37:11Z
[ "python", "list" ]
List/Arrays - Check Dates
518,782
<p>I'm trying to make a program that checks an array to make sure there are four folders with partially same names.</p> <p>So</p> <p>For a date like 0103 (jan 3rd), there should be 0103-1, 0103-2, 0103-3, and 0103-4. Other folders are like 0107-1, 0107-2, 0107-3, 0107-4. How do I go about doing this? I thought about using glob.glob (python) and wildcards to make sure there are only four matches...but I don't like this method.</p> <p>Any suggestions?</p>
0
2009-02-06T01:35:00Z
518,798
<pre><code>import os def myfunc(date, num): for x in range(1, num+1): filename = str(date) + "-" + str(x) if os.path.exists(filename): print(filename+" exists") else: print(filename+" does not exist") myfunc('0102', 3); </code></pre> <p><em>0102-1 does not exist</em></p> <p><em>0102-2 does not exist</em></p> <p><em>0102-3 does not exist</em></p>
3
2009-02-06T01:46:44Z
[ "python", "sorting" ]
List/Arrays - Check Dates
518,782
<p>I'm trying to make a program that checks an array to make sure there are four folders with partially same names.</p> <p>So</p> <p>For a date like 0103 (jan 3rd), there should be 0103-1, 0103-2, 0103-3, and 0103-4. Other folders are like 0107-1, 0107-2, 0107-3, 0107-4. How do I go about doing this? I thought about using glob.glob (python) and wildcards to make sure there are only four matches...but I don't like this method.</p> <p>Any suggestions?</p>
0
2009-02-06T01:35:00Z
519,196
<p>Here's a naive way to find the largest common leading substring given an array of strings:</p> <pre><code>&gt;&gt;&gt; arr = ['0102-1', '0102-2', '0102-3'] &gt;&gt;&gt; for i in reversed(range(len(arr[0]))): ... for s in arr: ... if not s.startswith(arr[0][:i+1]): ... break ... else: ... break ... else: ... if i == 0: i = -1 ... &gt;&gt;&gt; arr[0][:i+1] '0102-' &gt;&gt;&gt; i 4 </code></pre>
0
2009-02-06T05:16:05Z
[ "python", "sorting" ]
Getting OperationalError: FATAL: sorry, too many clients already using psycopg2
519,296
<p>I am getting the error OperationalError: FATAL: sorry, too many clients already when using psycopg2. I am calling the close method on my connection instance after I am done with it. I am not sure what could be causing this, it is my first experience with python and postgresql, but I have a few years experience with php, asp.net, mysql, and sql server.</p> <p>EDIT: I am running this locally, if the connections are closing like they should be then I only have 1 connection open at a time. I did have a GUI open to the database but even closed I am getting this error. It is happening very shortly after I run my program. I have a function I call that returns a connection that is opened like:</p> <p>psycopg2.connect(connectionString)</p> <p>Thanks</p> <p>Final Edit: It was my mistake, I was recursively calling the same method on mistake that was opening the same method over and over. It has been a long day..</p>
3
2009-02-06T06:15:50Z
519,304
<p>This error means what it says, there are too many clients connected to postgreSQL. Are you the only one connected to this database? Are you running a graphical IDE? What method are you using to connect? Are you testing queries at the same time that you running the code? any of these things could be the problem. If you are the admin, you can up the number of clients, but if a program is hanging it open, then that won't help for long. </p> <p>There are too many reasons that you could be having too many clients running at the same time with the sparse info that you gave us.</p>
4
2009-02-06T06:24:20Z
[ "python", "postgresql", "psycopg2" ]
Getting OperationalError: FATAL: sorry, too many clients already using psycopg2
519,296
<p>I am getting the error OperationalError: FATAL: sorry, too many clients already when using psycopg2. I am calling the close method on my connection instance after I am done with it. I am not sure what could be causing this, it is my first experience with python and postgresql, but I have a few years experience with php, asp.net, mysql, and sql server.</p> <p>EDIT: I am running this locally, if the connections are closing like they should be then I only have 1 connection open at a time. I did have a GUI open to the database but even closed I am getting this error. It is happening very shortly after I run my program. I have a function I call that returns a connection that is opened like:</p> <p>psycopg2.connect(connectionString)</p> <p>Thanks</p> <p>Final Edit: It was my mistake, I was recursively calling the same method on mistake that was opening the same method over and over. It has been a long day..</p>
3
2009-02-06T06:15:50Z
15,046,529
<p>Make sure your db connection command isn't in any kind of loop. I was getting the same error from my script until I moved my db.database() out of my programs repeating execution loop.</p>
1
2013-02-23T22:34:39Z
[ "python", "postgresql", "psycopg2" ]
Lazy Method for Reading Big File in Python?
519,633
<p>I have a very big file 4GB and when I try to read it my computer hangs. So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.</p> <p>Is there any method to <code>yield</code> these pieces ?</p> <p>I would love to have a <strong>lazy method</strong>.</p>
156
2009-02-06T09:11:13Z
519,653
<p>To write a lazy function, just use <a href="http://docs.python.org/tutorial/classes.html#generators"><code>yield</code></a>:</p> <pre><code>def read_in_chunks(file_object, chunk_size=1024): """Lazy function (generator) to read a file piece by piece. Default chunk size: 1k.""" while True: data = file_object.read(chunk_size) if not data: break yield data f = open('really_big_file.dat') for piece in read_in_chunks(f): process_data(piece) </code></pre> <p><hr /></p> <p>Another option would be to use <a href="http://docs.python.org/library/functions.html#iter"><code>iter</code></a> and a helper function:</p> <pre><code>f = open('really_big_file.dat') def read1k(): return f.read(1024) for piece in iter(read1k, ''): process_data(piece) </code></pre> <p><hr /></p> <p>If the file is line-based, the file object is already a lazy generator of lines:</p> <pre><code>for line in open('really_big_file.dat'): process_data(line) </code></pre>
231
2009-02-06T09:20:08Z
[ "python", "file-io", "generator" ]
Lazy Method for Reading Big File in Python?
519,633
<p>I have a very big file 4GB and when I try to read it my computer hangs. So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.</p> <p>Is there any method to <code>yield</code> these pieces ?</p> <p>I would love to have a <strong>lazy method</strong>.</p>
156
2009-02-06T09:11:13Z
519,667
<p>Take a look at <a href="http://neopythonic.blogspot.com/2008/10/sorting-million-32-bit-integers-in-2mb.html">this post on Neopythonic</a>: "Sorting a million 32-bit integers in 2MB of RAM using Python"</p>
18
2009-02-06T09:28:12Z
[ "python", "file-io", "generator" ]
Lazy Method for Reading Big File in Python?
519,633
<p>I have a very big file 4GB and when I try to read it my computer hangs. So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.</p> <p>Is there any method to <code>yield</code> these pieces ?</p> <p>I would love to have a <strong>lazy method</strong>.</p>
156
2009-02-06T09:11:13Z
519,693
<p>You can use the <a href="http://docs.python.org/library/mmap.html">mmap module</a> to map the contents of the file into memory and access it with indices and slices. Here an example from the documentation:</p> <pre><code>import mmap with open("hello.txt", "r+") as f: # memory-map the file, size 0 means whole file map = mmap.mmap(f.fileno(), 0) # read content via standard file methods print map.readline() # prints "Hello Python!" # read content via slice notation print map[:5] # prints "Hello" # update content using slice notation; # note that new content must have same size map[6:] = " world!\n" # ... and read again using standard file methods map.seek(0) print map.readline() # prints "Hello world!" # close the map map.close() </code></pre>
20
2009-02-06T09:41:29Z
[ "python", "file-io", "generator" ]
Lazy Method for Reading Big File in Python?
519,633
<p>I have a very big file 4GB and when I try to read it my computer hangs. So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.</p> <p>Is there any method to <code>yield</code> these pieces ?</p> <p>I would love to have a <strong>lazy method</strong>.</p>
156
2009-02-06T09:11:13Z
519,770
<p>I'm in a somewhat similar situation. It's not clear whether you know chunk size in bytes; I usually don't, but the number of records (lines) that is required is known:</p> <pre><code>def get_line(): with open('4gb_file') as file: for i in file: yield i lines_required = 100 gen = get_line() chunk = [i for i, j in zip(gen, range(lines_required))] </code></pre> <p><strong>Update</strong>: Thanks nosklo. Here's what I meant. It almost works, except that it loses a line 'between' chunks.</p> <pre><code>chunk = [next(gen) for i in range(lines_required)] </code></pre> <p>Does the trick w/o losing any lines, but it doesn't look very nice.</p>
1
2009-02-06T10:12:47Z
[ "python", "file-io", "generator" ]
Lazy Method for Reading Big File in Python?
519,633
<p>I have a very big file 4GB and when I try to read it my computer hangs. So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.</p> <p>Is there any method to <code>yield</code> these pieces ?</p> <p>I would love to have a <strong>lazy method</strong>.</p>
156
2009-02-06T09:11:13Z
519,818
<p>i am not allowed to comment due to my low reputation, but SilentGhosts solution should be much easier with file.readlines([sizehint])</p> <p><a href="http://docs.python.org/library/stdtypes.html#file-objects" rel="nofollow">python file methods</a></p> <p>edit: SilentGhost is right, but this should be better than:</p> <pre><code>s = "" for i in xrange(100): s += file.next() </code></pre>
1
2009-02-06T10:37:22Z
[ "python", "file-io", "generator" ]
Lazy Method for Reading Big File in Python?
519,633
<p>I have a very big file 4GB and when I try to read it my computer hangs. So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.</p> <p>Is there any method to <code>yield</code> these pieces ?</p> <p>I would love to have a <strong>lazy method</strong>.</p>
156
2009-02-06T09:11:13Z
2,111,801
<p>file.readlines() takes in an optional size argument which approximates the number of lines read in the lines returned.</p> <pre><code>bigfile = open('bigfilename','r') tmp_lines = bigfile.readlines(BUF_SIZE) while tmp_lines: process([line for line in tmp_lines]) tmp_lines = bigfile.readlines(BUF_SIZE) </code></pre>
18
2010-01-21T18:27:59Z
[ "python", "file-io", "generator" ]
Lazy Method for Reading Big File in Python?
519,633
<p>I have a very big file 4GB and when I try to read it my computer hangs. So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.</p> <p>Is there any method to <code>yield</code> these pieces ?</p> <p>I would love to have a <strong>lazy method</strong>.</p>
156
2009-02-06T09:11:13Z
9,952,333
<pre><code>f = ... # file-like object, i.e. supporting read(size) function and # returning empty string '' when there is nothing to read def chunked(file, chunk_size): return iter(lambda: file.read(chunk_size), '') for data in chunked(f, 65536): # process the data </code></pre> <p>UPDATE: The approach is best explained in <a href="http://stackoverflow.com/a/4566523/38592">http://stackoverflow.com/a/4566523/38592</a></p>
6
2012-03-31T01:50:18Z
[ "python", "file-io", "generator" ]
Lazy Method for Reading Big File in Python?
519,633
<p>I have a very big file 4GB and when I try to read it my computer hangs. So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.</p> <p>Is there any method to <code>yield</code> these pieces ?</p> <p>I would love to have a <strong>lazy method</strong>.</p>
156
2009-02-06T09:11:13Z
10,405,648
<p>To process line by line, this is an elegant solution:</p> <pre><code> def stream_lines(file_name): file = open(file_name) while True: line = file.readline() if not line: file.close() break yield line </code></pre> <p>As long as there're no blank lines.</p>
0
2012-05-01T23:12:15Z
[ "python", "file-io", "generator" ]
Lazy Method for Reading Big File in Python?
519,633
<p>I have a very big file 4GB and when I try to read it my computer hangs. So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.</p> <p>Is there any method to <code>yield</code> these pieces ?</p> <p>I would love to have a <strong>lazy method</strong>.</p>
156
2009-02-06T09:11:13Z
19,802,839
<p>I think we can write like this:</p> <pre><code>def read_file(path, block_size=1024): with open(path, 'rb') as f: while True: piece = f.read(block_size) if piece: yield piece else: return for piece in read_file(path): process_piece(piece) </code></pre>
1
2013-11-06T02:15:10Z
[ "python", "file-io", "generator" ]
Lazy Method for Reading Big File in Python?
519,633
<p>I have a very big file 4GB and when I try to read it my computer hangs. So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.</p> <p>Is there any method to <code>yield</code> these pieces ?</p> <p>I would love to have a <strong>lazy method</strong>.</p>
156
2009-02-06T09:11:13Z
30,775,393
<p>There are already many good answers, but I ran into a similar issue recently and the solution I needed is not listed here, so I figured I could complement this thread.</p> <p>80% of the time, I need to read files line by line. Then, as suggested in this <a href="http://stackoverflow.com/a/519653/628786">answer</a>, you want to use the file object itself as lazy generator:</p> <pre><code>with open('big.csv') as f: for line in f: process(line) </code></pre> <p>However, I recently ran into a very very big (almost) single line csv, where the row separator was in fact not <code>'\n'</code> but <code>'|'</code>.</p> <ul> <li>Reading line by line was not an option, but I still needed to process it row by row.</li> <li>Converting<code>'|'</code> to <code>'\n'</code> before processing was also out of the question, because some of the fields of this csv contained <code>'\n'</code> (free text user input).</li> <li>Using the csv library was also ruled out because the fact that, at least in early versions of the lib, <a href="https://docs.python.org/2/library/csv.html#csv.Dialect.lineterminator" rel="nofollow">it is hardcoded to read the input line by line</a>.</li> </ul> <p>I came up with the following snippet, that I am sharing it here:</p> <pre><code>def rows(f, chunksize=1024, sep='|'): """ Read a file where the row separator is '|' lazily. Usage: &gt;&gt;&gt; with open('big.csv') as f: &gt;&gt;&gt; for r in rows(f): &gt;&gt;&gt; process(row) """ incomplete_row = None while True: chunk = f.read(chunksize) if not chunk: # End of file if incomplete_row is not None: yield incomplete_row break # Split the chunk as long as possible while True: i = chunk.find(sep) if i == -1: break # If there is an incomplete row waiting to be yielded, # prepend it and set it back to None if incomplete_row is not None: yield incomplete_row + chunk[:i] incomplete_row = None else: yield chunk[:i] chunk = chunk[i+1:] # If the chunk contained no separator, it needs to be appended to # the current incomplete row. if incomplete_row is not None: incomplete_row += chunk else: incomplete_row = chunk </code></pre> <p>I have tested it succesfully on large files and with different chunk sizes (I even tried a chunksize of 1 byte, just to make sure the algorithm is not size dependent).</p>
3
2015-06-11T08:23:16Z
[ "python", "file-io", "generator" ]
Lazy Method for Reading Big File in Python?
519,633
<p>I have a very big file 4GB and when I try to read it my computer hangs. So I want to read it piece by piece and after processing each piece store the processed piece into another file and read next piece.</p> <p>Is there any method to <code>yield</code> these pieces ?</p> <p>I would love to have a <strong>lazy method</strong>.</p>
156
2009-02-06T09:11:13Z
30,916,544
<p>you can use following code.</p> <pre><code>file_obj = open('big_file') </code></pre> <p>open() returns a file object</p> <p>then use os.stat for getting size</p> <pre><code>file_size = os.stat('big_file').st_size for i in range( file_size/1024): print file_obj.read(1024) </code></pre>
0
2015-06-18T13:20:52Z
[ "python", "file-io", "generator" ]
Is there a HAML implementation for use with Python and Django
519,671
<p>I happened to stumble across <a href="http://haml-lang.com/">HAML</a>, an interesting and beautiful way to mark up contents and write templates for HTML.</p> <p>Since I use Python and Django for my web developing need, I would like to see if there is a Python implementation of HAML (or some similar concepts -- need not be exactly identical) that can be used to replace the Django template engine.</p>
68
2009-02-06T09:30:01Z
519,679
<p>I'd check out <a href="https://github.com/derdon/ghrml">GHRML</a>, Haml for Genshi. The author admits that it's basically Haml for Python and that most of the syntax is the same (and that it works in Django). Here's some GHRML just to show you how close they are:</p> <pre><code>%html %head %title Hello World %style{'type': 'text/css'} body { font-family: sans-serif; } %script{'type': 'text/javascript', 'src': 'foo.js'} %body #header %h1 Hello World %ul.navigation %li[for item in navigation] %a{'href': item.href} $item.caption #contents Hello World! </code></pre>
21
2009-02-06T09:36:46Z
[ "python", "django", "django-templates", "haml" ]
Is there a HAML implementation for use with Python and Django
519,671
<p>I happened to stumble across <a href="http://haml-lang.com/">HAML</a>, an interesting and beautiful way to mark up contents and write templates for HTML.</p> <p>Since I use Python and Django for my web developing need, I would like to see if there is a Python implementation of HAML (or some similar concepts -- need not be exactly identical) that can be used to replace the Django template engine.</p>
68
2009-02-06T09:30:01Z
1,582,702
<p>This doesn't actually answer your question, but the CSS component of HAML, <a href="http://sass-lang.com/" rel="nofollow">SASS</a>, can be used freely with any framework. I'm using it right now with Django. </p>
4
2009-10-17T17:18:24Z
[ "python", "django", "django-templates", "haml" ]
Is there a HAML implementation for use with Python and Django
519,671
<p>I happened to stumble across <a href="http://haml-lang.com/">HAML</a>, an interesting and beautiful way to mark up contents and write templates for HTML.</p> <p>Since I use Python and Django for my web developing need, I would like to see if there is a Python implementation of HAML (or some similar concepts -- need not be exactly identical) that can be used to replace the Django template engine.</p>
68
2009-02-06T09:30:01Z
1,934,207
<p>You might be interested in SHPAML:</p> <p><a href="http://shpaml.com/">http://shpaml.com/</a></p> <p>I am actively maintaining it. It is a simple preprocessor, so it is not tied to any other tools like Genshi. I happen to use it with Django, so there is a little bit of Django support, but it should not interfere with most other use cases.</p>
35
2009-12-19T21:33:50Z
[ "python", "django", "django-templates", "haml" ]
Is there a HAML implementation for use with Python and Django
519,671
<p>I happened to stumble across <a href="http://haml-lang.com/">HAML</a>, an interesting and beautiful way to mark up contents and write templates for HTML.</p> <p>Since I use Python and Django for my web developing need, I would like to see if there is a Python implementation of HAML (or some similar concepts -- need not be exactly identical) that can be used to replace the Django template engine.</p>
68
2009-02-06T09:30:01Z
2,765,628
<p>I'm not sure what the status is of the GHRML bit as I only recently was looking into it. Can't find a repo for it, original developer doesn't have time for it anymore and maintenance was picked up by someone else with an interest in the project. Any extra info on this would be helpful.</p> <p>Unfortunately, as these things go, I started writing my own HAML style processor ;)</p> <p><a href="http://dasacc22.wordpress.com/2010/05/03/python-implementation-of-haml/" rel="nofollow">http://dasacc22.wordpress.com/2010/05/03/python-implementation-of-haml/</a></p> <p>It's in no way fit for production use at the moment (its literally a 4 day old infant now but like 60+hours crammed in those 4 days) but anyone interested may check it out here. It has a range of features already implemented that make it useful as a toy, and as I clean up the codebase over the next week, I hope to see it replace all my custom XSLT/xpath extensions and templates I have.</p>
3
2010-05-04T13:22:42Z
[ "python", "django", "django-templates", "haml" ]
Is there a HAML implementation for use with Python and Django
519,671
<p>I happened to stumble across <a href="http://haml-lang.com/">HAML</a>, an interesting and beautiful way to mark up contents and write templates for HTML.</p> <p>Since I use Python and Django for my web developing need, I would like to see if there is a Python implementation of HAML (or some similar concepts -- need not be exactly identical) that can be used to replace the Django template engine.</p>
68
2009-02-06T09:30:01Z
3,324,983
<p>i'm looking for the same. I haven't tried it, but found this:</p> <p><a href="http://github.com/jessemiller/HamlPy">http://github.com/jessemiller/HamlPy</a></p>
18
2010-07-24T11:56:45Z
[ "python", "django", "django-templates", "haml" ]