Pass keyboard input to a windows executable
Question: I am creating a Python batch script for a piece of software that must run as a
windows executable in C:\ The pipeline is almost set up. But the executable
requires some keyboard entry before it starts. Before trying to pass keyboard
entry it worked with `subprocess.call()` but I couldn't get the syntax to work
for `communicate()`. This is commented out below.

I have tried now with win32com add on SendKeys (see below), but now the main
script carries on before the executable finishes. Any advice on my code? Can I
log the exit status of the executable to use a while loop just to sleep the
main process until the executable finishes?

    
    
    #subprocess.call(r"C:\LTR_STRUC\LTR_STRUC_1_1.exe")
    shell = win32com.client.Dispatch("WScript.shell")
    Return = shell.Run(r"C:\LTR_STRUC\LTR_STRUC_1_1.exe")
    time.sleep(2)
    shell.AppActivate(r"C:\LTR_STRUC\LTR_STRUC_1_1.exe")
    shell.SendKeys("y", 0)
    shell.SendKeys("{Enter}", 0)
    time.sleep(1)
    shell.SendKeys("y", 0)
    shell.SendKeys("{Enter}", 0)
    time.sleep(1)
    shell.SendKeys("{Enter}", 0)
    
    ###...and on goes the code...
    

Any other clever suggestions will be much appreciated!!


Answer: Give this a try:

    
    
    import os
    from subprocess import Popen, PIPE
    cmd = r"C:\LTR_STRUC\LTR_STRUC_1_1.exe"
    
    app = Popen(cmd, stdin=PIPE, shell=True)
    app.stdin.write("y" + os.linesep)
    ...
    

Also if you wanted respond to a prompt you could PIPE stdout as well and
access it via:

    
    
    app.stdout.read()
    

reference: <https://docs.python.org/2/library/subprocess.html#subprocess.PIPE>

