相关疑难解决方法(0)

逐行读取子进程标准输出

我的python脚本使用subprocess来调用非常嘈杂的linux实用程序.我想将所有输出存储到日志文件中并向用户显示一些输出.我认为以下内容可行,但在实用程序产生大量输出之前,输出不会显示在我的应用程序中.

#fake_utility.py, just generates lots of output over time
import time
i = 0
while True:
   print hex(i)*512
   i += 1
   time.sleep(0.5)

#filters output
import subprocess
proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)
for line in proc.stdout:
   #the real code does filtering here
   print "test:", line.rstrip()
Run Code Online (Sandbox Code Playgroud)

我真正想要的行为是过滤器脚本在从子进程接收时打印每一行.Sorta就像tee使用python代码一样.

我错过了什么?这甚至可能吗?


更新:

如果将a sys.stdout.flush()添加到fake_utility.py,则代码在python 3.1中具有所需的行为.我正在使用python 2.6.您会认为使用proc.stdout.xreadlines()将与py3k一样工作,但事实并非如此.


更新2:

这是最小的工作代码.

#fake_utility.py, just generates lots of output over time
import sys, time
for i in range(10):
   print i
   sys.stdout.flush()
   time.sleep(0.5)

#display out put line by …
Run Code Online (Sandbox Code Playgroud)

python subprocess

216
推荐指数
8
解决办法
32万
查看次数

有没有办法将'stdin'作为参数传递给python中的另一个进程?

我正在尝试创建一个使用python的多处理模块的脚本.脚本(让我们称之为myscript.py)将从另一个带有管道的脚本获取输入.

假设我像这样调用脚本;

$ python writer.py | python myscript.py 
Run Code Online (Sandbox Code Playgroud)

这是代码;

// writer.py
import time, sys

def main():
    while True:
        print "test"
        sys.stdout.flush()
        time.sleep(1)

main()

//myscript.py
def get_input():
    while True:
        text = sys.stdin.readline()
        print "hello " + text
        time.sleep(3)

if __name__ == '__main__':        
    p1 = Process(target=get_input, args=())
    p1.start()
Run Code Online (Sandbox Code Playgroud)

这显然不起作用,因为sys.stdin对象对于主进程和p1是不同的.所以我试过这个解决它,

//myscript.py
def get_input(temp):
    while True:
        text = temp.readline()
        print "hello " + text
        time.sleep(3)

if __name__ == '__main__':        
    p1 = Process(target=get_input, args=(sys.stdin,))
    p1.start()
Run Code Online (Sandbox Code Playgroud)

但我遇到了这个错误;

Process Process-1:
Traceback (most recent call last):
  File "/usr/lib/python2.7/multiprocessing/process.py", …
Run Code Online (Sandbox Code Playgroud)

python stdin multiprocessing

16
推荐指数
1
解决办法
7190
查看次数

标签 统计

python ×2

multiprocessing ×1

stdin ×1

subprocess ×1