如何执行 OS 命令的结果并将其保存到文件中
How to execute and save result of an OS command to a file
在 python 2.7 中,我想执行一个 OS 命令(例如 UNIX 中的 'ls -l')并将其输出保存到一个文件中。我不希望执行结果显示在文件以外的任何地方。
不使用 os.system 是否可以实现?
假设您只想 运行 一个命令的输出进入一个文件,您可以使用 subprocess
模块,例如
subprocess.call( "ls -l > /tmp/output", shell=True )
虽然不会重定向 stderr
使用 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)
无论您在命令 returns 非零退出状态时做什么,都应该在 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
参数传递给 subprocess.call
,而发往 stdout
的输出将转到该文件。
import subprocess
with open("result.txt", "w") as f:
subprocess.call(["ls", "-l"], stdout=f)
它不会捕获到 stderr
的任何输出,尽管必须通过将文件作为 stderr
参数传递给 subprocess.call
来重定向。我不确定你是否可以使用相同的文件。
在 python 2.7 中,我想执行一个 OS 命令(例如 UNIX 中的 'ls -l')并将其输出保存到一个文件中。我不希望执行结果显示在文件以外的任何地方。
不使用 os.system 是否可以实现?
假设您只想 运行 一个命令的输出进入一个文件,您可以使用 subprocess
模块,例如
subprocess.call( "ls -l > /tmp/output", shell=True )
虽然不会重定向 stderr
使用 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)
无论您在命令 returns 非零退出状态时做什么,都应该在 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
参数传递给 subprocess.call
,而发往 stdout
的输出将转到该文件。
import subprocess
with open("result.txt", "w") as f:
subprocess.call(["ls", "-l"], stdout=f)
它不会捕获到 stderr
的任何输出,尽管必须通过将文件作为 stderr
参数传递给 subprocess.call
来重定向。我不确定你是否可以使用相同的文件。