我使用yaml库中的yaml_file在python中的一个变量中使用了这个safe_load:
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:
!=> {“已更改”:真,"msg":“非零返回代码”,"rc":1,"stderr":“跟踪”(最近一次调用):\n文件第32行,=>=yaml_file“拓扑”拓扑:‘拓朴’\n,"stderr_lines":[“跟踪(最近调用的最后一次调用):",”文件“第32行,”yaml_cluster“拓扑”=yaml_file“拓扑”“,"KeyError:‘拓朴’”],"stdout":“,"stdout_lines":[]}
发布于 2021-01-19 20:20:29
您所得到的错误是因为yaml_cluster["topology"]["Name"]被分配了一个值,而没有存在任何一个键。yaml_cluster["topology"]不存在,因此不能将某些东西分配给键Name。
标准库中的集合模块提供了一个类collections.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"]https://stackoverflow.com/questions/65798506
复制相似问题