捕获所有异常,然后关闭Com端口

时间:2013-01-19 16:14:58

标签: python windows python-2.7

我正在修改一个通过串行连接发送和接收数据的非平凡程序(有2个线程)。很多时候,由于意外错误(或我的编码错误:))程序终止并且COM端口保持打开状态。在下一次运行时,我在尝试打开COM端口时出现错误。我想尝试并完全缓解这种情况,并确保无论发生何种错误 - 运行一段故障安全代码并尝试关闭COM端口。

我可以在一个try / except / finally块中包装整个程序,还是我必须对每个线程/类进行微观管理? 问候 西蒙

编辑代码,如果有帮助

#usual python imports etc
...
board = pyfirmata.Arduino("COM26", baudrate=57600) # Replace COM26 with your Arduino port
...
#vairable initilistation


class MyError(Exception):
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return repr(self.value)

class ScratchSender(threading.Thread):
    #one of the threads


class ScratchListener(threading.Thread):
    #the other thread

#bit of code

def cleanup_threads(threads):
    for thread in threads:
        thread.stop()

    for thread in threads:
        thread.join()

if __name__ == '__main__':
    if len(sys.argv) > 1:
        host = sys.argv[1]
    else:
        host = DEFAULT_HOST

cycle_trace = 'start'
while True:

    if (cycle_trace == 'disconnected'):
        cleanup_threads((listener, sender))
        time.sleep(1)
        cycle_trace = 'start'

    if (cycle_trace == 'start'):
        listener = ScratchListener(the_socket)
        sender = ScratchSender(the_socket)
        cycle_trace = 'running'
        listener.start()
        sender.start()

    # wait for ctrl+c
    try:
        #bit of code
        #print "motorA val:" , motorA

        if ((motorA > 0) or (motorB > 0)):
            #do something
        else:
            #just let the threads do their stuff in the background
            time.sleep(0.1)
    except KeyboardInterrupt:
        cleanup_threads((listener,sender))
        board.exit()
        sys.exit()

0 个答案:

没有答案