【问题标题】:Async read console output with python while process is running进程运行时使用python异步读取控制台输出
【发布时间】:2014-04-04 10:04:03
【问题描述】:

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

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

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

【问题讨论】:

  • 你的进程calculix模拟运行时在控制台写入数据?
  • 是的,确保它写入控制台

标签: python process console


【解决方案1】:

您必须使用subprocess.Popen.poll 来检查进程是否终止。

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

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

【讨论】:

    【解决方案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()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-21
      • 2013-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多