我正在使用 Google Colab,并且在 Python 中還很新,但我正在嘗試構建一個具有“綠色”、“黃色”和“紅色”三種狀態的機器人。這是基本的機器人,每 10 秒運行一次,如果它正在運行并且我按下停止按鈕一次,它會變成黃色,但第二次按下停止按鈕我得到“在處理上述例外期間,另一個例外發生了:”。這是代碼:
import sched, time, datetime, json
try:
def run_bot(sc):
if botstate == "green":
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") " doing " botstate " state stuff")
s.enter(10, 1, run_bot, (sc,))
s.run()
elif botstate == "yellow":
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") " doing " botstate " state stuff")
s.enter(10, 1, run_bot, (sc,))
s.run()
else:
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") " FINISHED")
# START POINT
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
botstate = "green"
s = sched.scheduler(time.time, time.sleep)
s.enter(10, 1, run_bot, (s,))
s.run()
except KeyboardInterrupt:
if botstate == "green":
botstate = "yellow"
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") " botstate set to " botstate ", shutdown state entered")
s.run()
else:
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") " HARD FINISHED")
任何幫助深表感謝!
uj5u.com熱心網友回復:
你第一次打電話時s.run(),你在一個try街區。當您按下 ctrl-c 時,您會進入 KeyboardInterrupt 例外塊。
然后在那個塊內你s.run()再次呼叫,但這次你不在一個try塊中,所以再次按 ctrl-c 會引發一個未捕獲的例外。
uj5u.com熱心網友回復:
根據接受的答案,我更改了例外部分,此示例現在可以完美運行:
import sched, time, datetime, json
try:
def run_bot(sc):
if botstate == "green":
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") " doing " botstate " state stuff")
elif botstate == "yellow":
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") " doing " botstate " state stuff")
# recurse
s.enter(10, 1, run_bot, (sc,))
s.run()
# START POINT
print (datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") " STARTED")
botstate = "green"
s = sched.scheduler(time.time, time.sleep)
s.enter(10, 1, run_bot, (s,))
s.run()
except KeyboardInterrupt:
try:
if botstate == "green":
botstate = "yellow"
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") " botstate set to " botstate ", shutdown state entered")
s.run()
except KeyboardInterrupt:
print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") " FINISHED")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/426233.html
