【问题标题】:In Python how do I read data from stdin until piped process terminates?在 Python 中,如何从标准输入读取数据,直到管道进程终止?
【发布时间】:2020-01-31 07:38:56
【问题描述】:

我想做这样的事情:

data = json.load(open(sys.argv[1]) if len(sys.argv) > 1 else sys.stdin)

在这个例子中可以简化为

data = json.load(sys.stdin)

但是 json.load 运行一个 .read() 可能不包含我通过提供的整个 JSON 字符串

generate_json_output | myprogram.py

是否有推荐的方法从stdin 读取直到generate_json_output 终止?我试图抓住BrokenPipeError,但我跑的时候它没有被提升

while True:
    data += sys.stdin.read()

【问题讨论】:

    标签: python-3.x pipe stdin


    【解决方案1】:

    除了while 循环,您可以使用下面的 for 循环来迭代标准输入。

    import sys
    
    data = ''
    for line in sys.stdin:
        data += line
    

    可以写成一个表达式:

    data = "".join(sys.stdin)
    

    使用管道生成的输入运行此程序会读取标准输入,直到它终止。

    t.json:

    {
        'a': 2,
        'b': 3
    }
    

    运行 cat t.json | python a.py 将完整的文件打印到标准输出。

    【讨论】:

    • 这和我希望的一样直截了当 :) 更短的版本:data = "".join(sys.stdin)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    相关资源
    最近更新 更多