'Exception in Python scheduler
I'm using Google Colab, and pretty new at Python, but I am trying to build a bot that has three states "green", "yellow" and "red". This is the basic bot, runs every 10 seconds, and if it is running and I press the stop button once, it goes into yellow, but the 2nd time I press the stop button I get "During handling of the above exception, another exception occurred:". Here is the code:
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")
Any help is much appreciated!
Solution 1:[1]
Based on the accepted answer, I changed the exception section and this example now works perfectly:
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")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | WagsMax |
