码迷,mamicode.com
首页 > 其他好文 > 详细

ping

时间:2017-06-19 13:12:27      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:try   blog   shel   main   自动   alt   stdin   pipe   爬虫   

# -*- 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的内容自己判断吧!

ping

标签:try   blog   shel   main   自动   alt   stdin   pipe   爬虫   

原文地址:http://www.cnblogs.com/hanxing/p/7047668.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!