Skip to content

Instantly share code, notes, and snippets.

@b4hand
Created March 11, 2014 01:07
Show Gist options
  • Save b4hand/9477640 to your computer and use it in GitHub Desktop.
Save b4hand/9477640 to your computer and use it in GitHub Desktop.
Extract a single value from a YAML file
#!/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)
@stephen-mw
Copy link

Does exit(1) need to be sys.exit(1)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment