gpt4 book ai didi

python - sys.stdin.read() 在 python 中到底返回什么?

转载 作者:太空宇宙 更新时间:2023-11-03 15:10:26 25 4
gpt4 key购买 nike

我是 python 新手,正在研究交互式 shell。我正在尝试 python 标准库,我从文档中读到 stdin.read()返回一个字符串参数。但是,当我继续打印存储输入值的变量时,它会显示一个随机字符。对其含义感到困惑

>>>input=sys.stdin.read()
>>>1 2
>>>sys.stdout.write(input)
>>>1 2
4

4代表什么。为什么会显示。如果我这样做print(input) 。它工作正常并返回 "1 2" .它只是一个垃圾值还是有一些意义。

进一步,当我拆分输入以获得列表时。它仅返回两个元素 ['1', '2'] 。正如预期的那样。我很好奇为什么显示4并且它不是恒定的。

>>>input=sys.stdin.read()
>>>1 2 3 4
>>>sys.stdout.write(input)
>>>1 2 3 4
8

再次打印和拆分效果很好。

最佳答案

48sys.stdout.write 返回。它“表示”已打印了多少个字符(或字节)。

喜欢documentation on sys.stdin and sys.stdout状态:

These streams are regular text files like those returned by the open() function.

这些流有 write方法:

Write the given bytes-like object, b, to the underlying raw stream, and return the number of bytes written.

您可以简单地忽略它,或者如果它确实困扰您,只需在变量中捕获返回:

>>> bytes_written = sys.stdout.write(input)
1 2

>>> bytes_written
4

关于python - sys.stdin.read() 在 python 中到底返回什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44247011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com