产生以下输出的代码和数据结构如下所示:
Actions = set()
# loop through and obtain a list of files and commands
for item in d['server']:
Actions.add('{action}'.format(**item))
print(Actions)
commands = list(Actions)
commands = list(Actions)
输出:
Actions = {"{'command1': ['uptime'], 'path': ['/var/log/syslog']}", "{'command1': ['df -h'], 'path': ['/var/log/auth.log']}"}
我需要分别提取命令和路径,这样的东西不起作用。
print(commands[0]['command1'])
Traceback (most recent call last):
文件"read_shell_yaml.py",第46行,位于打印(命令[0]['command1'](TypeError:字符串索引必须是整数
如果你需要按照你的方式来做,你可以在最后:
import json
content = json.loads(command[0].replace("'", '"'))
content['command1'] #prints ['df -h']
您正在使用str.format
方法将item
dict格式化为字符串,以防止后一个代码从dict中提取项目。
出于您的目的,更适合Actions
的数据结构将是由以下命令索引的dict:
Actions = {}
for item in d['server']:
Actions[items.pop('command1')] = item
以便以后可以迭代Actions
dict的项目,如下所示:
for command, properties in Actions.items():
print(command, properties['path'])