Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import yaml
- import sys
- VAR_DELIM = ","
- KEY_DELIM = ":"
- def int_try_parse(value):
- try:
- return int(value)
- except ValueError:
- return value
- def add_field(file_dict, key, value):
- fields = key.split(".")
- current = file_dict
- for idx, field, in enumerate(fields):
- if current.get(field) is None:
- if idx == len(fields) - 1:
- current[field] = int_try_parse(value)
- else:
- current[field] = {}
- current = current[field]
- else:
- current = current[field]
- return file_dict
- def build_dict(list_of_keys):
- file_dict = {}
- pairs = list_of_keys.split(VAR_DELIM)
- for pair in pairs:
- [key, value] = pair.split(KEY_DELIM)
- file_dict = add_field(file_dict, key, value)
- return file_dict
- def write_out_yaml_file(filename, to_yaml_dict):
- with open(filename, 'w') as outfile:
- yaml.dump(to_yaml_dict, outfile, default_flow_style=False)
- def print_usage():
- usage = """
- NAME
- make_yaml.py - produces a yaml file from a list of key/value pairs
- SYNOPSIS
- make_yaml.py [filename] [key_value_list]
- The [key_value_list] is a list, delimited by {VAR_DELIM}, which specifies a yaml key at arbitrary depth
- and its value. The key/value are delimited by {KEY_DELIM}.
- EXAMPLE
- $ make_yaml.py out.yaml one:1,two:2,three.four.five:5,three.six:6,three.four.eight:8
- will produce a file called out.yaml with the contents:
- one: '1'
- three:
- four:
- eight: '8'
- five: '5'
- six: '6'
- two: '2'
- """
- print(usage)
- def main(output_file, list_of_keys):
- to_yaml_dict = build_dict(list_of_keys)
- write_out_yaml_file(output_file, to_yaml_dict)
- if __name__ == "__main__":
- if len(sys.argv) != 3:
- print_usage()
- else:
- _output_file = sys.argv[1]
- _list = sys.argv[2]
- main(_output_file, _list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement