这是在python中检查Internet连接的好方法吗?据我所知,我不应该使用纯粹的例外。
import urllib.request
import time
def connect():
try:
urllib.request.urlopen('http://google.com')
return True
except:
return False
while True:
if connect(): # checks if there is Internet connection
print('Connected to Internet.')
else:
print("No Internet.")
time.sleep(10)
continue # Loops to beginning and checks for Internet connection again
main_function()
试试这个代码:
import socket
ip = socket.gethostbyname(gethostname)
if ip="127.0.0.1":
print("Not Connected")
else:
print("Connected!")