0

I need to run a external exe file inside a python script. I need two things out of this.

  1. Get whatever the exe outputs to the stdout (stderr).
  2. exe stops executing only after I press the enter Key. I can't change this behavior. I need the script the pass the enter Key input after it gets the output from the previous step.

This is what I have done so far and I am not sure how to go after this.

import subprocess

first = subprocess.Popen(["myexe.exe"],shell=True,stdout=subprocess.PIPE)
0

1 Answer 1

1
from subprocess import Popen, PIPE, STDOUT
first = Popen(['myexe.exe'], stdout=PIPE, stderr=STDOUT, stdin=PIPE) 
while first.poll() is None:
    data = first.stdout.read()
    if b'press enter to' in data:
        first.stdin.write(b'\n')
first.stdin.close()
first.stdout.close()

This pipes stdin as well, do not forget to close your open file handles (stdin and stdout are also file handles in a sense).

Also avoid shell=True if at all possible, I use it a lot my self but best practices say you shouldn't.

I assumed python 3 here and stdin and stdout assumes bytes data as input and output.

first.poll() will poll for a exit code of your exe, if none is given it means it's still running.

Some other tips

one tedious thing to do can be to pass arguments to Popen, one neat thing to do is:

import shlex
Popen(shlex.split(cmd_str), shell=False) 

It preserves space separated inputs with quotes around them, for instance python myscript.py debug "pass this parameter somewhere" would result in three parameters from sys.argv, ['myscript.py', 'debug', 'pass this parameter somewhere'] - might be useful in the future when working with Popen

Another thing that would be good is to check if there's output in stdout before reading from it, otherwise it might hang the application. To do this you could use select.
Or you could use pexpect which is often used with SSH since it lives in another user space than your application when it asks for input, you need to either fork your exe manually and read from that specific pid with os.read() or use pexpect.

Sign up to request clarification or add additional context in comments.

Comments

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.