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

Sira Lam :

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?

Tin Nguyen :
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')

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=21311&siteId=1