如何将.exe的输出重定向到python中的文件?

17 python io redirect

在脚本中,我想运行一个带有一些命令行参数的.exe作为"-a",然后

将程序的标准输出重定向到文件?

我该如何实现呢?

mon*_*kut 27

您可以使用子进程直接重定向到文件.

import subprocess
with open('output.txt', 'w') as output_f:
    p = subprocess.Popen('Text/to/execute with-arg',
                         stdout=output_f,
                         stderr=output_f)
Run Code Online (Sandbox Code Playgroud)


Ale*_*lli 10

最简单的是os.system("the.exe -a >thefile.txt"),但还有许多其他方法,例如subprocess标准库中的模块.

  • 值得记住的是,在尝试使用os.system重定向事物时,操作系统之间的管道符号有所不同...... (3认同)