# -*- 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("程序測試結束")
我在京東爬蟲中用的到判斷網絡情況的代碼,核心代碼以下:shell
p = subprocess.Popen(["ping.exe", pingUrl], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) out = p.stdout.read()再根據out的內容本身判斷吧!