【问题标题】:How to execute and save result of an OS command to a file [duplicate]如何执行操作系统命令的结果并将其保存到文件中[重复]
【发布时间】:2015-08-21 09:29:25
【问题描述】:

在 python 2.7 中,我想执行一个操作系统命令(例如 UNIX 中的“ls -l”)并将其输出保存到文件中。我不希望执行结果显示在文件以外的任何地方。

不使用 os.system 可以实现吗?

【问题讨论】:

  • “隐藏标准输出的执行结果”是什么意思?您是否只想将这些结果放入文件中而不显示在屏幕/程序的其他位置?
  • @eric 实际上,我不希望结果显示在屏幕上或文件以外的任何其他地方。
  • 你想只重定向标准输出还是同时重定向标准输出和标准错误?

标签: python python-2.7 subprocess


【解决方案1】:

使用subprocess.check_call 将标准输出重定向到文件对象:

from subprocess import check_call, STDOUT, CalledProcessError

with open("out.txt","w") as f:
    try:
        check_call(['ls', '-l'], stdout=f, stderr=STDOUT)
    except CalledProcessError as e:
        print(e.message)

当命令返回非零退出状态时,无论你做什么,都应该在except中处理。如果您想要一个用于 stdout 的文件和另一个用于处理 stderr 的文件,请打开两个文件:

from subprocess import check_call, STDOUT, CalledProcessError, call

with open("stdout.txt","w") as f, open("stderr.txt","w") as f2:
    try:
        check_call(['ls', '-l'], stdout=f, stderr=f2)
    except CalledProcessError as e:
        print(e.message)

【讨论】:

    【解决方案2】:

    假设您只想运行命令并将其输出放入文件中,您可以使用subprocess 模块,如

    subprocess.call( "ls -l > /tmp/output", shell=True )
    

    虽然这不会重定向stderr

    【讨论】:

      【解决方案3】:

      您可以打开一个文件并将其作为stdout 参数传递给subprocess.call,而发往stdout 的输出将转到该文件。

      import subprocess
      
      with open("result.txt", "w") as f:
          subprocess.call(["ls", "-l"], stdout=f)
      

      它不会捕获到stderr 的任何输出,尽管必须通过将文件作为stderr 参数传递给subprocess.call 来重定向。我不确定你是否可以使用同一个文件。

      【讨论】:

        猜你喜欢
        • 2012-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-11
        • 1970-01-01
        • 2011-07-16
        • 2012-04-21
        相关资源
        最近更新 更多