【问题标题】:Waiting for user input when controlling 3rd party application via python script通过 python 脚本控制 3rd 方应用程序时等待用户输入
【发布时间】:2018-04-20 21:48:20
【问题描述】:

我正在编写一个供项目团队成员使用的脚本。作为脚本的一部分,我将启动通过 Citrix 运行的第 3 方专有应用程序。我将主要使用脚本将密钥发送到此应用程序,但启动后的第一步是让用户登录。

因为我希望用户在脚本运行时登录,而不是早先从某种 GUI 输入中要求用户/通行证,并且因为 Citrix 启动所需的时间各不相同,所以我想包括一些一种检测用户何时登录然后从那里恢复脚本的逻辑,而不是包含令人讨厌的长时间隐式等待或冒着脚本超时的风险。

有没有办法使用 win32com.client 检测用户击键(或检测应用程序本身状态的变化)?启动应用的相关代码如下:

import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shell.Run('C:\Citrix\[rest of path])

编辑: 根据 Vasily 在下面 cmets 中的建议,我尝试使 "hook and listen" code 适应我的场景,但没有成功。当我启动我的文件时,我什至没有在终端中收到异常消息,我收到一个 Windows 弹出窗口,提示 Python 遇到问题并需要退出。

我是这样改编的:

#[omitting import lines for brevity]
def on_timer():
    """Callback by timer out"""
    win32api.PostThreadMessage(main_thread_id, win32con.WM_QUIT, 0, 0);


def on_event(args):
    """Callback for keyboard and mouse events"""
    if isinstance(args, KeyboardEvent):
        for i in range(1,100):
            time.sleep(1)
            if args.pressed_key == 'Lcontrol':
                break

def init():
    hk = Hook()
    hk.handler = on_event
    main_thread_id = win32api.GetCurrentThreadId()
    t = Timer(55.0, on_timer)  # Quit after 55 seconds
    t.start()
    hk.hook(keyboard=True, mouse=True)

当第 3 方 Citrix 应用程序开始在我的主脚本中启动时,我调用 hookandlisten.init()。

提醒一下,我的目标是等到用户发送某个击键(这里我选择了 Control),然后再继续执行主脚本的其余部分。

【问题讨论】:

  • 示例:hook_and_listen.py.
  • 这看起来应该可以解决问题!我会测试一下。这也可以用来触发键盘事件(即不仅仅是发送击键)吗?
  • 您的意思是按住键然后在其他一些操作后释放键吗?这是可能的,但需要更详细的描述以提供示例或指向正确文档页面的链接。
  • 看起来键盘成功了 (pypi.org/project/keyboard)。我仍在为上述模块苦苦挣扎的一件事是它似乎在监听一个动作,然后执行一个指定的动作,但我似乎无法让它做的是作为“等待”的功能——也就是说,一旦听到按下“Enter”键,继续我的脚本的其余部分,但除非或直到按下该键,否则什么也不做。
  • @VasilyRyabov 我尝试修改该模块以匹配我的场景(参见编辑后的帖子),但没有成功。我哪里错了?

标签: python windows pywin32 pywinauto


【解决方案1】:

通过消除计时器并在正确击键时松开键盘来解决此问题:

import win32api
import win32con
from pywinauto.win32_hooks import Hook
from pywinauto.win32_hooks import KeyboardEvent
from pywinauto.win32_hooks import MouseEvent


def on_event(args):

    """Callback for keyboard and mouse events"""
    if isinstance(args, KeyboardEvent):
        if args.current_key == 'Lcontrol' and args.event_type == 'key down':
            print("Success")
            hk.unhook_keyboard()
            return

def init():
    hk.handler = on_event
    hk.hook(keyboard=True, mouse=False)

hk = Hook()

【讨论】:

    猜你喜欢
    • 2011-02-12
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多