开发者

statements not executed when called from another thread

A simple program I lifted from somewhere, all it does is register some global keyboard hooks,(for global hotkeys) , It works as expected when the hotkeys() function is called. But if the hotkeys() function is called inside another thread like this:

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

then the statements sys.exit() , os.startfile (os.environ['TEMP']) , user32.PostQuitMessage (0) , inside def handle_win_f3 () are not executed immediately , but after a minute or so(sometimes). Why? and is there a fix? better way of doing what I am doing?

The program:

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()

Thanks


Try putting the main thread to sleep of make it wait on the spawned thread. IOW, add t.join() at the of your program.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜