Using Python to run an executable and fill in user input

I am trying to use Python to automate a process that involves calling a Fortran executable and passing some user inputs. I spent several hours reading similar questions and trying different things, but I was out of luck. Here is a minimal example to show what I tried in the past

#!/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 welcome.

EDIT:

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 file, wait until it asks to enter the user, and then put this input.

+4
5

, , .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() , .

+5

, communicate() , .

, p.stdin & Co ( ).

+1

ps.communicate( " 2" ), ps ps.communicate( " 1" ) EOF. , stdin, , , :

ps.stdin.write('argument 1')
ps.stdin.write('argument 2')
0
source

My problem is for sure - the program first requests input, and then processes this input and produces output. I want to run this program automatically through the subprocess API ...

0
source

Your arguments should not be passed for communication. they should be indicated in a call to Popen, for example: http://docs.python.org/2/library/subprocess.html#subprocess.Popen

>>> import shlex, subprocess
>>> command_line = raw_input()
/bin/vikings -input eggs.txt -output "spam spam.txt" -cmd "echo '$MONEY'"
>>> args = shlex.split(command_line)
>>> print args
['/bin/vikings', '-input', 'eggs.txt', '-output', 'spam spam.txt', '-cmd', "echo '$MONEY'"]
>>> p = subprocess.Popen(args) # Success!
-1
source

Source: https://habr.com/ru/post/1525008/


All Articles