随笔 - 366  文章 - 0  评论 - 101  阅读 - 30万

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的内容自己判断吧!
posted on   寒星12345678999  阅读(218)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示