sys.stdout and Python3

Chris Angelico rosuav at gmail.com
Sat Nov 23 09:16:18 EST 2013


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.

ChrisA



More information about the Python-list mailing list