【问题标题】:write out before subprocess在子进程之前写出
【发布时间】:2012-10-28 11:33:10
【问题描述】:

我有一个使用子进程启动多个进程的脚本。现在我想写一个日志文件,其中包含我自己的输出和子进程的输出。

log = open(LOG,'w')
for tasks in tasklist:
  log.write('log text')
  ... some code and log text ...
  sp = subprocess('task[0]',stdout=log)
  sp.wait()
  log.write('log text')
  sp = subprocess('task[1]',stdout=log)
  sp.wait()
  log.write('log text')
  sp = subprocess('task[2]',stdout=log)
  sp.wait()
  log.write('log text')

现在它将子进程的输出写入顶部,然后是我编写的所有内容。在我每次开始子进程之前,有没有更好的方法来关闭并重新打开文件?

【问题讨论】:

    标签: python io subprocess


    【解决方案1】:

    您需要在每次写入时刷新 python 缓冲区:

    log.write('log text')
    log.flush()
    

    子进程缓冲它们的写入,因此它们的数据在 python 写入之前就在日志文件中结束。 Python 的写入最终会进入它的缓冲区,并且在该缓冲区已满之前不会被刷新。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      相关资源
      最近更新 更多