Using Python to run executable and fill in user input

后端 未结 4 1231
太阳男子
太阳男子 2020-12-15 12:25

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

相关标签:
4条回答
  • 2020-12-15 12:51

    your arguments should not be passed to communicate. they should be given in the call to Popen, like: 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!
    
    0 讨论(0)
  • 2020-12-15 13:01

    By the time, you reach ps.communicate('argument 2'), ps process is already closed as ps.communicate('argument 1') waits until EOF. I think, if you want to write multiple times at stdin, you might have to use:

    ps.stdin.write('argument 1')
    ps.stdin.write('argument 2')
    
    0 讨论(0)
  • 2020-12-15 13:07

    As the spec says communicate() awaits for the subprocess to terminate, so the second call will be addressed to the finished process.

    If you want to interact with the process, use p.stdin&Co instead (mind the deadlock warning).

    0 讨论(0)
  • 2020-12-15 13:18

    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() waits for process to terminate therefore you may call it at most once.

    0 讨论(0)
提交回复
热议问题