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

发布于 2021-01-29 17:14:20

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

但是,当我尝试运行此命令时,出现以下错误:

  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

任何建议或指示,将不胜感激。

编辑:

当我调用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'

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

关注者
0
被浏览
150
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    如果输入的内容不取决于先前的答案,则可以使用.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() 等待进程终止,因此您最多可以调用一次。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看