使用Python运行可执行文件并填写用户输入 [英] Using Python to run executable and fill in user input

查看:53
本文介绍了使用Python运行可执行文件并填写用户输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 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.

这篇关于使用Python运行可执行文件并填写用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆