Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 242
critop Avatar asked May 05 '16 09:05

critop


People also ask

Does python print write to stdout?

Every running program has a text output area called "standard out", or sometimes just "stdout". The Python print() function takes in python data such as ints and strings, and prints those values to standard out.

What is stdout in python?

A built-in file object that is analogous to the interpreter's standard output stream in Python. stdout is used to display output directly to the screen console. Output can be of any form, it can be output from a print statement, an expression statement, and even a prompt direct for input.


1 Answers

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.

like image 159
Noctua Avatar answered Oct 02 '22 17:10

Noctua