Python使用循环检查internet连接
我试着写一个简单的脚本,如果没有互联网连接,它会不断迭代Python使用循环检查internet连接,python,loops,web,Python,Loops,Web,我试着写一个简单的脚本,如果没有互联网连接,它会不断迭代 #!/usr/bin/python3 # -*- coding: utf-8 -*- import urllib.request, time; while True: try: file = urllib.request.urlopen('http://google.com'); print('Connect'); break; except urllib.error.U
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import urllib.request, time;
while True:
try:
file = urllib.request.urlopen('http://google.com');
print('Connect');
break;
except urllib.error.URLError:
print('No connect');
time.sleep(3);
当互联网断开连接时,它应该继续迭代。但是当我连接到web时,break表达式不会触发。重要的是,如果存在internet连接,我希望脚本中断循环,而无需重新启动脚本。我使用的是:
import requests,time
def check():
try:
requests.get('https://www.google.com/').status_code
print('online')
time.sleep(5)
check_again()
except:
print('offline')
time.sleep(5)
def check_again():
try:
requests.get('https://www.google.com/').status_code
print('online')
time.sleep(5)
check()
except:
print('offline')
time.sleep(5)
check()
check()
你的代码在我的机器上运行良好。你能告诉我当你连接时发生了什么吗?同时更新您工作的环境。虽然可能性很小,但由于某些代理设置(在ubuntu中已经看到),终端无法访问internet。我使用fedora,当我从终端启动脚本时,键入“python script.py”连接internet,就会触发break语句。但是,当我断开与internet的连接并启动脚本时,当我再次连接到web并同时启动脚本后,break语句不起作用,在循环中终端打印“No connect”字符串。请注意:在python中,语句末尾不需要分号。这是我在javascript中的习惯:)我想不出任何东西。这看起来像是一个特定于系统的问题。我会尝试使用“”。它是google.com的ip地址,避免dns查找