在Python中,判断网络通断可以通过以下几种方法:
1. 使用`os.system`执行`ping`命令:
import os
def is_pingable(ip):
response = os.system(f"ping -c 1 {ip}") 执行ping命令
return response == 0 返回0表示连通,非0表示不连通
ip = "www.google.com"
if is_pingable(ip):
print("网络连通")
else:
print("网络不连通")
2. 使用`subprocess`模块执行`ping`命令:
import subprocess
def ping_check(ip):
cmd = f"ping {ip} -n 2"
exit_code = subprocess.call(cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return exit_code == 0
if ping_check("8.8.8.8"):
print("网络连通")
else:
print("网络不连通")
3. 使用`socket`库尝试连接到已知的服务器:
import socket
def check_internet_connection():
try:
创建一个socket对象并尝试连接到www.baidu.com的80端口
socket.create_connection(("www.baidu.com", 80))
return True
except OSError:
return False
if check_internet_connection():
print("网络连接正常")
else:
print("无法连接到网络")
4. 使用HTTP请求测试网络通断(需要网络能够访问外部HTTP服务):
import requests
def check_http_connection(url="http://www.google.com"):
try:
response = requests.get(url, timeout=5)
return response.status_code == 200
except requests.exceptions.RequestException:
return False
if check_http_connection():
print("网络连通")
else:
print("网络不连通")
以上方法都可以用来检测网络是否连通,选择哪一种取决于你的具体需求和环境。需要注意的是,执行系统命令可能会受到操作系统权限的限制,而且不同操作系统下的命令可能有所不同。