python - Windows CMD 用python的sys.stdout在打印行的末尾添加一个随机数

标签 python cmd stdout python-3.7

我在 Windows 10 64 位操作系统的控制台中编写了一个简单的 sys.stdout.write 语句。

Microsoft Windows [Version 10.0.17134.590]
(c) 2018 Microsoft Corporation. All rights reserved.

C:\Users\user>python
Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 23:09:28) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.stdout.write('x')
x1
>>> sys.stdout.write('try')
try3
>>> sys.stdout.write('fooo')
fooo4

安装的Python版本是3.7.2

最佳答案

数字不是随机的;它是写入的字符数。因为您处于 Python 交互中,所以也会打印语句的返回值。 sys.stdout.write(或一般写入文件)返回写入的字符数。

因此,当您执行类似sys.stdout.write('fooo') 的操作时,它首先打印fooo,然后返回值(4) 被打印出来。

sys.stdout.write 可以这样模拟:

def mywrite(s):
    print(s, end='')
    return len(s)

在互动中:

>>> def mywrite(s):
...     print(s, end='')
...     return len(s)
...
>>> mywrite('x')
x1
>>> mywrite('try')
try3
>>> mywrite('fooo')
fooo4

关于python - Windows CMD 用python的sys.stdout在打印行的末尾添加一个随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55096646/

相关文章:

python - 如何在需要时启用滚动功能?

powershell - 如何在几分钟内掌握流程的开始时间?

java - 转义参数中的非法字符

r - 以位图格式(例如 PNG)将绘图写入标准输出

python - 谁能给我一个关于 Python 3 中标准输入和标准输出的快速教程?

python - 如何创建 Pandas 数据框的字典,并将数据框返回到 excel 工作表中?

python - pySVG CSS 链接

python - python cv2 中 VideoCapture 的多个实例的问题

batch-file - 到 "Call"或 "Not to Call"一个批处理文件?

perl - 从 perl 中的外部 *nix 命令获取 STDOUT、STDERR 和响应代码