sys.stdout and Python3

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Nov 24 15:31:48 CET 2013


On Sun, 24 Nov 2013 01:16:18 +1100, Chris Angelico wrote:

> On Sun, Nov 24, 2013 at 12:26 AM, Frank Millman <frank at chagford.com>
> wrote:
>> for i in range(10):
>>   sys.stdout.write('.')
>>   sys.stdout.flush()
>>   time.sleep(1)
>> sys.stdout.write('\n')
>>
>> I tried it under Python3, and found that it differs in two ways -
>>
>> 1. Each 'write' is terminated by a newline 2. Each 'write' appends the
>> length of the string written.
> 
> Only in the interactive interpreter, where return values get printed. In
> a script, that won't happen. To prevent that from happening
> interactively, just assign the result to something:
> 
> for i in range(10):
>     _=sys.stdout.write(".")
>     sys.stdout.flush()
> 
> There definitely is a difference between Py2 and Py3 there, but it's
> nothing to do with sys.stdout - it's a change in the REPL (interactive
> interpreter, Read/Eval/Print Loop) and how it handles return values
> inside loops. I think it's an improvement, overall, though it is a
> little confusing when you work with partial output.


I don't think the REPL handles return values inside loops any different 
from how it handles them outside loops. The difference is that file.write 
methods used to return None in Python 2, in Python 3 they return the 
number of bytes written.


-- 
Steven



More information about the Python-list mailing list