python:nonblocking subprocess,检查stdout

Wil*_*agh 4 python subprocess stdout popen nonblocking

好的,我试图解决的问题是:

我需要运行一个设置了一些标志的程序,检查它的进度并向服务器报告.所以我需要我的脚本以避免程序执行时阻塞,但我还需要能够读取输出.不幸的是,我不认为Popen提供的任何方法都会在没有阻塞的情况下读取输出.我尝试了以下,这有点hack-y(我们是否允许从两个不同的对象读取和写入相同的文件?)

import time
import subprocess
from subprocess import *
with open("stdout.txt", "wb") as outf:
    with open("stderr.txt", "wb") as errf:
        command = ['Path\\To\\Program.exe', 'para', 'met', 'ers']
        p = subprocess.Popen(command, stdout=outf, stderr=errf)
        isdone = False
        while not isdone :
            with open("stdout.txt", "rb") as readoutf: #this feels wrong
                for line in readoutf:
                    print(line)
            print("waiting...\\r\\n")
            if(p.poll() != None) :
                done = True
            time.sleep(1)
        output = p.communicate()[0]    
        print(output)
Run Code Online (Sandbox Code Playgroud)

不幸的是,在命令终止之前,Popen似乎没有写入我的文件.

有谁知道这样做的方法?我并不致力于使用python,但我确实需要在相同的脚本中将POST请求发送到服务器,因此python似乎比shell脚本更容易.

谢谢!将

Joc*_*zel 8

基本上你有3个选择:

  1. 使用threading读取另一个线程不会阻塞主线程.
  2. select在stdout,stderr而不是communicate.这样,您可以在数据可用时读取并避免阻塞.
  3. 让图书馆解决这个问题,twisted是一个显而易见的选择.