【问题标题】:Writing the stdout of subprocess to a file using communicate使用通信将子进程的标准输出写入文件
【发布时间】:2014-10-13 22:45:23
【问题描述】:

我正在使用子进程来运行可执行文件并使用通信管道输出它的输出。最后,我将通信的内容写入文件。具体代码如下所示

run = subprocess.Popen(['executable'], stdout=subprocess.PIPE)
output = run.communicate()[0]
logfile = open('run.log', 'a')
logfile.write(output)
logfile.close()

在上述过程中,日志文件是在运行结束时写入的。但是,有没有办法在可执行文件运行时将输出写入日志?

【问题讨论】:

  • 这在the docs中直接解释:“stdin,stdoutstderr指定执行程序的标准输入、标准输出和标准错误文件句柄。有效值为PIPEDEVNULL、现有文件描述符(正整数)、现有文件对象和None。"

标签: python subprocess stdout communicate


【解决方案1】:

你的意思是这样的:

with open("run.log","a") as f:
      run = subprocess.Popen(['executable'], stdout=f)

【讨论】:

  • 使用 subprocess.check_call() 等待子进程完成(如问题中所示)。如果子进程返回非零退出状态,check_call() 也会自动引发异常。
  • 谢谢@padraic。虽然上述方法有效,但终端从可执行文件中解放出来。 subprocess 有没有办法将可执行文件保留在终端中,直到运行结束?
  • @Deepak:按照我的建议,将Popen 替换为check_call。参数是一样的。
  • Popen 在启动进程后返回时,它会不会离开导致f 被保留为关闭文件的with 块?
【解决方案2】:

我想我找到了解决办法:

logfile = ('run.log', 'w')
run = subprocess.Popen(['executable'], stdout = logfile)
run.wait()
logfile.close()

第一行创建run.log 用于写入,stdout 在可执行文件运行时直接写入日志文件。 run.wait() 等待可执行文件完成,然后关闭日志文件。

【讨论】:

    猜你喜欢
    • 2013-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 1970-01-01
    • 2014-09-26
    相关资源
    最近更新 更多