【问题标题】:append subprocess.Popen output to file?将 subprocess.Popen 输出附加到文件?
【发布时间】:2011-11-15 09:25:14
【问题描述】:

我可以成功地将我的输出重定向到一个文件,但这似乎覆盖了文件的现有数据:

import subprocess
outfile = open('test','w') #same with "w" or "a" as opening mode
outfile.write('Hello')
subprocess.Popen('ls',stdout=outfile)

将从文件中删除'Hello' 行。

我想一种解决方法是将输出作为字符串或其他内容存储在其他地方(不会太长),然后手动附加outfile.write(thestring) - 但我想知道我是否在模块中遗漏了一些东西促进了这一点。

【问题讨论】:

标签: python subprocess popen


【解决方案1】:

您当然可以将subprocess.Popen 的输出附加到文件中,我每天都会使用它。这是我的做法:

log = open('some file.txt', 'a')  # so that data written to it will be appended
c = subprocess.Popen(['dir', '/p'], stdout=log, stderr=log, shell=True)

(当然,这是一个虚拟的例子,我没有使用subprocess 来列出文件...)

顺便说一句,其他表现得像文件的对象(特别是 write() 方法)可以替换这个 log 项目,所以你可以缓冲输出,并用它做任何你想做的事情(写入文件,显示,等)[但这似乎并不那么容易,请参阅下面的评论]。

注意:可能具有误导性的是,subprocess,出于某种我不明白的原因,会在您想写的内容之前写。所以,这是使用它的方法:

log = open('some file.txt', 'a')
log.write('some text, as header of the file\n')
log.flush()  # <-- here's something not to forget!
c = subprocess.Popen(['dir', '/p'], stdout=log, stderr=log, shell=True)

所以提示是:不要忘记flush输出!

【讨论】:

  • 请注意上面的帖子:经过一些试验后,subprocess.Popenstdoutstderrarguments 似乎需要一个类似文件的东西,所以给他们一个自定义对象,只有write 方法是不够的。我试过了,但是需要 fileno 函数,而且我还不够好,无法在我自己的类上模拟它。
  • 我一直在尝试使用这种方法,但我发现由于某种原因,每次我使用我明确打开以进行附加的文件运行外部进程时,进程的输出都会从文件的开头并覆盖那里的任何信息。因此,为了使用此解决方案,必须在打开文件后立即调用 log.seek(0, os.SEEK_END)。​​
【解决方案2】:

问题是如果你希望标题是标题,那么你需要在将其余输出写入文件之前刷新:D

【讨论】:

    【解决方案3】:

    文件中的数据真的被覆盖了吗?在我的 Linux 主机上,我有以下行为: 1)您在单独目录中的代码执行得到:

    $ cat test
    test
    test.py
    test.py~
    Hello
    

    2) 如果我在outfile.write('Hello') 之后添加outfile.flush(),结果会略有不同:

    $ cat test
    Hello
    test
    test.py
    test.py~
    

    但输出文件在这两种情况下都有Hello。如果没有显式的 flush() 调用 stdout 缓冲区将在 python 进程终止时被刷新。 问题出在哪里?

    【讨论】:

      猜你喜欢
      • 2017-03-20
      • 2016-06-07
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 2011-09-09
      • 2015-09-05
      • 1970-01-01
      相关资源
      最近更新 更多