Created
March 11, 2014 01:07
-
-
Save b4hand/9477640 to your computer and use it in GitHub Desktop.
Extract a single value from a YAML file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env python | |
| from __future__ import print_function | |
| import sys, yaml | |
| if len(sys.argv) < 3: | |
| print("usage: %s file key ... " % (sys.argv[0]), file=sys.stderr) | |
| exit(1) | |
| def retrieve_key(f, keys): | |
| config = yaml.load(f) | |
| while keys and config: | |
| key = keys.pop(0) | |
| try: | |
| config = config[key] | |
| except TypeError: | |
| config = config[int(key)] | |
| return config | |
| def output_key(f, keys): | |
| print(retrieve_key(f, keys)) | |
| input_file = sys.argv[1] | |
| keys = sys.argv[2:] | |
| if input_file == '-': | |
| output_key(sys.stdin, keys) | |
| else: | |
| with open(input_file) as f: | |
| output_key(f, keys) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does
exit(1)need to besys.exit(1)?