为什么 sys.stdout.write 会输出意外的字符?

Why is sys.stdout.write outputs unexpected characters?

from sys import stdin, stdout
temp=1
stdout.write(str(temp))

我希望输出为 1 但它是 11 。为什么?

>>> import sys
>>> help(sys.stdout.write)

Help on built-in function write:

write(text, /) method of _io.TextIOWrapper instance
    Write string to stream.
    Returns the number of characters written (which is always equal to
    the length of the string)

第一个 "1" 是您给 write 的参数,第二个 "1" 是由 write 编辑的 return 字符串的长度。

>>> sys.stdout.write("Hello")
Hello5

请注意,return 值出现在输出中,因为这是一个交互式会话。如果您 运行 来自 .py 文件的此代码,您将只能看到 "Hello",如您所料。