【发布时间】:2023-09-14 04:47:01
【问题描述】:
我只是在学习 python3 时很好奇,并没有在网上找到任何好的解释,我的问题也没有。
阅读 input() 它说“从标准输入读取”,所以我想我可能会尝试并尝试使用它从管道中读取。确实如此!但只有一条线(直到 EOL)。所以接下来出现的问题是
如何使用 input() 从管道 (stdin) 中读取多行?
我找到了 sys.stdin 并使用 sys.stdin.isatty() 来确定 stdin 是否绑定到 tty,假设如果未绑定到 tty,则数据来自管道。所以我也成功地找到并使用了 sys.stdin.readlines() 来读取多行。
但出于我的好奇心,有没有办法通过使用普通的 input() 函数来实现相同的目的?到目前为止,如果标准输入包含更多行而不阻塞我的程序,我还没有找到“测试”的东西。
对不起,如果这一切对你来说没有意义。
这是我目前没有输入()的实验代码:
import sys
if sys.stdin.isatty(): # is this a keyboard?
print( "\n\nSorry! i only take input from pipe. "
"not from a keyboard or tty!\n"
"for example:\n$ echo 'hello world' | python3 stdin.py"
""
""
)
else:
print ( "reading from stdin via pipe : \n ")
for line in sys.stdin.readlines():
print(line, end="")
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ can these two lines be replaced with
# some construction using plain old input() ?
【问题讨论】:
标签: python-3.x input pipe stdin