Python 捕获所有异常,然后关闭Com端口
我正在修改一个非常重要的程序(有两个线程),它通过串行连接发送和接收数据。通常,由于意外错误(或我的代码错误:),程序终止,COM端口保持打开状态。在下一次运行时,我在尝试打开COM端口时出错。我想尝试完全缓解这种情况,并确保无论在何处发生错误,都会运行一段故障保护代码并尝试关闭COM端口 我可以将整个程序包装在一个try/except/finally块中吗?还是必须对每个线程/类进行微管理? 当做 西蒙 如果有帮助,请编辑代码Python 捕获所有异常,然后关闭Com端口,python,windows,python-2.7,Python,Windows,Python 2.7,我正在修改一个非常重要的程序(有两个线程),它通过串行连接发送和接收数据。通常,由于意外错误(或我的代码错误:),程序终止,COM端口保持打开状态。在下一次运行时,我在尝试打开COM端口时出错。我想尝试完全缓解这种情况,并确保无论在何处发生错误,都会运行一段故障保护代码并尝试关闭COM端口 我可以将整个程序包装在一个try/except/finally块中吗?还是必须对每个线程/类进行微管理? 当做 西蒙 如果有帮助,请编辑代码 #usual python imports etc ... boa
#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()
如果你展示了代码的相关部分,这会有所帮助——否则,这是一种猜测,就像你可以回答
try/except/finally
问题一样——通过尝试。是的,我可以“尝试”但是我正在努力学习progran inard:)而且我不是嵌套异常处理专家,因此正在寻找一些节省时间的指导:)当前代码(我没有编写)似乎可以很好地处理Ctrl-C,但不能处理其他异常(或者我称之为-编码中的错误:))