mirror of
https://github.com/kennethreitz/dive-into-python3.git
synced 2026-06-05 23:10:17 +00:00
add var to catch return value of sys.stdout.write
This commit is contained in:
+4
-4
@@ -464,20 +464,20 @@ AttributeError: 'GzipFile' object has no attribute '__exit__'</samp></pre>
|
||||
|
||||
<pre class=screen>
|
||||
<samp class=p>>>> </samp><kbd class=pp>for i in range(3):</kbd>
|
||||
<a><samp class=p>... </samp><kbd class=pp> print('PapayaWhip')</kbd> <span class=u>①</span></a>
|
||||
<a><samp class=p>... </samp><kbd class=pp> print('PapayaWhip')</kbd> <span class=u>①</span></a>
|
||||
<samp>PapayaWhip
|
||||
PapayaWhip
|
||||
PapayaWhip</samp>
|
||||
<samp class=p>>>> </samp><kbd class=pp>import sys</kbd>
|
||||
<samp class=p>>>> </samp><kbd class=pp>for i in range(3):</kbd>
|
||||
<a><samp class=p>... </samp><kbd class=pp> sys.stdout.write('is the')</kbd> <span class=u>②</span></a>
|
||||
<a><samp class=p>... </samp><kbd class=pp> l = sys.stdout.write('is the')</kbd> <span class=u>②</span></a>
|
||||
<samp>is theis theis the</samp>
|
||||
<samp class=p>>>> </samp><kbd class=pp>for i in range(3):</kbd>
|
||||
<a><samp class=p>... </samp><kbd class=pp> sys.stderr.write('new black')</kbd> <span class=u>③</span></a>
|
||||
<a><samp class=p>... </samp><kbd class=pp> l = sys.stderr.write('new black')</kbd> <span class=u>③</span></a>
|
||||
<samp>new blacknew blacknew black</samp></pre>
|
||||
<ol>
|
||||
<li>The <code>print()</code> function, in a loop. Nothing surprising here.
|
||||
<li><code>stdout</code> is defined in the <code>sys</code> module, and it is a <a href=#file-like-objects>stream object</a>. Calling its <code>write()</code> function will print out whatever string you give it. In fact, this is what the <code>print</code> function really does; it adds a carriage return to the end of the string you’re printing, and calls <code>sys.stdout.write</code>.
|
||||
<li><code>stdout</code> is defined in the <code>sys</code> module, and it is a <a href=#file-like-objects>stream object</a>. Calling its <code>write()</code> function will print out whatever string you give it, then return the length of the output. In fact, this is what the <code>print</code> function really does; it adds a carriage return to the end of the string you’re printing, and calls <code>sys.stdout.write</code>.
|
||||
<li>In the simplest case, <code>sys.stdout</code> and <code>sys.stderr</code> send their output to the same place: the Python <abbr>IDE</abbr> (if you’re in one), or the terminal (if you’re running Python from the command line). Like standard output, standard error does not add carriage returns for you. If you want carriage returns, you’ll need to write carriage return characters.
|
||||
</ol>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user