自己動手造“輪子”---python常用的幾個方法

前言:由於工作內容的原因,經常需要些python腳本,久而久之,發現有一些方法經常用到,於是就自己動手編輯了一些常用的、大衆的、通用的方法。小弟不才,但也希望能爲開源做做貢獻。

最後再附上代碼哈;

一、目前該文件中只總結了五個方法:

1、ping_network(network_ip)   ---  ping測試的方法

2、socket_port(network_ip, port)  ---  檢測目標網絡端口是否開放(正常)的方法

3、file_format_analysis(file_path,format)  ---  解析json、yaml格式文件的方法

4、list_contrast(list_a,list_b)  ---  對比兩個數組數據的方法

5、dic_contrast(dic_a,dic_b) --- 對比兩個字典數據差異的方法

使用方法,只需要將這個 wheel_xpt.py 文件  import導入就可以咯;

二、方法介紹及示例

1、ping_network(network_ip)
使用python中的os模塊測試目標ip網絡是否可達,返回Trun或False;

示例:測試www.baidu.com的連通性

from wheel_xpt import *

result = ping_network("www.baidu.com")
print(result)

輸出結果:

正在 Ping www.a.shifen.com [61.135.169.121] 具有 32 字節的數據:
來自 61.135.169.121 的回覆: 字節=32 時間=7ms TTL=53
來自 61.135.169.121 的回覆: 字節=32 時間=5ms TTL=53
來自 61.135.169.121 的回覆: 字節=32 時間=5ms TTL=53
來自 61.135.169.121 的回覆: 字節=32 時間=5ms TTL=53

61.135.169.121 的 Ping 統計信息:
    數據包: 已發送 = 4,已接收 = 4,丟失 = 0 (0% 丟失),
往返行程的估計時間(以毫秒爲單位):
    最短 = 5ms,最長 = 7ms,平均 = 5ms
本機至 www.baidu.com 網絡通暢;
True

前面是方法連接測試的輸出(註釋代碼也可以將其取消),最後的True是連通性的判斷結果;

接下來再測試一個網絡不通的,這次直接使用ip:

from wheel_xpt import *

result = ping_network("192.168.0.123")
print(result)

輸出結果:

正在 Ping 192.168.0.123 具有 32 字節的數據:
請求超時。
請求超時。
請求超時。
請求超時。

192.168.0.123 的 Ping 統計信息:
    數據包: 已發送 = 4,已接收 = 0,丟失 = 4 (100% 丟失),
本機至 192.168.0.123 網絡不通;
False

ping不通的結果返回的就是 False 。

2、socket_port(network_ip, port)
使用python中的socket模塊檢測ip的端口是否開通;

示例:我們來檢測下csdn的80端口

from wheel_xpt import *

result = socket_port("www.csdn.net", "80")
print(result)

輸出結果:

正在檢測目標ip端口......別慌,稍作等待......
檢測 www.csdn.net 80 端口[正常].
True

返回True的話就是該端口開放,返回 False 就是目標端口未開放了;

3、file_format_analysis(file_path,format)
判斷文件是否存在,進行json、yaml格式的解析

示例:這裏我們測試解析兩個文件,一個json格式,一個yaml格式

from wheel_xpt import *

#解析json格式的文件
result_json = file_format_analysis(r"D:\my_files\python_test_file\json_yaml_test\role.json","json")
print(result_json)

print("====================================================")

#解析yaml格式的文件
result_yaml = file_format_analysis(r"D:\my_files\python_test_file\json_yaml_test\predata.yml","yaml")
print(result_yaml)

輸出結果:測試的兩個文件數據量可能有點大了,諒解哈;

D:\my_files\python_test_file\json_yaml_test\role.json 文件存在,進行json解析。
{'MachineGroups': {'Machines': ['a56c07001.cloud.c07.amtest8', 'a56c07002.cloud.c07.amtest8', 'a56c07003.cloud.c07.amtest8'], 'aarch64': [], 'sw_64': []}, 'ServerRoles': {'OpsClone#': ['a56c07001.cloud.c07.amtest8:10.14.4.1:docker010014004001', 'a56c07002.cloud.c07.amtest8:10.14.4.2:docker010014004002'], 'OpsCloneVipAgent#': ['a56c07001.cloud.c07.amtest8:10.14.4.11:docker010014004011'], 'OpsCloneWeb#': ['a56c07001.cloud.c07.amtest8:10.14.4.3:docker010014004003', 'a56c07002.cloud.c07.amtest8:10.14.4.19:docker010014004019'], 'OpsCloneWebVipAgent#': ['a56c07001.cloud.c07.amtest8:10.14.4.12:docker010014004012'], 'OpsDecider#': ['a56c07001.cloud.c07.amtest8', 'a56c07002.cloud.c07.amtest8'], 'OpsDns#': ['a56c07001.cloud.c07.amtest8:10.14.4.5:docker010014004005', 'a56c07002.cloud.c07.amtest8:10.14.4.21:docker010014004021'], 'OpsDnsMaster#': ['a56c07001.cloud.c07.amtest8:10.14.4.6:docker010014004006', 'a56c07002.cloud.c07.amtest8:10.14.4.22:docker010014004022'], 'OpsDnsSlave#': ['a56c07001.cloud.c07.amtest8:10.14.4.7:docker010014004007', 'a56c07002.cloud.c07.amtest8:10.14.4.23:docker010014004023'], 'OpsDnsSlaveVipAgent#': ['a56c07001.cloud.c07.amtest8:10.14.4.8:docker010014004008', 'a56c07002.cloud.c07.amtest8:10.14.4.24:docker010014004024'], 'OpsDnsVipAgent#': ['a56c07001.cloud.c07.amtest8:10.14.4.4:docker010014004004', 'a56c07002.cloud.c07.amtest8:10.14.4.20:docker010014004020'], 'OpsMasterTagAgent#': ['a56c07001.cloud.c07.amtest8'], 'OpsMysql#': ['a56c07001.cloud.c07.amtest8:10.14.4.9:docker010014004009', 'a56c07002.cloud.c07.amtest8:10.14.4.25:docker010014004025'], 'OpsMysqlVipAgent#': ['a56c07001.cloud.c07.amtest8:10.14.4.13:docker010014004013'], 'OpsNtp#': ['a56c07001.cloud.c07.amtest8', 'a56c07002.cloud.c07.amtest8'], 'OpsNtpVipAgent#': ['a56c07001.cloud.c07.amtest8:10.14.4.14:docker010014004014'], 'OpsOob#': ['a56c07001.cloud.c07.amtest8', 'a56c07002.cloud.c07.amtest8'], 'OpsOobVipAgent#': ['a56c07001.cloud.c07.amtest8:10.14.4.15:docker010014004015'], 'OpsTc#': ['a56c07001.cloud.c07.amtest8', 'a56c07002.cloud.c07.amtest8'], 'OpsYum#': ['a56c07001.cloud.c07.amtest8', 'a56c07002.cloud.c07.amtest8'], 'OpsYumVipAgent#': ['a56c07001.cloud.c07.amtest8:10.14.4.16:docker010014004016']}}
====================================================
D:\my_files\python_test_file\json_yaml_test\predata.yml 文件存在,進行yaml解析。
{'dnsslave': [{'anycastVip': ['10.45.250.1/32', '10.45.250.2/32'], 'anycast_ntp_vips': ['10.45.68.0/32', '10.45.68.1/32'], 'anycast_yum_vips': ['10.45.68.2/32'], 'bgpConnections': [], 'bgpanycastVip': [], 'docker0_ip': '10.45.8.8', 'env': {'idcMap': {'amtest34': 'master'}, 'idc_room': 'amtest34', 'isCenterRegion': True, 'region': 'cn-qingdao-sg-d01', 'zone': 'cn-qingdao-sg-amtest34001-a'}, 'ip': '10.45.1.2', 'master': ['10.45.8.6', '10.45.8.22'], 'ospfConnections': [{'localIp': '10.45.152.222/30', 'localPort': 'eth4', 'localas': '65081', 'ospfArea': '0.0.0.201', 'ospfPassword': 'aliospf', 'protocol': 'ospf', 'remoteIp': '10.45.152.221/30', 'remoteas': '65021'}], 'ospfanycastVip': ['10.45.250.1/32', '10.45.250.2/32', '10.45.68.2/32', '10.45.68.0/32', '10.45.68.1/32'], 'resolv_lines': ['nameserver 10.45.250.1', 'nameserver 10.45.250.2', 'nameserver 10.45.8.21', 'nameserver 10.45.8.5'], 'role': 'slave', 'single_mode': False, 'slave': ['10.45.1.1', '10.45.1.2'], 'slave_vips': ['10.45.8.21', '10.45.8.5'], 'subnets': ['10', '172'], 'vips': [{'ip': '10.45.8.21', 'maskbit': 32, 'name': 'VIP_10.45.8.21', 'priority': '85', 'state': 'BACKUP', 'vip_interface': 'docker0', 'virtual_router_id': '50', 'vrrp_interface': 'docker0'}, {'ip': '10.45.8.5', 'maskbit': 32, 'name': 'VIP_10.45.8.5', 'priority': '90', 'state': 'MASTER', 'vip_interface': 'docker0', 'virtual_router_id': '51', 'vrrp_interface': 'docker0'}]}]}

直接返回解析的結果,想要獲取json、yaml文件裏的某一個數值的話就可以直接使用 result_json/yaml 進行獲取了;

4、list_contrast(list_a,list_b)
判斷兩個數組內的數據是否相同,並輸出數組中不同的數據和交集;(不會損壞原數組)

示例:

from wheel_xpt import *

list_1 = ['a','b','c','d']
list_2 = ['a','b','d','f','456']

result = list_contrast(list_1,list_2)
print(result)

輸出結果:

{'list_same': ['a', 'b', 'd'], 'list_different_a': ['c'], 'list_different_b': ['f', '456']}

返回一個字典:

list_same 是兩個數組相同的數值;

list_different_a 是傳入第一個數組中不同的數值;

list_different_b 是傳入第二個數組中不同的數值;

5、dic_contrast(dic_a,dic_b)
判斷兩個字典內的數據,進行對比,返回相同的數據和不同的數據;(不會損壞原字典數據)

示例:爲了看着方便,測試對比用的字典數據就儘量減少了;

from wheel_xpt import *

dic_1 = {
    'a':'艾希',
    'b':'趙信',
    'c':'嘉文四世',
    'd':'內瑟斯',
}
dic_2 = {
    'a':'艾希',
    'b':'趙信',
    'd':'德瑪西亞',
}

result = dic_contrast(dic_1,dic_2)
print(result)

輸出結果:

{'same': {'a': '艾希', 'b': '趙信'}, 'diff_a': {'c': '嘉文四世', 'd': '內瑟斯'}, 'diff_b': {'d': '德瑪西亞'}}

返回一個字典:

same 是兩個字典中鍵值都相同的數據;

diff_a 是傳入第一個字典中不同的數據;

diff_b 是傳入第二個字典中不同的數據;

 

額.......咋樣,個人覺得還算好用吧;雖然網上有一些對比的方法,但還是感覺不如自己寫的用着順手哇,嘎嘎;

三、源碼

最後附上“輪子”源碼:

import os
import socket
import json
import yaml

"""使用python中的os模塊測試目標ip網絡是否可達,返回Trun或False"""
def ping_network(network_ip):
    #result = os.system("ping %s -w 3 -c 3" % (network_ip))     #在windows下不適用,-c 參數被封;
    result = os.system("ping %s -w 3" % (network_ip))
    if result == 0:
        print("本機至 %s 網絡通暢;" % (network_ip))
        return True
    else:
        print("本機至 %s 網絡不通;" % (network_ip))
        return False

"""使用python中的socket模塊檢測ip的端口是否開通"""
def socket_port(network_ip, port):
    # global socket_port_number  # 定義一個全局參數,返回ip目標端口的連通性:0 爲連通,1 爲阻塞;

    print("正在檢測目標ip端口......別慌,稍作等待......")
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
    try:
        s.connect((network_ip, int(port)))
        s.shutdown(2)
        socket_port_number = 0
    except:
        socket_port_number = 1
        pass
    if socket_port_number == 0:
        print("檢測 %s %s 端口[正常]." % (network_ip, port))
        return True
    else:
        print("檢測 %s %s 端口[關閉]." % (network_ip, port))
        return False

"""判斷文件是否存在,進行json、yaml格式的解析"""
#用法:在 file_format_analysis() 內傳入參數,file_path爲文件的絕對路徑,format爲[json、yaml]兩個字段。
def file_format_analysis(file_path,format):     #format只能爲 json、yaml。
    if os.path.exists(file_path) == True:
        if format == "json":
            print("%s 文件存在,進行json解析。" % (file_path))
            with open(file_path, 'rb') as f:
                file_json = json.load(f)
            return file_json
        elif format == "yaml":
            print("%s 文件存在,進行yaml解析。" % (file_path))
            with open(file_path, 'rb') as files:
                file_yaml = yaml.load(files,Loader=yaml.FullLoader)
            return file_yaml
        else:
            print("%s 文件存在,只進行判斷,不進行解析。" % (file_path))
            return True
    elif os.path.exists(file_path) == False:
        print("%s 文件不存在。" % (file_path))
        return False
    else:
        print("判斷 %s 文件是否存在時出現異常。" % (file_path))
        exit()

#判斷兩個數組內的數據是否相同的,不相同的話輸出不同的數據;
#返回一個字典---dic_list:
#   dic_lsit['list_same'] = ["兩個數組交集"]
#   dic_lsit['list_different_a'] = ["list_a中不同的數值"]
#   dic_lsit['list_different_b'] = ["list_b中不同的數值"]
def list_contrast(list_a,list_b):
    if len(list_a) == 0 or len(list_b) == 0:    #判斷傳入的數字是否爲空
        print("傳入數組不可都爲空")
        exit()

    list_1 = list_a[:]
    list_2 = list_b[:]
    dic_list = {}   #定義一個字典,裏面存放:1、兩個數組相同的數值;2、list_a數組不同的數值;3、list_b數組不同的數值;
    list_same = []    #定義一個列表,存儲相同的數值
    for i in range(0,len(list_1)):  #在數據量相同的情況下,遍歷一個數組,
        if list_1[i] in list_2:
            list_same.append(list_1[i])   #將相同的數值存儲到一個列表中;
        else:
            pass
    dic_list['list_same'] = list_same   #將相同的數值存入字典;

    for i in range(0,len(list_same)):   #遍歷存放兩個數組交集的列表;
        list_1.remove(list_same[i])     #刪除list_a中相同的數值,剩下不同的數值;
        list_2.remove(list_same[i])     #刪除list_b中相同的數值,剩下不同的數值;
    dic_list['list_different_a'] = list_1   #將list_a中不同的數值存入字典
    dic_list['list_different_b'] = list_2   #將list_b中不同的數值存入字典

    return dic_list

"""判斷兩個字典內容的方法"""
#   dic_all["same"] = {兩個字典的交集}
#   dic_all["diff_a"] = {第一個參數中不同的鍵值}
#   dic_all["diff_a"] = {第一個參數中不同的鍵值}
def dic_contrast(dic_a,dic_b):
    dic_all = {}
    dic_same = {}      #定義一個字典,存儲兩個字典中相同的鍵值;
    dic_diff_a = {}     #定義一個字典,存儲第一個參數中不同的鍵值;
    dic_diff_b = {}     #定義一個字典,第一個參數中不同的鍵值;

    if len(dic_a) == 0 and len(dic_b) == 0:
        print("傳入字典參數不可都爲空")
        exit()

    if len(dic_a) >= len(dic_b):    #對比兩個字典內的數量,遍歷多的去和少的對比;
        for i in dic_a.keys():      #遍歷dic_a的鍵;
            if i in dic_b.keys():   #如果dic_a中的鍵在dic_b中存在
                if dic_a[i] == dic_b[i]:    #則判斷值是否相等;
                    dic_same[i] = dic_a[i]
                else:
                    dic_diff_a[i] = dic_a[i]
                    dic_diff_b[i] = dic_b[i]
            else:    #如果dic_a中的鍵在dic_b中不存在
                dic_diff_a[i] = dic_a[i]
    else:
        for i in dic_b.keys():      #遍歷dic_b的鍵;
            if i in dic_a.keys():   #如果dic_b中的鍵在dic_a中存在
                if dic_b[i] == dic_a[i]:    #則判斷值是否相等;
                    dic_same[i] = dic_b[i]
                else:
                    dic_diff_a[i] = dic_a[i]
                    dic_diff_b[i] = dic_b[i]
            else:       #如果dic_b中的鍵在dic_a中不存在
                dic_diff_b[i] = dic_b[i]

    dic_all["same"] = dic_same
    dic_all["diff_a"] = dic_diff_a
    dic_all["diff_b"] = dic_diff_b

    return dic_all

人生苦短,我用python。
之後會繼續總結一些常用的方法進行添加的;。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章