5

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?

Sira Lam
  • 5,179
  • 3
  • 34
  • 68
  • Does this answer your question? [How to generate keyboard events in Python?](https://stackoverflow.com/questions/13564851/how-to-generate-keyboard-events-in-python) – ChatterOne Mar 03 '20 at 07:49

1 Answers1

6
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

Community
  • 1
  • 1
Tin Nguyen
  • 5,250
  • 1
  • 12
  • 32
  • I think we need the 'b' before '\n' because it looks like input requires a byte-like object. I tried `p.communicate(input=b'\n')` and it worked! Thank you. – Sira Lam Mar 03 '20 at 08:13
  • Glad it worked, edited my comment. `p.communicate()` also does a `p.wait()`. – Tin Nguyen Mar 03 '20 at 08:14