python - 排除子进程时的线程

标签 python multithreading subprocess

我编写了一个程序来捕获俄罗斯方 block 上的键盘事件,该事件是通过子进程打开的。不,当我只想在不打开俄罗斯方 block 的情况下捕获事件时,我的键盘处理程序 (pyHook) 不会捕获事件:

# open Tetris
#Tetris = subprocess.Popen (["C:\\Program Files (x86)\Tetris\Tetris.exe"])
#start game by sending "F2" key
#for hwnd in get_hwnds_for_pid (Tetris.pid):
    #win32gui.PostMessage (hwnd, win32con.WM_KEYDOWN, win32con.VK_F2, 0)

keyH = KeyHandler()
ToneT = ToneTimer()

keyH.setDaemon(True)
ToneT.setDaemon(True)

keyH.start()
ToneT.start()

这在使用另一个子进程时工作正常,但我不知道为什么现在卡住了。 KeyHandler 不会拿起 key 。

class KeyHandler(threading.Thread):

    def run(self):
        # watch for all keyboard events
        KeyHandler.hm.KeyDown = self.OnKeyboardCharEvent
        # set the hook
        KeyHandler.hm.HookKeyboard()
        # activate message pipeline
        print "keyboardhooked"
        pythoncom.PumpMessages()
        print "thisshouldnotbeprinted"

除了最后一条语句之外的所有语句都被打印出来,但唤起的键没有被打印出来,而是当我按下一个键时应用程序卡住(我有一个函数来捕获事件,该事件与包含的子进程一起工作......)

我猜想在省略子进程时线程有问题。

我发现如果我在按下一个键之前切换到另一个 GUI 窗口,然后按下一个键,键就会被接受并打印出键事件。

更精确的信息:这可能与在 OpenSesame(实验软件)中运行脚本有关,因为 pyhook 通常不会从他的窗口中检索键盘响应,而只能从 gui 窗口中检索键盘响应?!因此我可能需要在这里寻找 pyhook 的替代品?

最佳答案

由于 Qt 绕过了 Windows 消息循环,它无法正常工作——pyHook 依赖于消息循环来运行。

Modern graphical interface frameworks, such as Windows Forms, Windows Presentation Foundation, MFC, Delphi, Qt and others do not typically require applications to directly access the Windows message loop, but instead automatically route events such as key presses and mouse clicks to their appropriate handlers as defined within the framework.

来自 Message Loop in MS Windows

关于python - 排除子进程时的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23630969/

相关文章:

python - 我如何使用(唯一键和最大值)从字典中提取所有值

python - 如何计算系列对象中带有模式的字符串?

java - 以原子方式递增存储在 ConcurrentHashMap 中的计数器

c++ - Boost Asio延迟写入tcp套接字

python - 如何通过管道将子进程调用传递给文本文件?

python - Django 模型问题

python - 如何在 flatMap 函数中实现迭代

c++ - 使用openMP的多线程两个功能

Python 子进程 : read returncode is sometimes different from returned code

python - 波浪号 (~) 在 subprocess.Popen() 中不起作用