要检测Python中的网络状态,您可以使用以下几种方法:
1. 使用`socket`库创建连接:
python
import socket
def check_network_status():
try:
尝试连接到一个已知的服务器
socket.create_connection(("www.google.com", 80))
return True
except OSError:
pass
return False
while True:
if check_network_status():
print("网络连接正常")
else:
print("网络连接断开")
time.sleep(1) 每秒检查一次网络状态
2. 使用`ping`命令:
python
import os
def check_network_status_with_ping():
return os.system("ping -c 1 www.google.com") == 0
while True:
if check_network_status_with_ping():
print("网络连接正常")
else:
print("网络连接断开")
time.sleep(1)
3. 使用`urllib3`库发送HTTP请求:
python
import urllib3
def check_network_status_with_http():
http = urllib3.PoolManager()
try:
http.request("GET", "https://www.google.com")
return True
except Exception as e:
return False
while True:
if check_network_status_with_http():
print("网络连接正常")
else:
print("网络连接断开")
time.sleep(1)
4. 使用`subprocess`库执行`ping`命令:
python
import subprocess
def check_network_status_with_subprocess():
return subprocess.run("ping -c 1 www.google.com", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).returncode == 0
while True:
if check_network_status_with_subprocess():
print("网络连接正常")
else:
print("网络连接断开")
time.sleep(1)
以上方法都可以用来检测网络状态,您可以根据需要选择适合您场景的方法。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/49562.html