Python Forum
Stopping a loop in another file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Stopping a loop in another file (/thread-27616.html)



Stopping a loop in another file - catosp - Jun-13-2020

Hello

File1.py:
import File2

while True:
    a = input()
    if a == "start":
        threading.Thread(target = File2.func()).start()
    if a == "stop":
        #stop function File2.func
File2.py:
def func():
    while True:
        #do stuff
How can i stop the running of func() in File2? I have no idea! I cannot pass a stop variable to func() because the variable are one time loaded at the beggining of the func() running.
Thank you!


RE: Stopping a loop in another file - Yoriz - Jun-13-2020

Maybe this will suffice

File1.py:
import File2
 
while True:
    a = input()
    if a == "start":
        File2.run_func = True
        threading.Thread(target = File2.func).start()
    if a == "stop":
        #stop function File2.func
        File2.run_func = False
File2.py:
run_func = True

def func():
    while run_func:
        #do stuff
Edit: I removed the () from File2.func as the thread should call the function


RE: Stopping a loop in another file - catosp - Jun-13-2020

So, the run_func is a global variable in File2? And by writing File2.run_func can acces the global variable from that File2?


RE: Stopping a loop in another file - catosp - Jun-14-2020

@Yoriz,thank you!


RE: Stopping a loop in another file - catosp - Jun-15-2020

(Jun-13-2020, 06:12 PM)Yoriz Wrote: Maybe this will suffice

File1.py:
import File2
 
while True:
    a = input()
    if a == "start":
        File2.run_func = True
        threading.Thread(target = File2.func).start()
    if a == "stop":
        #stop function File2.func
        File2.run_func = False
File2.py:
run_func = True

def func():
    while run_func:
        #do stuff

Is not working, i cannot update the value of File2.run_func into False. If I do:
print(File2.run_func)
after run the line:
File2.run_func = False
the output is:
Output:
True
instead of False



EDIT: It works! Sorry, my mistake!Thank you all!