我正在使用Raspberry Pi
和库gpiozero
。我初始化连接到板上的按钮,并希望在按住按钮时处理事件。为此,我尝试使用异常。下面是代码:
from signal import pause
from gpiozero import Button
class pressException( Exception ):
pass
def raisePressException():
raise pressException( 'Button held' )
push = Button( 5 )
push.when_held = raisePressException
try:
pause()
except pressException:
print( 'Exception accepted' )
但是,一旦我按住按钮,异常块就不会捕获此异常,因为它不是以某种方式从pause()内部发出的。终端输出如下:
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/threading.py", line 754, in run
self.__target(*self.__args, **self.__kwargs)
File "/usr/lib/python2.7/dist-packages/gpiozero/mixins.py", line 460, in held
parent._fire_held()
File "/usr/lib/python2.7/dist-packages/gpiozero/mixins.py", line 364, in _fire_held
self.when_held()
File "test.py", line 8, in raisePressException
raise pressException( 'Button held' )
pressException: Button held
如何捕获此异常?还是有另一种方法可以在初始化Button
的同一范围内处理此类事件?
答案 0 :(得分:1)
尝试做这样的事情,
from signal import pause
from gpiozero import Button
class pressException( Exception ):
pass
def raisePressException():
raise pressException( 'Button held' )
try:
push = Button( 5 )
push.when_held = raisePressException()
pause()
except pressException:
print( 'Exception accepted' )
发生这种情况的原因是您在try和except之外引发了错误,因此它无法捕获该错误,并且即使您尝试捕获自己的代码,您也在循环中调用了自己的raise函数,最终将陷入递归循环
答案 1 :(得分:0)
从这行上升的
raise pressException( 'Button held' )
,因此您必须在右边用try ... except
换行,
那一个,或更高级别,您在其中运行raisePressException
顺便说一句,这毫无意义:
def raisePressException():
raise pressException( 'Button held' )
push = Button( 5 ) # not able to be reached or achieved.
push.when_held = raisePressException
只需使用
raise pressException( 'Button held' )