当进程正在运行时,异步读取控制台输出与python

时间:2014-04-04 10:04:04

标签: python process console

我想通过python运行一个漫长的过程(calculix模拟)。

如上所述here,可以使用communicate()读取控制台字符串。

据我所知,该过程完成后会返回字符串?在进程运行时是否有可能获得控制台输出?

2 个答案:

答案 0 :(得分:2)

您必须使用subprocess.Popen.poll检查流程终止。

while sub_process.poll() is None:
    output_line = sub_process.stdout.readline()

这将为您提供运行时输出。

答案 1 :(得分:1)

这应该有效:

sp = subprocess.Popen([your args], stdout=subprocess.PIPE)
while sp.poll() is None: # sp.poll() returns None while subprocess is running
  output = sp.stdout # here you have acccess to the stdout while the process is running
  # Do stuff with stdout

注意我们不在这里调用子进程上的communic()。