python - 继续运行在 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
解决方案
推荐阅读
- microsoft-graph-api - 如果地址包含特殊字符,如何更新工作表范围?
- javascript - 如何使用谷歌存储中的图像修复 Microsoft Azure 计算机视觉中的 InvalidImageFormat?
- javascript - 将一个文本框的值复制到另一个文本框返回 null
- c# - Azure VirtualNetworkGatewayConnection 没有 ExpressRoute ConnectionType 的 ConnectionStatus
- powershell - 命令行中的 PowerShell 参数、单引号和双引号
- c++ - 为什么我不能在 C++ 中将对象插入到地图中
- python - 如何利用 Django 用户模型的内置名字和姓氏功能?
- ruby-on-rails - 表单(文件)上传后显示警报
- java - 春季如何每30分钟更新一次缓存?
- java - 在 NetBeans 中设置类路径