1

So I have a function I want to run, however this function connects to a serial device, if the device was not turned off correctly it will return an error if you try to run such a function. Since I only need to run the function once all I want is to

try
   #function
except
   #function to turn off the device
   #try again

not within a loop since I want to just run it once and keep going, is this possible in python without using a loop?

6
  • Could you write a function to check if the connection work and run it before you try to run your current function? Commented Oct 17, 2020 at 18:52
  • 1
    Why not within a loop? Do you only want to try twice maximum? Commented Oct 17, 2020 at 18:54
  • There is, but the function will work to check the connection, since the device is alive, but when you try to poll data from the device it will give a byte mismatch, the only fix is to restart the device and try again. Commented Oct 17, 2020 at 18:55
  • I guess what's confusing is that you say you only want to run it once, but there is this "try again" comment. Which is it? Commented Oct 17, 2020 at 18:58
  • 1
    Replace #try again with #function? Commented Oct 17, 2020 at 19:04

1 Answer 1

2

Instead of using a loop, since you explicitly want to use this logic maximum twice and be exception safe, just wrap everything into a function which returns the success status and call it twice:

def connect_and_do_stuff_safe() -> bool:
    try
       # function
       return True
    except
       # function to turn off the device
       return False

if not connect_and_do_stuff_safe():
    # Maybe you need to do some start related logic in between, anyway you need it here
    connect_and_do_stuff_safe()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.