简体   繁体   English

我如何从Python执行此终端命令?

[英]How do I get this terminal command to be executed from python?

I have to run an executable for which input parameters are saved in a text file, say input.txt. 我必须运行一个可执行文件,其输入参数保存在文本文件中,例如input.txt。 The output is then redirected to a text file, say output.txt. 然后将输出重定向到文本文件,例如output.txt。 In windows terminal, I use the command, 在Windows终端中,我使用以下命令,

executable.exe < input.txt > output.txt

How can I do this from within a python program? 如何在python程序中执行此操作?

I understand that this can be achieved using os.system. 我知道可以使用os.system来实现。 But I wanted to run the same using subprocess module. 但是我想使用子进程模块运行相同的代码。 I was trying something like this, 我在尝试这样的事情

input_path = '<'+input+'>'
temp = subprocess.call([exe_path, input_path, 'out.out'])

But, the python code executes the exe file without directing the text file to it. 但是,python代码执行了exe文件,而没有将文本文件定向到该文件。

To redirect input/output, use the stdin and stdout parameters of call : 要重定向输入/输出,请使用callstdinstdout参数:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM