将键盘输入传递给Windows可执行文件

时间:2014-05-14 17:06:39

标签: python windows python-2.7 win32com

我正在为一个必须在C:\作为Windows可执行文件运行的软件创建一个Python批处理脚本 管道几乎已经建立。但是可执行文件在启动之前需要一些键盘输入。在尝试传递键盘输入之前,它与subprocess.call()配合使用,但我无法使用communicate()的语法。这在下面说明。

我现在尝试使用win32com添加SendKeys(见下文),但现在主脚本在可执行文件完成之前继续。对我的代码有任何建议吗?我是否可以记录可执行文件的退出状态以使用while循环来暂停主进程,直到可执行文件完成?

#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...

非常感谢任何其他聪明的建议!!

2 个答案:

答案 0 :(得分:3)

尝试一下:

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)
...

此外,如果您想要响应提示,您也可以PIPE stdout并通过以下方式访问它:

app.stdout.read()

参考:https://docs.python.org/2/library/subprocess.html#subprocess.PIPE

答案 1 :(得分:0)

使用Pywin模块的另一个函数管理解决它 - win32ui 它在问题中如上所述,但后来有这个:

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)

本质上,这测试是否存在可执行窗口/进程。虽然窗口存在,但您知道程序仍在运行,因此脚本的其余部分不会继续。

希望这在某些时候对其他人有用!