【问题标题】:Pipe infinite output from shell command to a python script将 shell 命令的无限输出通过管道传输到 python 脚本
【发布时间】:2019-05-08 09:14:31
【问题描述】:

我想将一个脚本的输出转发到另一个。

我尝试这样做:

./producer.py > ./consumer.py

生产者在哪里:

#!/usr/bin/env python3

import sys
import time

i=0
while True:
    print(i)
    i+=1
    time.sleep(1)

和消费者:

#!/usr/bin/env python3

import sys

f= open("test.txt","w+")

while True:
    line = sys.stdin.read()
    print(line)
    f.write(line)

我希望生产者会生成:1 2 3 4 5,并且此管道将由另一个脚本保存在文件 test.txt 中。谢谢你的帮助。

【问题讨论】:

    标签: python linux python-3.x unix pipe


    【解决方案1】:

    使用管道| 而不是> 将输出(stdout)从一个进程转发到另一个进程(作为标准输入)。另外,请注意管道上的数据是缓冲的,当没有很多数据并且流永远不会关闭时,这似乎什么都没有发生。

    【讨论】:

      【解决方案2】:

      考虑改用具有两个线程的队列。 Here 是一个很好的基本指南。 Here 是另一个指南。

      【讨论】:

        【解决方案3】:

        尝试使用 subprocess,然后将输出管道中的数据保存到文件中。不需要在外面执行命令。

        from subprocess import PIPE,Popen
        
        process = Popen(['python','test.py'],stderr=PIPE,stdout=PIPE)
        
        output = process.stdout.readlines()
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-01-15
          • 2018-08-18
          • 2018-05-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多