Python 3 interpreter prints length to standard input for every write [duplicate]

余生长醉 提交于 2020-01-14 03:23:10

问题


There are a few questions about this kind of behaviour:

>>> import sys
>>> sys.stdout.write("aaaa")
aaaa4
>>>

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"
...
>>>

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:\>

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?


回答1:


This seems to be a duplicate of this question: sys.stdout.write in python3 adds 11 at end of string

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.

Edit: 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

This is because the python executable doesn't show returned values whereas the interpreter does.



来源:https://stackoverflow.com/questions/39592227/python-3-interpreter-prints-length-to-standard-input-for-every-write

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