一般情况下,我们通用属性一般都是写在属性文件中,然后通过configparser根据其键去获取相对应的值,还有就是字典中比较key和value的值,下边我们这里几个小需求:
1.通过configparser获取属性值
2.Python执行shell命令并返回值
3.dict中相同的key值是否相同
4.dict中同一个key缺失list-value中的哪些值
一、通过configparser获取属性值
1.1 创建属性文件 mycf.ini :
[date.list]
day=1,2,3
1.2 读取属性文件的值:
import os
import configparser
import datetime
def parse_config_file():
cf = configparser.ConfigParser()
cf.read("mycf.ini") # 配置文件的路径
return cf
def get_day_list():
cf = parse_config_file()
date_str = cf['date.list']['day']
d_list = date_str.split(",")
return d_list
1.3 先创建一个入口函数:
if __name__ == '__main__':
# 1 读取前三天的日期
for day in get_day_list():
otherStyleTime = (datetime.datetime.today() - datetime.timedelta(int(day))).strftime(
"%Y-%m-%d")
print(otherStyleTime)
# 2 执行 shell 命令
# url = "echo 'hellow'"
# print(get_shell_url(url))
# 3 对比同一个key是否value
# source_dict = {"topic1":"a","topic2":"m","topic3":"y"}
# sink_dict = {"topic1":"d","topic2":"m"}
# dict_result = print_dict_result(source_dict, sink_dict)
# print(dict_result)
# 4 对比两个字典中相同key列表的值是否缺失,是否缺失key
# source_dict = {"topic1": ["a","b","c","d","e"], "topic2": ["m","n","x","y","z"],"topic3": ["o","p"]}
# sink_dict = {"topic1": ["d","e"], "topic2": ["m","n"]}
# dict_result = print_dict_result2(source_dict, sink_dict)
# print(dict_result)
1.4 执行效果如下:
image.png
二、Python执行shell命令并返回值
2.1 定义函数:
def get_shell_url(url):
# data = os.popen("curl --insecure --cipher 'DEFAULT:!DH' "+ url +"%s"% a).read()
baidu_str = os.popen(url).read()
return baidu_str
2.2 执行的效果:
image.png
三、dict中相同的key值是否相同
3.1 定义函数:
# 对比同一个 topic 的值是否相等
def print_dict_result(source_dict, sink_dict):
# 相同
source_result_dict = {key: "源值:"+ str(source_dict.get(key,0)) +" <---> 目标值:"+ str(sink_dict.get(key,0)) for key in set(source_dict.keys())&set(sink_dict.keys())}
# 不相同
sink_result_dict = {key: "源值:"+ str(source_dict.get(key,0)) +" <---> 目标值:"+ str(sink_dict.get(key,0)) for key in set(source_dict.keys())^set(sink_dict.keys())}
result_idct = {"result": {"sucess": source_result_dict,"fail": sink_result_dict}}
return result_idct
3.2 执行的效果:
image.png
四、dict中同一个key缺失list-value中的哪些值
4.1 定义函数:
# dict中同一个key缺失list-value中的哪些值
def print_dict_result2(source_dict, sink_dict):
result_idct = {}
# 不存在
for i in source_dict.keys():
for j in sink_dict.keys():
if i==j:
result_idct[i] = [x for x in source_dict[i] if x not in sink_dict[j]]
result_list = {"key": [key for key in set(source_dict.keys())^set(sink_dict.keys())]}
result_dict = {"gen2 -> result":{"sink端同一个key缺失的value": result_idct,"sink端缺少的key": result_list}}
return result_dict
4.2 执行结果:
image.png
到此,我们的案例已完全执行,快复制粘贴吧,哈哈哈。。。
网友评论