如何在python中将YAML拆分为不同的文件?
我使用yaml库中的safe_load将此yaml_文件保存在python中的一个变量中:如何在python中将YAML拆分为不同的文件?,python,dictionary,yaml,Python,Dictionary,Yaml,我使用yaml库中的safe_load将此yaml_文件保存在python中的一个变量中: domainInfo: AdminUserName: '--FIX ME--' AdminPassword: '--FIX ME--' topology: Name: 'wld-pil-10' ConfigBackupEnabled: true AdminServerName: 'wls-pil-10-sa-adm-n0' DomainVersion: 12
domainInfo:
AdminUserName: '--FIX ME--'
AdminPassword: '--FIX ME--'
topology:
Name: 'wld-pil-10'
ConfigBackupEnabled: true
AdminServerName: 'wls-pil-10-sa-adm-n0'
DomainVersion: 12.2.1.4.0
ProductionModeEnabled: true
ArchiveConfigurationCount: 20
Cluster:
'test-bruno-jee-r01a-c01':
ClientCertProxyEnabled: true
WeblogicPluginEnabled: true
Server:
'wls-pil-10-sa-adm-n0':
ListenPort: 11030
WeblogicPluginEnabled: true
ClientCertProxyEnabled: true
Machine: 'wlm-pil-10-n0'
'test-bruno-jee-r01a-it-c01-m1-n1':
ListenPort: 10022
WeblogicPluginEnabled: true
ClientCertProxyEnabled: true
NMSocketCreateTimeoutInMillis: 30000
Machine: 'wlm-pil-10-n1'
'test-bruno-jee-r02a-it-c01-m1-n1':
ListenPort: 10025
WeblogicPluginEnabled: true
ClientCertProxyEnabled: true
NMSocketCreateTimeoutInMillis: 30000
Machine: 'wlm-pil-10-n2'
为了分割这个yaml文件,我尝试将键和值放入一个新字典中,但没有成功。我错过了什么?我知道在某种程度上我需要一本字典,我是否需要使用另一个模块,比如pyyaml或ruamel
yaml_cluster = {}
yaml_cluster["topology"]["Name"] = yaml_file["topology"]["Name"]
yaml_cluster["topology"]["AdminServerName"] = yaml_file["topology"]["AdminServerName"]
结果:
致命:[wls-pil-103-sa-adm-n0]:失败!=>{“已更改”:true,“msg”:
“非零返回码”、“rc”:1、“stderr”:“回溯(最新版本)”
上次调用):\n文件
“/tmp/ansible-tmp-1611083722.9917288-55849-2153778473850896/split_yaml.py”,
第32行,在yaml_集群[“拓扑”][“名称”]=
yaml_文件[“拓扑”][“名称”]\nKeyError:“拓扑”\n,
“stderr_行”:[“回溯(最近一次调用):”,“文件”
“/tmp/ansible-tmp-1611083722.9917288-55849-2153778473850896/split_yaml.py”,
第32行,在“,”yaml_集群[“拓扑”][“名称”]=
yaml_文件[“拓扑”][“名称”],键错误:“拓扑”,“标准输出”:
“”和“标准输出行”:[]}
您得到的错误是因为
yaml_cluster[“topology”][“Name”]
被分配了一个值,而没有任何键存在yaml_群集[“拓扑”]
不存在,因此您无法将某些内容分配给键Name
标准库中的Collections模块提供了一个classCollections.defaultdict
,如果某个键不存在,它将为该键提供一个默认值。在您的情况下,默认值为空字典的defaultdict
会将yaml_cluster[“topology]
的值设置为{}
(一个空dict),然后键Name
可以正常地为字典分配一个值
from collections import defaultdict
yaml_cluster = defaultdict(dict) # Specifying dictionary as default value for missing keys
yaml_cluster["topology"]["Name"] = yaml_file["topology"]["Name"]
yaml_cluster["topology"]["AdminServerName"] = yaml_file["topology"]["AdminServerName"]
但是现在,当我将变量保存到一个文件中时,我得到了类似的结果:
!!python/object/apply:collections.defaultdict args:-!!python/name:builtins.dict''dictems:topology:AdminServerName:wls-pil-103-sa-adm-n0 name:wld-pil-103
@shamaN一系列原因可能会给出这个错误,因为它太模糊了。我建议starting使用尽可能多的示例代码和一些日志文件创建一个新的stackoverflow线程