为什么在控制台中写入标准输出会附加在 Python 3 中写入的字符数? [英] Why does writing to stdout in console append the number of characters written, in Python 3?

查看:25
本文介绍了为什么在控制台中写入标准输出会附加在 Python 3 中写入的字符数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在 Python 控制台中玩弄 sys.stdout.write() 时,我注意到这给出了一些奇怪的输出.

I was just playing around with sys.stdout.write() in a Python console when I noticed that this gives some strange output.

对于每个 write() 调用写入的字符数,分别传递给函数会附加到控制台的输出中.

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')例如导致foo bar7 正在打印出来.

>>> sys.stdout.write('foo bar') for example results in foo bar7 being printed out.

即使传递一个空字符串也会导致 0 的输出.

Even passing an empty string results in an output of 0.

这实际上只发生在 Python 控制台中,但不会在执行具有相同语句的文件时发生.更有趣的是,它只适用于 Python 3,不适用于 Python 2.

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.

我的 Python 版本是 3.5.1,在 Ubuntu 15.10 下.

My Python version is 3.5.1 under Ubuntu 15.10.

推荐答案

除了写出给定的字符串,write 还会返回字符数(实际上是字节数,试试sys.stdout.write('へllö')) 当python控制台将每个表达式的返回值打印到stdout时,返回值会附加到实际打印的值上.

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.

因为 write 没有附加任何换行符,所以它看起来像同一个字符串.

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.

这篇关于为什么在控制台中写入标准输出会附加在 Python 3 中写入的字符数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆