python检测网络连接状态的几种方法

第一种

import socket

ipaddress = socket.gethostbyname(socket.gethostname())

if ipaddress == '127.0.0.1':
    return False
else:
    return True

缺点:如果IP是静态配置,无法使用,因为就算断网,返回的也是配置的静态IP

第二种

import urllib3

try:
    http = urllib3.PoolManager()
    http.request('GET', 'https://baidu.com')
    return True
exception as e:
    return False

第三种

import os

ret = os.system("ping baidu.com -n 1")
return True if res == 0 else False

第四种

import subprocess
import os


ret = subprocess.run("ping baidu.com -n 1", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
return True if ret.returncode == 0 else False

你可能感兴趣的:(python,python)