I want to exit a threading function from inside another function. Here is an example:
from threading import *
from time import *
import keyboard
def ExampleFunction():
while True:
print('The Example function is running.') # do something in a loop
sleep(1)
def ExitFunction():
print('ExitFunction was called.')
keyboard.wait('f8') # wait until f8 was pressed
# do whatever it takes to exit the ExampleFunction
if __name__ == '__main__':
Thread(target=ExampleFunction).start()
Thread(target=ExitFunction).start()
You could use global variable running = True and in ExampleFunction use while running: and in other function use running = False
from threading import *
from time import *
import keyboard
# global variable
running = True
def ExampleFunction():
print("ExampleFunction: start")
while running:
#print('The Example function is running.') # do something in a loop
sleep(1)
print("ExampleFunction: exit")
def ExitFunction():
global running # inform function to use global variable instead of local variable
print('ExitFunction: start')
keyboard.wait('f8') # wait until f8 was pressed
running = False
print('ExitFunction: sleep')
sleep(5) # simulate other code
print('ExitFunction: end')
if __name__ == '__main__':
t1 = Thread(target=ExampleFunction)
t1.start()
t2 = Thread(target=ExitFunction)
t2.start()
t1.join() # wait for end of `ExampleFunction`
t2.join() # wait for end of `ExitFunction`
The same way you can use threading.Event and it doesn't need to use global running because it will not use = inside ExitFunction
from threading import *
from time import *
import keyboard
# global variable
running = Event()
running.set() # set `True`
def ExampleFunction():
print("ExampleFunction: start")
while running.is_set():
#print('The Example function is running.') # do something in a loop
sleep(1)
print("ExampleFunction: exit")
def ExitFunction():
print('ExitFunction: start')
keyboard.wait('f8') # wait until f8 was pressed
running.clear() # set `False`
print('ExitFunction: sleep')
sleep(5) # simulate other code
print('ExitFunction: end')
if __name__ == '__main__':
t1 = Thread(target=ExampleFunction)
t1.start()
t2 = Thread(target=ExitFunction)
t2.start()
t1.join() # wait for end of `ExampleFunction`
t2.join() # wait for end of `ExitFunction`
You may even send Event as argument in Thread
from threading import *
from time import *
import keyboard
# global variable
running = Event()
running.set() # set `True`
def ExampleFunction(running):
print("ExampleFunction: start")
while running.is_set():
#print('The Example function is running.') # do something in a loop
sleep(1)
print("ExampleFunction: exit")
def ExitFunction(running):
print('ExitFunction: start')
keyboard.wait('f8') # wait until f8 was pressed
running.clear() # set `False`
print('ExitFunction: sleep')
sleep(5) # simulate other code
print('ExitFunction: end')
if __name__ == '__main__':
t1 = Thread(target=ExampleFunction, args=(running,)) # `args` needs `,` inside `()` to create `tuple`
t1.start()
t2 = Thread(target=ExitFunction, args=(running,)) # `args` needs `,` inside `()` to create `tuple`
t2.start()
t1.join() # wait for end of `ExampleFunction`
t2.join() # wait for end of `ExitFunction`
BTW:
If you would use multiprocessing then you could kill() other process.
Related
from time import sleep
def foo():
sleep(3)
return True
while True:
print('Running')
if foo() == True:
print('Finished.')
break
I want to keep printing "Running" but when foo returns True I want to print "Finished" (once) and break out of the loop.
I have tried the above but it prints "Running" just once and waits for foo to finish executing and then continues.
import threading
from time import sleep
flag = True
def foo()->None:
global flag
sleep(1)
flag = False
if __name__ == "__main__":
t1 = threading.Thread(target=foo)
t1.start()
while flag:
print('Running')
print('Finished')
Because you worked with only one thread, when you call the function the main stops until the function returns.
Therefore, if you want the main code and the function to run together, you have to work with threads.
So, after trying somethings I found 2 solutions, of my own question, that uses threading.
1. Modifies the foo function
from time import sleep
from threading import Thread
x = True
def foo():
sleep(3)
global x
x = False
print('finished')
def printing():
while x:
print('Running')
foo_thread = Thread(target=foo)
foo_thread.start()
printing_thread = Thread(target=printing)
printing_thread.start()
2. Uses decorator to keep foo unchanged
from time import sleep
from threading import Thread
x = True
def sets_true(func):
def wrapper():
returned_value = func()
global x
x = False
print('finished')
return wrapper
#sets_true
def foo():
sleep(3)
return True
def printing():
while x:
print('Running')
foo_thread = Thread(target=foo)
foo_thread.start()
printing_thread = Thread(target=printing)
printing_thread.start()
I have this code:
from pynput.keyboard import Key, Listener
import logging
import time as t
def stop():
print('Stop keylogging for a while')
def main():
logging.basicConfig(filename=('keylog.txt'), level=logging.DEBUG, format=" %(asctime)s - %(message)s")
def on_press(key):
logging.info(str(key))
with Listener(on_press=on_press) as listener :
listener.join()
main()
stop()
It writes your typed letters in a file, but I want to stop it for a while do another function and again start writing typed letters
So I just need to stop this function after 1 hour:
main()
Start this function:
stop()
And again start this function:
main()
And I want it to works in a loop
Easier:
def stop():
print('Stop')
def main():
while True:
print("Working")
while True:
# Again start main() function
main()
# Do stop() function after 10 seconds
stop()
When I start this code main() works infinitely, I want to stop it but after 10 seconds, and start stop() function, than again go to the main() function
from threading import Thread
import time
def main():
print('Working')
def stop():
print('stopped')
while 1:
t = Thread(target=main)
t.start()
time.sleep(6)
t.join()
stop()
you can use thread for it
I need run 3 or 5 threads approx, this threads monitoring some activities in the OS. Because of this, the main program must be running in background. I've read many examples and explanations, but I'm not clear yet how to launch threads and main program in the background and after that, how to control them.
I start threads in daemon mode from main program:
import threading
import time
def fun1():
while True:
print("Thread 1")
time.sleep(1)
def fun2():
while True:
print("Thread 2")
time.sleep(1)
def fun3():
while True:
print("Thread 3")
time.sleep(1)
def main():
thread1 = threading.Thread(target=fun1)
thread1.daemon = True
thread1.start()
thread2 = threading.Thread(target=fun2)
thread2.daemon = True
thread2.start()
thread3 = threading.Thread(target=fun3)
thread3.daemon = True
thread3.start()
if __name__ == '__main__':
try:
main()
while True:
print("------------")
print("Main program")
print("------------")
time.sleep(3)
except (KeyboardInterrupt, SystemExit):
print("Terminated")
and after that I run the main program in background with (I'm not sure that this is the best way to do it for what I want to achieve):
python daemon_thread.py &
How control the threads after main program initialization if I need stop a specific thread, change its state, or whatever? How to access a specific thread or the main program?
I understand now how to do, to resume the problem: I have a main program running in background and this main program have some threads. But I want with another script or program stop the main program with the threads safetly and in some cases pause and resume threads.
I didn't have a correctly concept about how to use the Threads. I can stop or send signal to this threads from main program How?,with a database or config file.
I updated my project with this changes:
import threading
import time
import sqlite3
def fun1(stop_event1):
while not stop_event1.is_set():
print("Thread 1")
time.sleep(1)
def fun2(stop_event2):
while not stop_event2.is_set():
print("Thread 2")
time.sleep(1)
def fun3(stop_event3):
while not stop_event3.is_set():
print("Thread 3")
time.sleep(1)
def main():
stop_event1 = threading.Event()
thread1 = threading.Thread(target=fun1, args=(stop_event1,))
thread1.daemon = True
thread1.start()
stop_event2 = threading.Event()
thread2 = threading.Thread(target=fun2, args=(stop_event2,))
thread2.daemon = True
thread2.start()
stop_event3 = threading.Event()
thread3 = threading.Thread(target=fun3, args=(stop_event3,))
thread3.daemon = True
thread3.start()
while True:
print("------------")
print("Main program")
print("------------")
time.sleep(3)
if alive_main():
print("Finish Threads")
stop_event1.set()
stop_event2.set()
stop_event3.set()
print("Bye")
break
def alive_main():
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('SELECT alive_main FROM config')
row = c.fetchone()
if row[0] == 1:
return True
else:
return False
if __name__ == '__main__':
try:
main()
except (KeyboardInterrupt, SystemExit):
print("Terminated")
If I want change with another class or script the state of my threads, I just change config table in my database y this take effect in the Threads, from main function. In this example if I stop correctly my threads and program just I update table, that's it.
sqlite> UPDATE config SET alive_main = 1;
I need read about Signals and Condition Objects to complement correctly Threads uses.
Thanks everyone!
I am new to python I have very little knowledge about threads in python. Here is my sample code.
import threading
from threading import Thread
import time
check = False
def func1():
print ("funn1 started")
while check:
print ("got permission")
def func2():
global check
print ("func2 started")
time.sleep(2)
check = True
time.sleep(2)
check = False
if __name__ == '__main__':
Thread(target = func1).start()
Thread(target = func2).start()
What I want is to see see "got permission" as the output. But with my current code it is not happening. I assume that the func1 thread is closed before func2 changes the check value to True.
How can I keep func1 alive?
I have researched on the internet but I could not found a solution.
Any help would be appreciated.
Thank you in advance!
The problem here is that func1 performs the check in the while loop, finds it is false, and terminates. So the first thread finishes without printing "got permission".
I don't think this mechanism is quite what you are looking for. I would opt to use a Condition like this,
import threading
from threading import Thread
import time
check = threading.Condition()
def func1():
print ("funn1 started")
check.acquire()
check.wait()
print ("got permission")
print ("funn1 finished")
def func2():
print ("func2 started")
check.acquire()
time.sleep(2)
check.notify()
check.release()
time.sleep(2)
print ("func2 finished")
if __name__ == '__main__':
Thread(target = func1).start()
Thread(target = func2).start()
Here the condition variable is using a mutex internally to communicate between the threads; So only one thread can acquire the condition variable at a time. The first function acquires the condition variable and then releases it but registers that it is going to wait until it receives a notification via the condition variable. The second thread can then acquire the condition variable and, when it has done what it needs to do, it notifies the waiting thread that it can continue.
from threading import Thread
import time
check = False
def func1():
print ("funn1 started")
while True:
if check:
print ("got permission")
break
def func2():
global check
print ("func2 started")
time.sleep(2)
check = True
time.sleep(2)
check = False
if __name__ == '__main__':
Thread(target = func1).start()
Thread(target = func2).start()
func1 must be like this
def func1():
print("func1 started")
while True:
if check:
print("got permission")
break
else:
time.sleep(0.1)
I have three files:
helper.py
from globalvariables import *
global exit_signal
global exited_signal
def helperstart():
global exited_signal
while True:
if exit_signal is True:
exited_signal = True
print ('Exiting from helper thread')
return
main.py
from globalvariables import *
import threading
import helper
global exit_signal
global exited_signal
def mainstart():
global exit_signal
helper_thread = threading.Thread(target = helper.helperstart)
input ('Press <enter> to start the thread')
helper_thread.start()
input ('Press <enter> to end the thread')
exit_signal = True
# check if helper has exited
if exited_signal is True:
print ('Helper exited successfully')
if __name__ == '__main__':
mainstart()
globalvariables.py
exit_signal = False
exited_signal = False
From main.py, the value of exit_signal should be edited to True. This should make the helper thread exit. But it is not exiting. I've tried printing the value of exit_signal from helperstart() function and it keeps showing as False. So, the main.py isn't editing the variable properly. Please help me figure out why.