Advertisement
Guest User

Untitled

a guest
Apr 18th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. import yaml
  2. import sys
  3.  
  4. VAR_DELIM = ","
  5. KEY_DELIM = ":"
  6.  
  7.  
  8. def int_try_parse(value):
  9. try:
  10. return int(value)
  11. except ValueError:
  12. return value
  13.  
  14.  
  15. def add_field(file_dict, key, value):
  16. fields = key.split(".")
  17. current = file_dict
  18.  
  19. for idx, field, in enumerate(fields):
  20. if current.get(field) is None:
  21. if idx == len(fields) - 1:
  22. current[field] = int_try_parse(value)
  23. else:
  24. current[field] = {}
  25. current = current[field]
  26. else:
  27. current = current[field]
  28. return file_dict
  29.  
  30.  
  31. def build_dict(list_of_keys):
  32. file_dict = {}
  33. pairs = list_of_keys.split(VAR_DELIM)
  34. for pair in pairs:
  35. [key, value] = pair.split(KEY_DELIM)
  36. file_dict = add_field(file_dict, key, value)
  37.  
  38. return file_dict
  39.  
  40.  
  41. def write_out_yaml_file(filename, to_yaml_dict):
  42. with open(filename, 'w') as outfile:
  43. yaml.dump(to_yaml_dict, outfile, default_flow_style=False)
  44.  
  45.  
  46. def print_usage():
  47. usage = """
  48. NAME
  49. make_yaml.py - produces a yaml file from a list of key/value pairs
  50.  
  51. SYNOPSIS
  52. make_yaml.py [filename] [key_value_list]
  53.  
  54. The [key_value_list] is a list, delimited by {VAR_DELIM}, which specifies a yaml key at arbitrary depth
  55. and its value. The key/value are delimited by {KEY_DELIM}.
  56.  
  57. EXAMPLE
  58. $ make_yaml.py out.yaml one:1,two:2,three.four.five:5,three.six:6,three.four.eight:8
  59. will produce a file called out.yaml with the contents:
  60.  
  61. one: '1'
  62. three:
  63. four:
  64. eight: '8'
  65. five: '5'
  66. six: '6'
  67. two: '2'
  68. """
  69.  
  70. print(usage)
  71.  
  72.  
  73. def main(output_file, list_of_keys):
  74. to_yaml_dict = build_dict(list_of_keys)
  75. write_out_yaml_file(output_file, to_yaml_dict)
  76.  
  77.  
  78. if __name__ == "__main__":
  79. if len(sys.argv) != 3:
  80. print_usage()
  81. else:
  82. _output_file = sys.argv[1]
  83. _list = sys.argv[2]
  84.  
  85. main(_output_file, _list)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement