我正在使用子进程模块启动子进程并连接到它的输出流(stdout).我希望能够在其标准输出上执行非阻塞读取.有没有办法让.readline非阻塞或在我调用之前检查流上是否有数据.readline?我希望这是可移植的,或至少在Windows和Linux下工作.
这是我现在如何做到的(.readline如果没有数据可用,则阻止它):
p = subprocess.Popen('myprogram.exe', stdout = subprocess.PIPE)
output_str = p.stdout.readline()
Run Code Online (Sandbox Code Playgroud) 我正在使用python的subprocess模块来启动一个新进程.我想实时捕获新进程的输出,以便我可以用它做事(显示它,解析它等).我已经看到很多关于如何做到这一点的例子,一些使用自定义文件类对象,一些使用threading,一些尝试读取输出直到进程完成.
stdin,stdout和stderr.stdout和stderr值.读取输出示例(见下文)
对我来说最有意义的例子是阅读stdout,stderr直到过程结束.这是一些示例代码:
import subprocess
# Start a process which prints the options to the python program.
process = subprocess.Popen(
["python", "-h"],
bufsize=1,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
# While the process is running, display the output to the user.
while True:
# Read standard output data.
for stdout_line in iter(process.stdout.readline, ""):
# Display standard output data.
sys.stdout.write(stdout_line)
# …Run Code Online (Sandbox Code Playgroud) 有这个代码
Run Code Online (Sandbox Code Playgroud)p = subprocess.Popen('tail -f /var/log/syslog', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) for line in p.stdout.readlines(): print line, time.sleep(1)
即使我向syslog添加内容,脚本也会挂起并且不会写任何行.
为什么?