要检测Python中的网络状态,您可以使用以下几种方法:
1. 使用`socket`库创建连接:
import socketdef check_network_status():try:尝试连接到一个已知的服务器socket.create_connection(("www.google.com", 80))return Trueexcept OSError:passreturn Falsewhile True:if check_network_status():print("网络连接正常")else:print("网络连接断开")time.sleep(1) 每秒检查一次网络状态
2. 使用`ping`命令:
import osdef check_network_status_with_ping():return os.system("ping -c 1 www.google.com") == 0while True:if check_network_status_with_ping():print("网络连接正常")else:print("网络连接断开")time.sleep(1)

3. 使用`urllib3`库发送HTTP请求:
import urllib3def check_network_status_with_http():http = urllib3.PoolManager()try:http.request("GET", "https://www.google.com")return Trueexcept Exception as e:return Falsewhile True:if check_network_status_with_http():print("网络连接正常")else:print("网络连接断开")time.sleep(1)
4. 使用`subprocess`库执行`ping`命令:
import subprocessdef check_network_status_with_subprocess():return subprocess.run("ping -c 1 www.google.com", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).returncode == 0while True:if check_network_status_with_subprocess():print("网络连接正常")else:print("网络连接断开")time.sleep(1)
以上方法都可以用来检测网络状态,您可以根据需要选择适合您场景的方法。
