[英]How to call and iterate values from a yaml file parsed using python?
I have a yaml file as below: 我有一个yaml文件,如下所示:
server1: host: os1 ip: ##.###.#.## path: /var/log/syslog file: syslog identityfile: /identityfile/keypair.pub server2: host: os2 ip: ##.###.#.## path: /var/log/syslog file: syslog.1 identityfile: /identityfile/id_rsa.pub
I have a piece of code to parse the yaml and read entries. 我有一段代码来解析yaml和读取条目。
def read_yaml(file):
with open(file, "r") as stream:
try:
config = yaml.load(stream)
print(config)
except yaml.YAMLError as exc:
print(exc)
print("\n")
return config
read_yaml("config_file") print(config) read_yaml(“ config_file”)print(config)
My problems: 1. I am unable to return values and I get a "NameError: name 'config' is not defined" at the print statement called outside the function. 我的问题:1.我无法返回值,并且在函数外部调用的打印语句上收到“ NameError:未定义名称'config'”。
How can I iterate and read the values in my yaml file by passing only the parameters? 如何通过仅传递参数来迭代和读取yaml文件中的值? Ex: print('{host}@{ip}:{path}'.format(**config['os1'])) but without the 'os1' as the yaml file may have 100s of entries 例如:print('{host} @ {ip}:{path}'。format(** config ['os1']))),但没有'os1',因为yaml文件可能有100个条目
I ensured there are no duplicates by using sets but want to use a loop and store the values from my string formatting command into a variable without using 'os1' or 'os2' or 'os#'. 我通过使用集合确保没有重复项,但想使用循环并将字符串格式化命令中的值存储到变量中,而不使用'os1'或'os2'或'os#'。
def iterate_yaml(): remotesys = set() for key,val in config.items(): print("{} = {}".format(key,val)) #check to ensure duplicates are removed by storing it in a set remotesys.add('{host}@{ip}:{path}'.format(**config['os1'])) remotesys.add('{host}@{ip}:{path}'.format(**config['os2'])) remotesys.add('{host}@{ip}:{path}'.format(**config['os3']))
Thanks for the help. 谢谢您的帮助。
NameError
exception because you don't return any values. 您会收到NameError
异常,因为您没有返回任何值。 You have to return config
from the function. 您必须从函数返回config
。 For example: 例如:
def read_yaml(...):
# code
return config
Then, by calling read_yaml
, you'll get your configuration returned. 然后,通过调用read_yaml
,将返回您的配置。
Check the Python documentation & tutorials for that. 查看Python文档和教程。
2-3. 2-3。 You can perform a for
loop using the dict.items
method. 您可以使用dict.items
方法执行for
循环。
For example: 例如:
x = {'lol': 1, 'kek': 2}
for name, value in x.items():
print(name, value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.