如何停止线程内的整个代码
我正在使用 selenium 和线程,并且我有一个函数 check_browser_running
来检查浏览器是否仍在运行:
def check_browser_running()
while True:
try:
driver.title
except WebDriverException:
print("DRIVER WAS CLOSED")
然后我在线程中运行此函数以让其他代码运行:
th = threading.Thread(target=check_browser_running)
th.start()
最后一件事是,我有一个循环函数来停止代码运行,因为如果我的代码中发生任何错误,我希望代码停止而不是退出:
def stop():
while True:
pass
我想要的是如何使用 stop( )
函数通过运行线程的函数?因为如果我在线程中调用 stop()
这不会停止主代码。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以执行以下操作:(推荐)
在运行 while 循环时使用变量作为标志,您可以将其设置为 false。结束循环。
或者是一个更俗气的解决方案,你只需获取 python 程序的 pid 并杀死它。
无论您是否从线程中调用它,这都会杀死整个程序。
Either you can do something like this: (Recommended)
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.
Which will kill the entire program regardless if you call it from withing a thread.