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
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With