Python 3 解释器将每次写入的长度打印到标准输入

1 python anaconda

关于这种行为有几个问题:

>>> import sys
>>> sys.stdout.write("aaaa")
aaaa4
>>>
Run Code Online (Sandbox Code Playgroud)

我明白那里发生了什么。我不明白的是在我的情况下发生了什么:无论我打开哪个文件,每当我使用它的.write方法时,数据的长度都会写入到 console/to stdout

>>> with open("garbage.file", "wb") as f:
...     for x in range(4):
...         f.write(b"xyz")
...
3
3
3
3
>>> with open("garbage.file", "rb") as f:
...     assert f.read() == b"xyzxyzxyzxyz"
...
>>>
Run Code Online (Sandbox Code Playgroud)

但是,当我让它作为脚本运行时,不会发生这种行为python

D:\>type CON > test.py
with open("garbage.file", "wb") as f:
    f.write(b"xyz")

^Z

D:\>python test.py

D:\>type garbage.file
xyz
D:\>
Run Code Online (Sandbox Code Playgroud)

在 Windows 命令提示符(“普通”cmd或“Anaconda 提示符”)上使用的任何新的 Python 3.5 解释器都会发生这种情况。

>>> import sys
>>> sys.version
'3.5.2 |Anaconda 4.1.1 (64-bit)| (default, Jul  5 2016, 11:41:13) [MSC v.1900 64 bit (AMD64)]'
>>>
Run Code Online (Sandbox Code Playgroud)

我以前从未见过这种行为,而且看起来也不应该发生。可能是什么原因?我该如何解决?

小智 5

这似乎是这个问题的重复:python3 中的 sys.stdout.write 在字符串末尾添加 11

这解释了.write()返回写入文件后写入的字符数。这解释了为什么您在解释器中看到它而不是您创建的文件。

编辑:显示解释器的示例显示返回值,而 python 可执行文件忽略它们。

>>> def show(string):
...     print(string)
...     return(len(string))
... 
>>> show('foobar')
foobar
6
Run Code Online (Sandbox Code Playgroud)

现在,如果我创建一个内容完全相同的文件,我会得到:

$ python show.py 
foobar
Run Code Online (Sandbox Code Playgroud)

这是因为python可执行文件不显示返回值,而解释器显示。

  • @Rhymoid 交互式解释器打印未赋值表达式的值,除非它的计算结果为“无”。 (4认同)