python - 从另一个线程调用时未执行的语句

标签 python multithreading

我从某个地方提取的一个简单程序,它所做的只是注册一些全局键盘钩子(Hook),(用于全局热键),当调用 hotkeys() 函数时,它按预期工作。但是如果在另一个线程中调用 hotkeys() 函数,如下所示:

t = threading.Thread(target=hotkeys) 
t.start()

然后语句 sys.exit() , os.startfile (os.environ['TEMP']) , user32.PostQuitMessage (0) , def handle_win_f3 () 内部不会立即执行,而是在一分钟左右(有时)之后执行。为什么?有解决办法吗?做我正在做的事情的更好方法?

该程序:
import threading
import datetime
import os
import sys
import ctypes
from ctypes import wintypes
import win32con

HOTKEYS = {
    1 : (win32con.VK_F3, win32con.MOD_WIN),
    2 : (win32con.VK_F4, win32con.MOD_WIN)
}

def handle_win_f3 (): 
    print 'opening' #this works!
    os.startfile (os.environ['TEMP']) #this doesn't
    print 'opened'

def handle_win_f4 ():
    print 'exiting'
    sys.exit()
    user32.PostQuitMessage (0)

HOTKEY_ACTIONS = {
    1 : handle_win_f3,
    2 : handle_win_f4
}


def hotkeys():
    byref = ctypes.byref
    user32 = ctypes.windll.user32
    print "hotkeys"

    for id, (vk, modifiers) in HOTKEYS.items ():
        print "Registering id", id, "for key", vk
        if not user32.RegisterHotKey (None, id, modifiers, vk):
            print "Unable to register id", id

    msg = wintypes.MSG()
    while user32.GetMessageA (byref (msg), None, 0, 0) != 0:
        print 'looping'
        if msg.message == win32con.WM_HOTKEY:
            action_to_take = HOTKEY_ACTIONS.get(msg.wParam)
            print action_to_take
            if action_to_take:
                action_to_take ()

t = threading.Thread(target=hotkeys)

t.start()
#hotkeys()

谢谢

最佳答案

尝试让主线程进入休眠状态,或者让它在生成的线程上等待。 IOW,在您的程序中添加 t.join() 。

关于python - 从另一个线程调用时未执行的语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6755302/

相关文章:

python - **0.5 可以返回负数吗?

python - 将文本中的值替换为 python 字典中的整数值并求其总和

python - 使用不同 matplotlib 版本绘图的差异

python - 使用 Pandas Melt 获得交替结果

c++ - 设计线程类

c++ - 具有任意作业参数的无锁作业队列

python - 如何准备存储在 zip 文件中的图像数据以便在 Tensorflow 2 中进行训练?

python - vtkRenderWindowInteractor 停止程序

c - 在多核系统中如何访问共享内存

C# One Writer Many Readers 只读一次