首页 > 解决方案 > 继续运行在 while 循环中调用的函数

问题描述

我正在尝试进行 ping 测试,如果 ping 成功,则调用一个函数并运行该函数,直到 ping 不成功。如果调用该函数后ping不通,则停止该函数运行,直到ping ping成功。

在此处输入图像描述

到目前为止,这是我尝试过的。ping 测试运行良好,但是 while 循环在运行函数中的所有代码后退出自动化函数(关闭浏览器)。我想继续运行功能并仅在 ping 失败之前停止它。

import urllib
from selenium import webdriver


def ping(host="8.8.8.8", port=53, timeout=3):
    from urllib import request
    try:
        urllib.request.urlopen('http://google.com', timeout=5)
        return True
    except:
        return False

def automation():
     url1 = "https://google.com"
     driver=webdriver.Chrome()
     driver.get(url1)



run_once = 0
while True:
        if ping():
                if run_once == 0:
                        automation()
                        run_once = 1
        else: 
                print("ping unsuccessful")
                run_once = 0

更新

感谢用户@questioning 的回答,这是对我有用的解决方案。我还使用了“drive.refersh”来节省电池寿命,因为我的用例涉及一个摄像头,并且在 while 循环之前调用驱动程序使浏览器和摄像头即使在连接丢失后也能继续运行。

import urllib
from selenium import webdriver

Global driver
driver=webdriver.Chrome()

def ping(host="8.8.8.8", port=53, timeout=3):
    from urllib import request
    try:
        urllib.request.urlopen('http://google.com', timeout=5)
        return True
    except:
        return False

def automation():
     url1 = "https://google.com"
     driver=webdriver.Chrome()
     driver.get(url1)



run_once = 0
reload_once = 0
while True:
        if ping():
                if run_once == 0:
                        automation()
                        run_once = 1
        else: 
                print("ping unsuccessful")
                run_once = 0
                if reload_once == 0:
                        drive.refersh()
                        reload_once == 1

标签: pythonpython-3.xseleniumwhile-loopautomation

解决方案


推荐阅读