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

点点圈 提交于 2020-01-03 09:30:10

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/37047368/why-does-writing-to-stdout-in-console-append-the-number-of-characters-written-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!