Reputation: 75
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!!
Upvotes: 4
Views: 2454
Reputation: 75
Managed to solve it using another function of the Pywin module - win32ui
It works as above in the question but then has this:
import win32ui
def WindowExists(windowname):
try:
win32ui.FindWindow(None, windowname)
except win32ui.error:
return False
else:
return True
process = True
while process == True:
if WindowExists(r"C:\LTR_STRUC\LTR_STRUC_1_1.exe"):
process = True
else:
process = False
time.sleep(5)
Essentially, this tests for the presence of the executable window/process. Whilst the window exists you know the program is still going, so the rest of the script doesn't continue.
Hope this is useful to someone else at some point!
Upvotes: 0
Reputation: 2442
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
Upvotes: 3