Strange output when writing to stdout in console

I just played with sys.stdout.write() in the Python console when I noticed that this was giving some weird result.

For each call to write() number of written characters passed to the function is appended accordingly to the output.

>>> sys.stdout.write('foo bar') e.g. foo bar7 .

Even passing an empty string leads to output 0 .

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

Although this is not a problem for me, since it only happens in the console, I really wonder why it behaves this way.

My version of Python is 3.5.1 under Ubuntu 15.10.

+6
source share
1 answer

In addition to writing this line, write will also return the number of characters (in fact, bytes, try sys.stdout.write('へllâ') ). Since the python console prints the return value of each expression to stdout, the return value is added to the actual printed value.

Since write does not add new lines, it looks like the same line.

You can check 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 executing the output:

 Greetings, human! return value: <18> 

This behavior is mentioned in the docs here .

+8
source

All Articles