[英]Python return to function after exiting one another
退出上一個函數后如何返回該函數? 我的代碼是這樣的:
import pyHook, pythoncom, sys
import msvcrt
def test(keyLogging):
key = msvcrt.getwche()
if key == 'x':
print("Worked")
sys.exit(0)
return None
def test2(keyLogging):
key = msvcrt.getwche()
if key == 'c':
print("Worked, again")
sys.exit(0)
return None
def keyLogging():
key = msvcrt.getwche()
if key == 'z':
hm = pyHook.HookManager()
hm.KeyDown = test
hm.HookKeyboard()
pythoncom.PumpMessages()
elif key == 'v':
hm = pyHook.HookManager()
hm.KeyDown = test2
hm.HookKeyboard()
pythoncom.PumpMessages()
keyLogging()
從keyLogging
test
或test2
調用一個函數並且被調用的函數完成后,我想返回到keylogging以再次選擇運行哪個函數。 類似無限循環但具有功能的東西。 sys.exit()
僅終止所有操作,我也嘗試在兩個函數中進行線程化,並在return
返回keyLogging
只需將keylogging()
放在要返回到keylogging()
的每個函數調用的末尾。 例如:
def test(keyLogging):
key = msvcrt.getwche()
if key == 'x':
print("Worked")
keyLogging()
return None
編輯:基於注釋,看來pyhook
模塊可能已損壞。
您可能需要使用pywin32來以其他方式訪問Windows掛鈎API。
我自己沒有這個項目的經驗,但是與pyhook不同,它似乎得到了積極維護,這始終是一個好兆頭。
您的問題不是關於“恢復功能”。
似乎您是在Windows下設置一個鍵盤掛鈎,並且每次觸發該掛鈎事件時都想重置它。
為此,您需要重組程序,因為如果您只是簡單地以編寫代碼的方式再次調用keyLogging
,那么您將難以進行多次嘗試來抽送消息隊列和安裝多個鈎子。
pyhook庫文檔非常糟糕,因此我不確定會出現哪種錯誤,但這更多的原因是為了干凈運行而重組程序。
首先 -具有main
功能,如下所示:
def main():
keyLogging(False) # call with False parameter means no old hooks to clean up
pythoncom.PumpMessages()
注意,我在您的keyLogging
函數中添加了一個參數,這樣做是為了讓該函數知道是否需要執行清理。
其次 -更改密鑰記錄設置功能以啟用對舊鈎子的清理,並確保完成后退出:
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
第三 -現在您有了合適的keyLogging
函數版本,可以從掛鈎函數中調用它,以允許用戶選擇新的掛鈎。
請注意,您不得為鈎子函數賦予與代碼中其他名稱相同的參數名稱!
這就是所謂的“陰影” ,這意味着您將無法從函數中訪問其他東西!
def test(event):
key = msvcrt.getwche()
if key == 'x':
print("Worked")
keyLogging(True) # call with True parameter means old hook needs cleanup
現在,您的程序將完全執行您想要的操作。
要考慮的另一件事是,如果您想知道用戶按下了什么鍵來觸發test
功能,則無需使用msvcrt.getwche()
。
它已經在函數參數event
傳遞,因此您可以像這樣檢查它:
def test(event):
if event.getKey() == 'x' or event.Ascii == 'x':
print("Worked")
keyLogging(True)
這在此處記錄 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.