使用 Python 运行可执行文件并填写用户输入

2022-01-18 00:00:00 python subprocess stdin communicate

问题描述

我正在尝试使用 Python 来自动化涉及调用 Fortran 可执行文件和提交一些用户输入的过程.我花了几个小时阅读类似的问题并尝试不同的事情,但没有任何运气.这是一个显示我上次尝试的最小示例

I'm trying to use Python to automate a process that involves calling a Fortran executable and submitting some user inputs. I've spent a few hours reading through similar questions and trying different things, but haven't had any luck. Here is a minimal example to show what I tried last

#!/usr/bin/python

import subprocess

# Calling executable 
ps = subprocess.Popen('fortranExecutable',shell=True,stdin=subprocess.PIPE)
ps.communicate('argument 1')
ps.communicate('argument 2')

但是,当我尝试运行它时,我收到以下错误:

However, when I try to run this, I get the following error:

  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

非常感谢任何建议或指示.

Any suggestions or pointers are greatly appreciated.

当我调用 Fortran 可执行文件时,它要求用户输入如下:

When I call the Fortran executable, it asks for user input as follows:

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'

不知何故,我需要运行可执行文件,等待它要求用户输入,然后提供该输入.

Somehow, I need to run the executable, wait until it asks for user input and then supply that input.


解决方案

如果输入不依赖于先前的答案,那么您可以使用 .communicate() 一次将它们全部传递:

If the input doesn't depend on the previous answers then you could pass them all at once using .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"]))

.communicate() 等待进程终止,因此您最多可以调用一次.

.communicate() waits for process to terminate therefore you may call it at most once.

相关文章