Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, How to swap between multiple infinite loops?

Could someone please point me in the right direction?

I am trying to swap between multiple infinite control loops within python. I need to kill a loop and then select a different loop upon request from an outside source(hopefully web interface), not based on an internal condition. I understand this is a vague question but I need a general point in the right direction to get me started, I have looked at exceptions, signals and threading but I am struggling to find what would be the "correct" way to do this.

Please note, I work in electronics not programming so sorry if this sounds stupid. Also if this is completely the wrong way to go about the problem could someone advise me on the correct method.

I can provide more info/explanation if someone can help me and post code if needed but I think it's pretty irrelevant at the moment due to the vagueness of the question.

Thanks

like image 304
ironcrow Avatar asked Apr 20 '26 21:04

ironcrow


2 Answers

I'm guessing you have two (or more) procedures you want to run repeatedly and allow them to be changed when the user selects a new condition. I would take advantage of Python having functions as objects and so something like this:

def f1():
    # do something
def f2():
    # do something else

func_to_run = {"user_input1": f1, "user_input2": f2}

while True:
    user_input = get_any_new_input()  # however you want to get your user input
    func_to_run[user_input]()

Edit: As Keith mentioned in the comments, get_any_new_input needs to be non-blocking. I would do this via threading. The web interface should be on a separate thread from the loops, but share a control object that the web interface will set. This could be a table in a database if you have that available. It might look something like this if you use your own lock:

L = threading.Lock()  # Shared by web ui
user_response = 'data set by web ui'
last_input = 'user_input1'

def get_any_new_input(L, last_input, user_response):
    if L.acquire([False]):
        last_input = user_response
    return last_input
like image 73
munk Avatar answered Apr 23 '26 09:04

munk


The easiest way is probably just read some file which controls your loops ...

while True:
    #loop1
    while True:
       #do something
       with open("some.file") as f:
            if f.read() == "loop2":
                break
     #loop2
     while True:
        #do something
        with open("some.file") as f:
            if f.read() == "loop1":
                break

then just put which loop you want in "some.file" (however you want ... web interface etc)

like image 20
Joran Beasley Avatar answered Apr 23 '26 11:04

Joran Beasley