Sira Lam
Sira Lam

Reputation: 5367

How can I simulate a key press in a Python subprocess?

The scenario is, I have a Python script which part of it is to execute an external program using the code below:

subprocess.run(["someExternalProgram", "some options"], shell=True)

And when the external program finishes, it requires user to "press any key to exit".

Since this is just a step in my script, it would be good for me to just exit on behalf of the user.

Is it possible to achieve this and if so, how?

Upvotes: 6

Views: 7624

Answers (1)

Tin Nguyen
Tin Nguyen

Reputation: 5330

from subprocess import Popen, PIPE

p = Popen(["someExternalProgram", "some options"], stdin=PIPE, shell=True)
p.communicate(input=b'\n')

If you want to capture the output and error log

from subprocess import Popen, PIPE
    
p = Popen(["someExternalProgram", "some options"], stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True)
output, error = p.communicate(input=b'\n')

remember that the input has to be a bytes object

Upvotes: 6

Related Questions