9

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.

smci
  • 26,085
  • 16
  • 96
  • 138
critop
  • 403
  • 2
  • 11

1 Answers1

9

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.

Noctua
  • 4,616
  • 1
  • 14
  • 21
  • 1
    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. – critop May 05 '16 at 09:56
  • 1
    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. – Noctua May 05 '16 at 09:58
  • 3
    Just to add, it counts Unicode characters `sys.stdout.write('へllö')` returns "へllö4" – C14L May 05 '16 at 10:01
  • 4
    @critop It's because IO was given an overhaul from 2 to 3. The type of `stdout` was a `file`, which declares [write](https://docs.python.org/2/library/stdtypes.html#file.write) as having no return value. The new type is `TextIOWrapper`, of which one of it's bases (`TextIOBase`) declares [write](https://docs.python.org/3/library/io.html#io.TextIOBase.write) to return the number of characters written. – Dunes May 05 '16 at 10:17