I have written a simple application for my RaspberryPi in python3. My rpi has a fresh install and I have completed all updates prior to starting development. This application is a sports scoreboard that displays on an LED matrix and utilizes a bluetooth game controller and the evdev module for input controls.
The bluetooth input was working very well, and was 100% responsive except that if it disconnected, the application would crash because it could no longer access /dev/input/event0 (which was is the gamepad input).
I added try-except Exception to the code, which resolved the crash and allowed the code to continue if the gamepad disconnected. This has introduced two new issues that I need assistance with.
About 10% of gamepad input doesn't register now. Sometimes a button has to be pressed twice to register.
Ctl-C in the console will not stop code execution. I'll get the following in the console:
KeyboardInterrupt:
^CException ignored in: <function InputDevice.del at 0x757d6588>
If I remove the try-except for the gamepad read, it will work normally until the gamepad disconnects. Here is the code in question.
while True:
#Gamepad read
try:
dev = InputDevice('/dev/input/event0')
gen = dev.read()
except Exception:
pass
#Gamepad functions
try:
for ev in gen:
if ev.type == ecodes.EV_KEY:
if ev.value == 1:
if ev.code == 23:
if home == 0:
pass
else:
home-=1
elif ev.code == 35:
home+=1
elif ev.code == 34:
away+=1
elif ev.code == 36:
if away==0:
pass
else:
away-=1
elif ev.code == 49:
stopwatch.reset()
start_clock == 300
elif ev.code == 32:
start_clock+=1
elif ev.code == 46:
start_clock-=1
elif ev.code == 33:
start_clock+=60
elif ev.code == 18:
start_clock-=60
elif ev.code == 24:
away=00
home=00
elif ev.code == 37:
_draw_ani()
elif ev.code == 50:
if stopwatch.running:
stopwatch.stop()
else:
stopwatch.start()
except IOError:
pass
question from:
https://stackoverflow.com/questions/65647552/why-does-python-try-except-cause-slowdown 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…