python - 如何让这个终端命令从 python 执行?
问题描述
我必须运行一个可执行文件,它的输入参数保存在一个文本文件中,比如 input.txt。然后将输出重定向到一个文本文件,比如 output.txt。在 Windows 终端中,我使用命令,
executable.exe < input.txt > output.txt
如何从 python 程序中执行此操作?
我知道这可以使用 os.system 来实现。但我想使用 subprocess 模块运行相同的程序。我正在尝试这样的事情,
input_path = '<'+input+'>'
temp = subprocess.call([exe_path, input_path, 'out.out'])
但是,python 代码执行 exe 文件而不将文本文件定向到它。
解决方案
要重定向输入/输出,请使用stdin
和stdout
参数call
:
with open(input_path, "r") as input_fd, open("out.out", "w") as output_fd:
temp = subprocess.call([exe_path], stdin=input_fd, stdout=output_fd)