![](/img/trans.png)
[英]How do I exit a while loop from a keypress without using KeyboardInterrupt? [python]
[英]Python how can I manually end an infinite while loop that's collecting data, without ending the code and not using KeyboardInterrupt?
在我的代碼中,我有一個“while True:”循環,需要在收集實時數據時運行不同的時間(3-5小時)。 由於時間沒有預先確定,我需要手動結束while循環而不終止腳本,以便它可以繼續到腳本中的下一個代碼體。
我不想在循環結束時使用“input()”,因為那時我必須手動告訴它每次完成循環時繼續循環,我收集實時數據到半秒,所以這是不實用。
另外我不想使用鍵盤中斷,它有問題。 還有其他解決方案嗎? 我所看到的只是嘗試/除了“keyboardinterrupt”
def datacollect()
def datacypher()
while True:
#Insert code that collects data here
datacollect()
#end the while loop and continue on
#this is where i need help
datacypher()
print('Yay it worked, thanks for the help')
我希望手動結束循環,然后繼續執行對收集的數據執行操作的代碼。
如果您需要更多詳細信息或我的措辭有問題,請告訴我。 我之前只問過一個問題。 我在學習。
如何在第二個線程中添加一個鍵監聽器? 按Enter鍵后 ,您將通過共享bool手動將腳本移動到下一個階段。 第二個線程不應該減慢進程,因為它阻塞input()
。
from threading import Thread
from time import sleep
done = False
def listen_for_enter_key_press():
global done
input()
done = True
listener = Thread(target=listen_for_enter_key_press)
listener.start()
while not done:
print('working..')
sleep(1)
listener.join()
print('Yay it worked, thanks for the help')
中斷循環的一種方法是使用信號。
import signal
def handler(signum, stackframe):
global DONE
DONE = True
signal.signal(signal.SIGUSR1, handler)
DONE = False
while not DONE:
datacollect()
datacypher()
循環將繼續,直到程序收到USR1信號(從shell發送,例如, kill -s USR1 <pid>
,其中<pid>
是程序的進程ID),此時DONE
將為True
你的循環測試它的價值。
您可以通過將handler
作為signal.SIGINT
的處理程序而不是signal.SIGUSR1
來修改鍵盤中斷,因為默認的信號處理程序首先引發了KeyboardInterrupt
異常。
一個選項是,您可以查找文件的存在,例如:
import os.path
fname = '/tmp/stop_loop'
def datacollect()
def datacypher()
while not os.path.isfile(fname):
#Insert code that collects data here
datacollect()
#end the while loop and continue on
#this is where i need help
datacypher()
print('Yay it worked, thanks for the help')
如果該文件不存在,它將繼續通過while循環。 然后,當你想要停止while循環時,你只需要touch /tmp/stop_loop
,while循環就會停止。
我懷疑isfile()
應該是一個相當有效的,所以也許這不會太糟糕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.