【发布时间】:2011-07-19 23:24:15
【问题描述】:
我从某个地方提取的一个简单程序,它所做的只是注册一些全局键盘钩子,(用于全局热键),当调用 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()
谢谢
【问题讨论】:
-
sys.exit()从另一个线程运行时只会杀死该线程。你到底想达到什么目的?如果你想完全杀死你的进程,试试os._exit(0)
标签: python multithreading