Python使用输入和输出流运行外部程序

时间:2017-03-17 06:25:01

标签: python input stream subprocess

我有一个FORTRAN程序,可以运行输入流。所以我通常使用“program.exe< Input> Output”命令来执行程序。但是,我想异步运行python中的程序。

我试过了:

input = open("Input", 'rb').read()
running_procs = [Popen(['program.exe'], stdout=PIPE, stdin=PIPE, stderr=PIPE)]

while running_procs:
for proc in running_procs:
    retcode = proc.poll()
    if retcode is not None: # Process finished.
        running_procs.remove(proc)
        break
else: # No process is done, wait a bit and check again.
    proc.stdin.write(input)
    time.sleep(.1)
    continue

# Here, `proc` has finished with return code `retcode`
if retcode != 0:
    """Error handling."""
print(proc.stdout)

我不知道是否

proc.stdin.write(input)

这将对输入流进行写入输入。

请帮忙。

1 个答案:

答案 0 :(得分:0)

对不起,我发现实际上有很多关于我问过的问题的帖子。

input = open("Input", 'rb').read()

running_proc = Popen(['program.exe'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
out, err = running_proc.communicate(input=input)
outfile = open("outfile.out", "w")
outfile.write(out.decode())

谢谢