Key press in a Python subprocess?

Viewed 108
try:
    subprocess.run(exe_path)
    keyboard.press_and_release('enter')
    print('Successful Extracted')
except Exception as exe:
    print(exe.args)
    keyboard.press_and_release('enter')

The point is to run the EXE of windows but it needs an input of keyboard to end its process, and it will remain stuck over there unless a keyboard input is given physically. Right now I am facing an issue as

subprocess.run('some_exe')

is running the process and after successfully run asking

Press Any Key To Exit

while I have already mentioned next to subprocess.run

keyboard.press_and_release('enter')

and it's coming to the next line unless we press the button from the keyboard manually

NOTE: python3.8

2 Answers

For the sake of a reproducible example, say we want to run the following Python script as a subprocess, let's call it script.py.

input('Press Enter to exit.')

It won't terminate until the user presses the Enter key. If we want to emulate the key press, we can just send a newline character to the subprocess's stdin using Popen.communicate. Like so:

from subprocess import Popen, PIPE

process = Popen(['python', 'script.py'], stdin=PIPE, text=True)
process.communicate('\n')

The external program doesn't have to be a Python script, it can be any executable. Just replace ['python', 'script.py'] with the corresponding command-line call, e.g. ['some_exe'].

Obviously this also works if the external program accepts any key to exit. Only sending special keys which don't have an obvious text representation, such as F1, would complicate things.

You can create a .vbs file to run your .exe file or python script without console debugging window:

Set oShell = CreateObject ("Wscript.Shell") 
Dim strArgs
strArgs = "cmd /c  python main.py"
oShell.Run strArgs, 0, false

If you have .exe file just replace python main.py with yourFile.exe.

Related