5

I have an executable example.exe. This executable's behaviour is as follows:

1.Waits for input from user
2.Performs some operations, based on input
3.goto 1

How can I use subprocess or a similar module to interact with executable?

I wish to run the process, insert input, receive output, then insert additional inputs based on the output received.

1 Answer 1

3
from subprocess import Popen, PIPE

process = Popen([r'path/to/process', 'arg1', 'arg2', 'arg3'], stdin=PIPE, stdout=PIPE)

to_program = "something to send to the program's stdin"
while process.poll() == None:  # While not terminated
    process.stdin.write(to_program)

    from_program = process.stdout.readline()  # Modify as needed to read custom amount of output
    if from_program == "something":  # send something new based on stdout
       to_program = "new thing to send to program"
    else:
       to_program = "other new thing to send to program"

print("Process exited with code {}".format(process.poll()))
Sign up to request clarification or add additional context in comments.

5 Comments

After first call stdout, stderr = process.communicate(to_program) process terminates... (all additional inputs concidered to be empty string)
The communicate() method reads all of the output and waits for child process to exit before returning.
Sorry, should have tested more thoroughly. Try the new example.
1- in general, you don't know how much should you read and there are other issues with the interactive subprocess usage 2- there is no need to call process.poll() here and it is not enough to call process.poll() -- the process may exit after .poll() call but before the .write() call (unrelated: use is None instead of == None). You should handle IOError errors (EPIPE, EINVAL) raised by .write() instead. If from_program is empty then it means EOF and you could exit the loop.
3- minor: close the pipes and call process.wait() at the end.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.