Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/magento/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何执行操作系统命令并将结果保存到文件中_Python_Python 2.7_Subprocess - Fatal编程技术网

Python 如何执行操作系统命令并将结果保存到文件中

Python 如何执行操作系统命令并将结果保存到文件中,python,python-2.7,subprocess,Python,Python 2.7,Subprocess,在Python2.7中,我希望执行一个OS命令(例如UNIX中的“ls-l”)并将其输出保存到一个文件中。我不希望执行结果显示在文件之外的任何其他地方 这在不使用操作系统的情况下是可以实现的吗 假设您只想运行一个命令,并将其输出放入一个文件中,您可以使用子流程模块,如 subprocess.call( "ls -l > /tmp/output", shell=True ) 虽然这不会重定向stderr使用子进程。检查调用将stdout重定向到文件对象: from subprocess i

在Python2.7中,我希望执行一个OS命令(例如UNIX中的“ls-l”)并将其输出保存到一个文件中。我不希望执行结果显示在文件之外的任何其他地方


这在不使用操作系统的情况下是可以实现的吗

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

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

虽然这不会重定向stderr

使用
子进程。检查调用
将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)

您可以打开一个文件并将其传递给
子流程。调用
stdout
作为
stdout
参数,目标为
stdout
的输出将转到该文件

import subprocess

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

它不会捕获到任何到
stderr
的输出,不过必须通过将文件传递到
子流程来重定向。调用
stderr
作为
stderr
参数。我不确定您是否可以使用同一个文件。

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