您好我刚刚开始使用python脚本来运行可执行文件。我基本上想要做的是使用python编辑 input.dat 文件并运行可执行文件 myfile ,其中输入 input.dat 作为输入参数并保存输出 result.dat 文件中的结果并在循环中运行整个 input.dat
我已经找到了编辑部分,但是运行和输入部分是我似乎无法弄清楚的。
在终端上它看起来像
sudo ./myfile < input.dat
答案 0 :(得分:2)
您可以使用subprocess.run()
通过文件输入执行命令并将其输出重定向到另一个文件:
import subprocess
for filename in 'input.dat', 'otherinput.dat', 'moreinput.dat':
with open(filename) as infile, open('result_{}'.format(filename), 'w') as outfile:
result = subprocess.run(['sudo', 'myfile'], stdin=infile, stdout=outfile)