dimanche 14 juin 2020

How to interrupt Python code at any time during execution and/or just to a different section

I have a code to control a robot that runs perfectly on his own. When I hit run, this code goes through several steps of initialization, then runs by doing some action, finally ends.

I want to control the execution of this code in a precise way. Basically, during the execution, I want to be able to interrupt the code at any time, for example by interrupting the actions and jump immediately to the end or interrupt some actions to do different ones.

The way I'm currently solving this is by defining a kind of state machine (similar to what sometimes is used in PLC programming). I have several steps inside an if statement. When one state is completed, I increment the variable and so make the execution of the next piece of code possible via an if statement. Here is some pseudo-code to explain what I mean:

sequence = 1

if sequence == 1:
    # Do something
    sequence = 2   # increment value
    while True:
        if condition:
        break

if sequence == 2:
    # Do something
    sequence = 3   # increment value
    while True:
        # do something here
        if condition:
            sequence = 10
            break
        else
            break

if sequence == 3:
    # Do something
    sequence = 4   # increment value
    while True:
        # do something here
        if condition:
            # do something here
            break

# more sequences here

if sequence == 10
    # Do something
    while True:
        if condition:
            # do something
            break

This approach is working and I'm able to achieve my goal so far. But I'm not really happy about it, there must be a better way. I'm scared that during the development, things will get harder and will encounter some limitations. One is very obvious: the different sequence must go in order or I need to copy some sequences multiple time because the code runs only downward (it's not inside a while loop)

My question: is there a way to solve this problem in python differently, in a way that is more efficient and flexible?

Aucun commentaire:

Enregistrer un commentaire