如何执行OS命令的结果并将其保存到文件中[重复] - python

This question already has answers here:

How to redirect output with subprocess in Python?

(5个答案)

5年前关闭。

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

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

python大神给出的解决方案

使用subprocess.check_call将stdout重定向到文件对象:

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)