Skip to content

Instantly share code, notes, and snippets.

@debrouwere
Created June 11, 2014 15:57
Show Gist options
  • Save debrouwere/80ea2c120efad6b5000b to your computer and use it in GitHub Desktop.
Save debrouwere/80ea2c120efad6b5000b to your computer and use it in GitHub Desktop.
Take arguments from both stdin and as command-line flags
#!/usr/bin/env python
# encoding: utf-8
"""
This on the command line
echo '{"d": 44}' | ./input.py --a 33 --b 44 --c
turns into this argument passed to your function
{'a': '33', 'c': True, 'b': '44', u'd': 44}
Of course, mostly you'd just use one or the other, but
it might come in handy when you want to configure stuff
over the command-line but send any big blobs of data
over stdin.
"""
import sys
import functools
import json
## UTILITY CODE ##
def cast(obj):
""" Currently, no automatic casting from e.g.
'1234' to the integer 1234, but I have a
module for autocasting I could dust off --
and there's probably others out there too. """
return obj
def cli(fn):
@functools.wraps(fn)
def wrapped_fn():
argv = sys.argv[1:]
if not sys.stdin.isatty():
stdin = json.loads(sys.stdin.readline())
else:
stdin = {}
pairs = []
for argument in argv:
if argument.startswith('--'):
pairs.append([argument[2:], True])
else:
pairs[-1][1] = cast(argument)
options = {}
options.update(pairs)
options.update(stdin)
return fn(options)
if __name__ == '__main__':
wrapped_fn()
return wrapped_fn
## WHAT THE ACTUAL INTERFACE WOULD LOOK LIKE ##
@cli
def main(options):
print options
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment