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

2024-09-30 22:24:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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


Tags: 字符串here进程communicatecalculix
2条回答

这应该是有效的:

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()。在

您必须使用^{}来检查进程是否终止。在

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

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

相关问题 更多 >