有數百個類似的問題,但在我的情況下,它們似乎都不是解決方案。我的代碼是這樣形成的
def iterative_func():
# do things
while True:
iterative_func()
然后我希望它在我按下熱鍵時停止讓我們說'ctrl k'。我試過pynput但監聽器不適用,因為它等待輸入并且腳本的其余部分(iterative_func())不會運行,在我的情況下,腳本應該連續運行,直到我按下某個熱鍵。還有解決辦法
while True:
try:
iterative_func()
except KeyboardInterrupt:
break
對我不起作用(我不知道為什么,但可能是因為我正在運行 VSCode),無論如何它不是我想要實作的代碼,因為腳本將被部署為 .exe 檔案。
PS。我不能 import Keyand Controllerfrom pynput,它會提示一個錯誤,我不知道如何解決這個問題,所以也應該避免使用這些的解決方案。
uj5u.com熱心網友回復:
我嘗試了pynput,但監聽器不適用,因為它等待輸入并且腳本的其余部分(iterative_func())不會運行
我可以闡明如何克服這個問題,這讓你選擇退出pynput。請參閱以下方法:
from pynput import keyboard
running = True # flag on loop runs
def stop_run(): # function to stop the program
global running
running = False
# register a hotkey, and call stop_run() when it is pressed
with keyboard.GlobalHotKeys({'<ctrl> k': stop_run}) as h:
while running:
print("Running ... ")
這將運行您的代碼并等待熱鍵通過標志停止回圈。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/436512.html
標籤:Python python-3.x 循环 用户界面
上一篇:groupboxGUI中的powershell進度條
下一篇:顫動中的文本欄位
