0

我正在修改一个通过串行连接发送和接收数据的重要程序(有 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()
4

0 回答 0