Note that there are some explanatory texts on larger screens.

plurals
  1. POCatch all exceptions and then close Com port
    text
    copied!<p>I'm modifying a non-trivial program (with 2 threads) that sends and receives data down a serial connection. Quite often, because of an unexpected error (or bad coding on my part :) ) the program terminates and the COM port is left open. On next subsequent run, I then get an error when attempting to open the COM port. I would like to try and full mitigate against this happening and make sure that no matter where an error occurs - a piece of failsafe code is run and attempts to close the COM port.</p> <p>Can I get away with wrapping the whole program in one try/except/finally block or will I have to micro-manage each thread/class? regards Simon</p> <p>Edited code if that helps</p> <pre><code>#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) &gt; 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 &gt; 0) or (motorB &gt; 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() </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload