gpt4 book ai didi

python - 如何比较 yaml 文件而不考虑顺序差异?

转载 作者:行者123 更新时间:2023-12-05 02:40:35 28 4
gpt4 key购买 nike

我需要比较由两个不同进程生成且排序不同的 yaml 文件,并检测它们在 python 中的逻辑是否相同。

yaml 文件 1:

apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deployment
labels:
app: nginx
spec:
replicas: 3
selector:
matchLabels:
app: nginx
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
image: nginx:1.14.2
ports:
- containerPort: 80

yaml 文件 2:

apiVersion: apps/v1
kind: Deployment
metadata:
labels:
app: nginx
name: nginx-deployment
spec:
selector:
matchLabels:
app: nginx
replicas: 3
template:
metadata:
labels:
app: nginx
spec:
containers:
- name: nginx
ports:
- containerPort: 80
image: nginx:1.14.2

在逻辑级别与文字文本级别生成有用的 yaml 差异的最佳方法是什么?在上面的示例中,这些 yaml 文件应该被认为是等效的。

最佳答案

我能够找到的最佳解决方案是在脚本下方。

"""
python path_to_dir/compare_yaml.py path_to_dir/file1.yaml path_to_dir/file2.yaml
"""
import argparse
import yaml
import dictdiffer

parser = argparse.ArgumentParser(description='Convert two yaml files to dict and compare equality. Allows comparison of differently ordered keys.')
parser.add_argument('file_paths', type=str, nargs=2,
help='Full paths to yaml documents')
args = parser.parse_args()

print(f"File Path 1: {args.file_paths[0]}")
print(f"File Path 2: {args.file_paths[1]}")

with open(args.file_paths[0],'r') as rdr:
data1=rdr.read()

with open(args.file_paths[1],'r') as rdr:
data2=rdr.read()

data1_dict = yaml.load(data1,Loader=yaml.FullLoader)
data2_dict = yaml.load(data2,Loader=yaml.FullLoader)

if data1_dict == data2_dict:
print("No difference detected")
else:
print("Differences detected:")
for diff in list(dictdiffer.diff(data1_dict, data2_dict)):
print(diff)

如果按原样针对有问题的示例运行:

python .../compare_yaml.py .../yaml1.yaml .../yaml2.yaml
File Path 1: .../yaml1.yaml
File Path 2: .../yaml2.yaml
No difference detected

如果改变一个键,那么得到这样的输出:

python .../compare_yaml.py .../yaml1.yaml .../yaml2.yaml
File Path 1: .../yaml1.yaml
File Path 2: .../yaml2.yaml
Differences detected:
('change', ['spec', 'template', 'spec', 'containers', 0, 'name'], ('nginx', 'ngin'))

关于python - 如何比较 yaml 文件而不考虑顺序差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68488797/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com