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

Using Python to run executable and fill in user input(使用 Python 运行可执行文件并填写用户输入)
本文介绍了使用 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 运行可执行文件并填写用户输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)