Python 3解释器会在每次写入时将长度输出到标准输入 [英] Python 3 interpreter prints length to standard input for every write
问题描述
关于这种行为有一些问题:
There are a few questions about this kind of behaviour:
>>> import sys
>>> sys.stdout.write("aaaa")
aaaa4
>>>
我知道那里发生了什么.我不知道发生了什么事:无论我打开哪个文件,只要我使用其.write
方法,数据的长度就会写入控制台/到stdout
.
I understand what's going on there. What I don't understand is what's happening in my case: regardless of which file I open, whenever I use its .write
method, the length of the data is written to the 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"
...
>>>
但是,当我让python
作为脚本运行它时,不会发生这种行为 :
However, this behaviour does not occur when I let python
run it as a script:
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:\>
使用Windows命令提示符(正常" cmd
或"Anaconda提示")的任何新鲜的Python 3.5解释器都会发生这种情况.
This happens with any fresh Python 3.5 interpreter used on a Windows command prompt (either the "normal" cmd
or the "Anaconda Prompt").
>>> 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)]'
>>>
我以前从未见过这种行为,而且看起来也不该发生.可能是什么原因?我该如何解决?
I've never seen this behaviour before, and it doesn't look like it's supposed to happen either. What could be the cause? How can I resolve it?
推荐答案
This seems to be a duplicate of this question: sys.stdout.write in python3 adds 11 at end of string
这将解释.write()
返回将其写入文件后写入的字符数.这就解释了为什么您在解释器中看到它的原因,而不是在创建的文件中看到的原因.
Which explains that .write()
returns the number of characters written after it's been written to the file. Which explains why you see it in the interpreter but not the file you've created.
显示解释器的示例显示返回值,而python可执行文件忽略它们.
Examples showing the interpreter show return values and the python executable ignore them.
>>> def show(string):
... print(string)
... return(len(string))
...
>>> show('foobar')
foobar
6
现在,如果我创建的文件内容完全相同:
Now if I create a file with the exact same contents I get:
$ python show.py
foobar
这是因为python
可执行文件不显示返回值,而解释程序则显示.
This is because the python
executable doesn't show returned values whereas the interpreter does.
这篇关于Python 3解释器会在每次写入时将长度输出到标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!