• 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的内容自己判断吧!
  • 相关阅读:
    C++内置类型对象之间的转换
    快速排序
    面试题7:用两个栈实现队列
    面试题6:重建二叉树
    poj 3264(线段树)
    poj 3038
    poj 并查集
    poj 1270(toposort)
    poj 2503(字符串)
    poj 3687(拓扑排序)
  • 原文地址:https://www.cnblogs.com/hanxing/p/7047668.html
Copyright © 2020-2023  润新知