Jam*_*mes 5 python stdin subprocess communicate
我正在尝试使用Python来自动化涉及调用Fortran可执行文件并提交一些用户输入的过程.我花了几个小时阅读类似的问题和尝试不同的事情,但没有运气.这是一个显示我上次尝试的最小例子
#!/usr/bin/python
import subprocess
# Calling executable
ps = subprocess.Popen('fortranExecutable',shell=True,stdin=subprocess.PIPE)
ps.communicate('argument 1')
ps.communicate('argument 2')
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试运行它时,我收到以下错误:
File "gridGen.py", line 216, in <module>
ps.communicate(outputName)
File "/opt/apps/python/epd/7.2.2/lib/python2.7/subprocess.py", line 737, in communicate
self.stdin.write(input)
ValueError: I/O operation on closed file
Run Code Online (Sandbox Code Playgroud)
非常感谢任何建议或指示.
编辑:
当我调用Fortran可执行文件时,它会询问用户输入如下:
fortranExecutable
Enter name of input file: 'this is where I want to put argument 1'
Enter name of output file: 'this is where I want to put argument 2'
Run Code Online (Sandbox Code Playgroud)
不知何故,我需要运行可执行文件,等待它询问用户输入然后提供该输入.
如果输入不依赖于先前的答案,那么您可以使用.communicate()以下方法一次性传递它们:
import os
from subprocess import Popen, PIPE
p = Popen('fortranExecutable', stdin=PIPE) #NOTE: no shell=True here
p.communicate(os.linesep.join(["input 1", "input 2"]))
Run Code Online (Sandbox Code Playgroud)
.communicate() 等待进程终止,因此您最多可以调用一次.