简体   繁体   English

sys.stdin 什么时候等待输入?

[英]When does sys.stdin await input?

What are the rules that determine whether sys.stdin awaits user input or not?确定sys.stdin是否等待用户输入的规则是什么? For example:例如:

>>> sys.stdin
# <_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>
>>> "".join(sys.stdin)
# <awaiting input...>

The second line awaits input even though I'm not "calling" sys.stdin or anything, so how does python know and what are the rules for when it waits?第二行等待输入,即使我没有“调用” sys.stdin或任何东西,那么 python 如何知道以及等待时的规则是什么?

Finally, is it possible to enter in sys.stdin without a trailing \\n ?最后,是否可以在没有尾随\\n情况下进入sys.stdin For example:例如:

>>> "".join(sys.stdin)
hello
'hello\n'

To exit I have to do Return ctrl-d .要退出,我必须执行Return ctrl-d Can I get the input without the \\n or so I just need to always do a rstrip() at the end or something similar?我可以在没有\\n情况下获得输入吗?所以我只需要在最后执行rstrip()或类似的操作吗?

The second use case is using the fact that file objects are iterators;第二个用例是使用文件对象是迭代器这一事实; it's implicitly calling sys.stdin 's __next__ method over and over until it raises StopIteration .它隐含调用sys.stdin__next__以上方法又一遍,直到它引发StopIteration Since it runs to completion, not just a single line, it won't return until sys.stdin is closed (typically by the other side).由于它运行到完成,而不仅仅是一行,因此在sys.stdin关闭(通常是另一端)之前它不会返回。 So the answer is what you thought, you just didn't realize that invoking the iterator protocol counts as a form of "calling".所以答案就是你的想法,只是你没有意识到调用迭代器协议算作一种“调用”形式。

If you just want a single line of input, without the newline at the end, just use the input function (that implicitly pulls the result from sys.stdin , but only a single line, it doesn't wait until it's closed).如果你只想要一行输入,最后没有换行符,只需使用input函数(从sys.stdin隐式提取结果,但只有一行,它不会等到它关闭)。 Otherwise, you're stuck stripping the newlines manually.否则,您将无法手动剥离换行符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM