如何在Python中将.exe的输出重定向到文件?
在一个脚本中,我想运行一个.exe文件,并给它一些命令行参数,比如“-a”,然后
把这个程序的标准输出(也就是它打印出来的信息)重定向到一个文件里。
我该怎么实现这个呢?
5 个回答
3
你可以这样做,比如读取 ls -l 命令的输出(或者其他任何命令的输出)。
p = subprocess.Popen(["ls","-l"],stdout=subprocess.PIPE)
print p.stdout.read() # or put it in a file
你也可以对错误输出(stderr)和标准输入(stdin)做类似的操作。
不过正如 Alex 提到的,如果你只是想把输出保存到一个文件里,那就直接把命令的输出重定向到文件就可以了。
11
最简单的方法是用 os.system("the.exe -a >thefile.txt")
,不过还有很多其他的方法,比如可以使用标准库里的 subprocess
模块。
29
你可以通过使用子进程直接将输出重定向到一个文件。
import subprocess
with open('output.txt', 'w') as output_f:
p = subprocess.Popen('Text/to/execute with-arg',
stdout=output_f,
stderr=output_f)