删除atexit tracebakc - atextit循环时不应该

时间:2013-11-26 13:21:35

标签: python loops raspberry-pi

如何从命令输出中删除引用,如何在atexit函数中停止此循环?

!/usr/bin/python

import time, atexit, sys
import RPi.GPIO as GPIO

#16 = Motor 1 - Forward
#18 = Motor 1 - Back
#11 = Motor 2 - Forward
#13 = Motor 2 - Back
#6  = Ground

GPIO.setmode(GPIO.BOARD)

GPIO.setup(16, GPIO.OUT)
GPIO.setup(18, GPIO.OUT)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)

def exit_handler():
   GPIO.cleanup()
   print 'STOPPED'

while True:
   GPIO.output(11, True)
   GPIO.output(16, True)
    print "Forward"
    time.sleep(5)
    atexit.register(exit_handler)

似乎工作正常,并在我的Pi 上运行电机控制器(只是 - 由于狡猾的接线head

但是当我运行它时,我将其作为输出:

[wilf@Pi MovementCommands]$ 1/forward.py
Forward
Forward
Forward
Forward
Forward
Forward
Forward
Forward
Forward
Forward
Forward
Forward
Forward
Forward
Forward
Forward
Forward
Forward
Forward
^CTraceback (most recent call last):
  File "1/forward.py", line 17, in <module>
    time.sleep(5)
KeyboardInterrupt
STOPPED
STOPPED
STOPPED
STOPPED
STOPPED
STOPPED
STOPPED
STOPPED
STOPPED
STOPPED
STOPPED
STOPPED
STOPPED
STOPPED
STOPPED
STOPPED
STOPPED
STOPPED
[wilf@Pi MovementCommands]$ 

由于某种原因,似乎循环exit_handler几乎与主位循环一样多次 - 如何阻止它执行此操作 - 如果它已经运行了一段时间,它可能需要很长时间才能退出,因为它循环清理命令。 (主位不必循环,但它可以作为视觉指示,它正在做某事 - 我可能只是循环print位...)

我似乎也无法停止显示atexit的追溯,而无需使用except KeyboardInterrupt。无论如何这都是有用的,但我以后可能想通过从Bash脚本运行它来自动化它(是的,我可以将它集成到它中,但我不想)

1 个答案:

答案 0 :(得分:4)

每次循环迭代时,您都会重新注册atexit处理程序。 Python将函数调用为已注册的次数。

只需注册功能。您也无需在sys.exit(0)功能中致电atexit退出您的计划。

更正程序:

import time, atexit
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)

def exit_handler():
    GPIO.cleanup()
    print 'STOPPED'

atexit.register(exit_handler)

while True:
    GPIO.output(11, True)
    GPIO.output(16, True)
    print "Forward"
    time.sleep(5)

或者,捕获KeyboardInterrupt并在异常处理程序中清理:

import time
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BOARD)

try:
    while True:
        GPIO.output(11, True)
        GPIO.output(16, True)
        print "Forward"
        time.sleep(5)
except KeyboardInterrupt:
    pass  # silence the interrupt
finally:
    GPIO.cleanup()
    print 'STOPPED'

finally阻止调用GPIO.cleanup(),无论发生什么异常,except KeyboardInterrupt只会使键盘中断异常静音。

请注意,回溯从未在atexit()函数中,这是程序退出的原因以及为什么要调用atexit()。换句话说,异常在atexit()函数调用之前。