我从某处提取的一个简单程序,它所做的只是注册一些全局键盘钩子(对于全局热键),它在调用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()
由于
答案 0 :(得分:0)
尝试让主线程处于休眠状态,让它在生成的线程上等待。 IOW,在你的程序中添加t.join()。