ping

# -*- coding:utf-8 -*-
import os
import time
import datetime
import subprocess
retrytime = 0


def mprint(str):
    print "#############   " + str.decode('utf-8') + "   #############"

def mNetPing(pingUrl):  #  mNetPing('jd.com')
    global retrytime
    print "开始检查网络状况,请耐心等待".decode('utf-8')
    p = subprocess.Popen(["ping.exe", pingUrl],
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         shell=True)
    out = p.stdout.read()
    # print out
    out = out.decode('GB2312').encode('utf-8')  # 转成utf8方便比较

    if "(0% 丢失)" in out:#不能用 0% 丢失  因为100% 丢失包含 0% 丢失  刚好0的左边是10  所以改成(0%是可以的 加个括号
        mprint("#############################网络正常#############################")
    elif "(100% 丢失)" in out:#网线连接正常 无法访问域名
        mprint("#####################域名故障,请检查电脑能否访问 www.jd.com##################")
        os.system("pause")
        mNetPing(pingUrl)
    elif "找不到主机" in out:#网线断开
        mprint("###########################请检查本机网络是否正常连接 3秒后自动重新检测###########################")
        time.sleep(3)
        retrytime = retrytime + 1
        #os.system("pause")
        mprint(""+str(retrytime)+"次重试")
        mNetPing(pingUrl)
    else:#请求超时
        mprint("网络不稳定 是否继续?按任意键继续")

        os.system("pause")
        # print chardet.detect(out.decode('GB2312').encode('utf-8'))
        # mlost="100% 丢失".decode('utf-8')
        # print chardet.detect(mlost)
        # print mlost
if __name__ == '__main__':
    # os.system("pause")
    print time.localtime()#<type 'time.struct_time'>
    print time.strftime('%Y-%m-%d', time.localtime(time.time()))
    print time.strftime('%H:%M:%S', time.localtime(time.time()))
    print time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    mNetPing('jd.com')
    mprint("程序测试结束")

我在京东爬虫中用的到判断网络状况的代码,核心代码如下:

    p = subprocess.Popen(["ping.exe", pingUrl],
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE,
                         shell=True)
    out = p.stdout.read()

再根据out的内容自己判断吧!
原文地址:https://www.cnblogs.com/hanxing/p/7047668.html