在进程运行时使用Python异步读取控制台输出

4 投票
2 回答
1360 浏览
提问于 2025-04-18 01:19

我想通过Python来运行一个比较长的过程(calculix模拟)。

正如这里提到的,可以使用communicate()来读取控制台的输出。

我理解的是,这个字符串是在过程完成后才返回的?有没有办法在过程运行时就获取控制台的输出呢?

2 个回答

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

注意,我们在这里没有对子进程调用 communicate() 方法。

2

你需要使用 subprocess.Popen.poll 来检查一个进程是否已经结束。

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

这样做会让你看到运行时的输出。

撰写回答