[英]python: nonblocking subprocess, check stdout
Ok so the problem I'm trying to solve is this: 好的,我试图解决的问题是:
I need to run a program with some flags set, check on its progress and report back to a server. 我需要运行一个设置了一些标志的程序,检查它的进度并向服务器报告。 So I need my script to avoid blocking while the program executes, but I also need to be able to read the output. 所以我需要我的脚本以避免程序执行时阻塞,但我还需要能够读取输出。 Unfortunately, I don't think any of the methods available from Popen will read the output without blocking. 不幸的是,我不认为Popen提供的任何方法都会在没有阻塞的情况下读取输出。 I tried the following, which is a bit hack-y (are we allowed to read and write to the same file from two different objects?) 我尝试了以下,这有点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)
Unfortunately, Popen doesn't seem to write to my file until after the command terminates. 不幸的是,在命令终止之前,Popen似乎没有写入我的文件。
Does anyone know of a way to do this? 有谁知道这样做的方法? I'm not dedicated to using python, but I do need to send POST requests to a server in the same script, so python seemed like an easier choice than, say, shell scripting. 我并不致力于使用python,但我确实需要在相同的脚本中将POST请求发送到服务器,因此python似乎比shell脚本更容易。
Thanks! 谢谢! Will 将
Basically you have 3 options: 基本上你有3个选择:
threading
to read in another thread without blocking the main thread. 使用threading
读取另一个线程而不阻塞主线程。 select
on stdout, stderr instead of communicate
. select
stdout,stderr而不是communicate
。 This way you can read just when data is available and avoid blocking. 这样,您可以在数据可用时读取并避免阻塞。 twisted
is a obvious choice . 让图书馆解决这个问题, twisted
是一个明显的选择 。 You can use twisted library for this use case. 您可以将扭曲的库用于此用例。 I think it will be great for that 我认为这会很棒
http://www.cs.lth.se/EDA046/assignments/assignment4/twisted/listings/process/quotes.py http://www.cs.lth.se/EDA046/assignments/assignment4/twisted/listings/process/quotes.py
documentation : http://www.cs.lth.se/EDA046/assignments/assignment4/twisted/process.html 文档: http : //www.cs.lth.se/EDA046/assignments/assignment4/twisted/process.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.