简体   繁体   中英

How to call and iterate values from a yaml file parsed using python?

  1. I have a yaml file as below:

     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.

read data from the config yaml file

    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)

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. How can I iterate and read the values in my yaml file by passing only the parameters? Ex: print('{host}@{ip}:{path}'.format(**config['os1'])) but without the 'os1' as the yaml file may have 100s of entries

  2. 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#'.

     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.

  1. You get the NameError exception because you don't return any values. You have to return config from the function.

For example:

def read_yaml(...):
    # code

     return config

Then, by calling read_yaml , you'll get your configuration returned.

Check the Python documentation & tutorials for that.

2-3. You can perform a for loop using the dict.items method.

For example:

x = {'lol': 1, 'kek': 2}

for name, value in x.items():
    print(name, value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM