2015-06-06 40 views
2

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

这可以在不使用os.system的情况下实现吗?

+0

你是什么意思“隐藏标准输出的执行结果”?你只是想让这些结果进入一个文件,而不是显示在你的程序中的屏幕/其他地方? –

+0

@eric事实上,我不希望结果显示在屏幕上或文件以外的其他地方。 – lisa1987

+0

你想重定向标准输出还是标准输出和标准错误? –

回答

3

使用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) 

无论你在命令返回非零出口时做什么除了应该处理tatus。如果你想为标准输出文件和其他处理标准错误打开两个文件:

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) 
1

假设你只是想运行一个命令有它的输出去到一个文件,你可以使用subprocess模块像

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

虽然不会重定向stderr

1

您可以打开一个文件,并把它传递给subprocess.callstdout参数,并运往stdout必去的文件,而不是输出。

import subprocess 

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

它不会捕捉任何输出stderr尽管这必须通过传递一个文件subprocess.callstderr参数被重定向。我不确定您是否可以使用相同的文件。

相关问题