【问题标题】:Python3 : Using input() how to Read Multiple Lines from pipe (stdin)?Python3:使用 input() 如何从管道 (stdin) 中读取多行?
【发布时间】: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


    【解决方案1】:

    您可以像任何其他可迭代对象一样迭代 stdin 中的行:

    for line in sys.stdin:
        # do something
    

    如果要将整个内容读入一个字符串,请使用:

    s = sys.stdin.read()
    

    请注意,遍历 s 会一次返回一个字符。

    注意it won't read until there is an EOF terminating stdin.

    【讨论】:

    • 谢谢。但这不是我问题的答案。它或多或少是我已经在那里所做的。 - 我想知道,有没有一种方法可以使用普通的旧“input()”来实现几乎相同的效果而不会阻塞程序并从管道中读取不止一行。
    【解决方案2】:

    如果你只想使用 input() 来访问标准输入的行:

    print(input()) #prints line 1
    print(input()) #prints next line
    

    但假设您只想访问第二行:

    input() #accesses the first line
    print(input()) #prints second line
    

    假设您想使用第二行并创建一个数组: 标准输入:

    10

    64630 11735 14216 99233 14470 4978 73429 38120 51135 67060

    input()
    values = list(map(int, input().split(' ')))
    

    值将等于 [64630, 11735, 14216, 99233, 14470, 4978, 73429, 38120, 51135, 67060]

    【讨论】: