EDIT: Based on the comments it looks like pyhook
module may be somewhat broken.
You may want to use pywin32 to access windows hooking API another way.
I don't have experience with this project my self, but it appears to be actively maintained, unlike pyhook, and thats always a good sign.
Your question is not really about "returning to function".
It appears that you are setting a keyboard hook under windows, and you want to reset it, every time the hooked event fires.
To do this, you need to restructure your program, because if you simply call keyLogging
again the way it is written in your code, you will be stuck with multiple attempts to pump the message queue and multiple hooks installed.
The pyhook library documentation is pretty bad, so I am not sure what kind of errors you would get, but this is all the more reason to restructure your program for clean operation.
First - have a main
function, like this:
def main():
keyLogging(False) # call with False parameter means no old hooks to clean up
pythoncom.PumpMessages()
Notice, I added a parameter to your keyLogging
function, this is so the function will know if it needs to perform cleanup.
Second - change your key logging setup function to enable cleanup of old hooks, and also, make sure it exits when done:
def keyLogging(cleanup):
hm = pyHook.HookManager()
# if you called this function before, uninstall old hook before installing new one!
if cleanup:
hm.UnhookKeyboard()
key = msvcrt.getwche() # ask user for new hook as you did originaly
# in the if block, only select what hook you want, clean up redundant code!
if key == 'z':
hm.KeyDown = test
elif key == 'v':
hm.KeyDown = test2
hm.HookKeyboard() # finally, install the new hook
Third - now that you have a suitable version of keyLogging
function, you can call it from your hook functions to allow the user to choose a new hook.
Note that you must not give your hook function a parameter name that is the same as another name in your code!
This is called 'shadowing' and it means you will not be able to access the other thing from within the function!
def test(event):
key = msvcrt.getwche()
if key == 'x':
print("Worked")
keyLogging(True) # call with True parameter means old hook needs cleanup
And now your program will do what you wanted cleanly.
One more thing to consider, is that if you want to know what key the user pressed to trigger your test
function, you don't need to use msvcrt.getwche()
.
It is already passed in the function parameter event
so you can check it like this:
def test(event):
if event.getKey() == 'x' or event.Ascii == 'x':
print("Worked")
keyLogging(True)
This is documented here.