I am using selenium and threading, and I have a funcion check_browser_running
to check if the browser is still running or not:
def check_browser_running()
while True:
try:
driver.title
except WebDriverException:
print("DRIVER WAS CLOSED")
then I run this function in a thread to let other code running:
th = threading.Thread(target=check_browser_running)
th.start()
Last thing is, I have a loop function to stop the code from running, because if any error happened in my code, I want the code to stop instead of exiting:
def stop():
while True:
pass
What I want is that how can I stop the code from running using the stop()
function through a function that is running a thread?? Because if I called stop()
in a thread this will not stop the main code.
CodePudding user response:
Either you can do something like this: (Recommended)
import threading
running = True
def thread():
global running
while running:
if(some_event):
stop()
def stop():
global running
running = False
th = threading.Thread(target=thread)
th.start()
Where you run a while loop with a variable as a flag you can set to false. To end the loop.
Or a tackier solution where you just get the pid of the python program and kill it.
import os, signal
def stop():
os.kill(os.getpid(), signal.SIGTERM)
Which will kill the entire program regardless if you call it from withing a thread.