Why does writing to stdout in console append the number of characters written, in Python 3?
Asked Answered
R

1

11

I was just playing around with sys.stdout.write() in a Python console when I noticed that this gives some strange output.

For every write() call the number of characters written, passed to the function respectively gets append to the output in console.

>>> sys.stdout.write('foo bar') for example results in foo bar7 being printed out.

Even passing an empty string results in an output of 0.

This really only happens in a Python console, but not when executing a file with the same statements. More interestingly it only happens for Python 3, but not for Python 2.

Although this isn't really an issue for me as it only occurs in a console, I really wonder why it behaves like this.

My Python version is 3.5.1 under Ubuntu 15.10.

Razorbill answered 5/5, 2016 at 9:46 Comment(0)
M
11

Apart from writing out the given string, write will also return the number of characters (actually, bytes, try sys.stdout.write('へllö')) As the python console prints the return value of each expression to stdout, the return value is appended to the actual printed value.

Because write doesn't append any newlines, it looks like the same string.

You can verify this with a script containing this:

#!/usr/bin/python
import sys

ret = sys.stdout.write("Greetings, human!\n")
print("return value: <{}>".format(ret))

This script should when executed output:

Greetings, human!
return value: <18>

This behaviour is mentioned in the docs here.

Mumford answered 5/5, 2016 at 9:51 Comment(4)
Interesting. So a = sys.stdout.write('foo') should reveal this behavior what it actually also does. a is set to 3 in this case, and number isn't append to the output anymore. But I still wonder why this only happens in Python 3. Afaik I also can't find any mention in the doc for this.Razorbill
I've appended a script that shows the result, to make things more clear. I didn't really read the docs for this, I just assumed it because it happens in quite a lot of languages and tested it. I'll search for a PEP mentioning this and get back here if I do.Mumford
Just to add, it counts Unicode characters sys.stdout.write('へllö') returns "へllö4"Deonnadeonne
@critop It's because IO was given an overhaul from 2 to 3. The type of stdout was a file, which declares write as having no return value. The new type is TextIOWrapper, of which one of it's bases (TextIOBase) declares write to return the number of characters written.Bullfighter

© 2022 - 2024 — McMap. All rights reserved.