Skip to content

Instantly share code, notes, and snippets.

@senderle
Last active August 29, 2015 14:06
Show Gist options
  • Save senderle/47bf0b2b13112cf5851b to your computer and use it in GitHub Desktop.
Save senderle/47bf0b2b13112cf5851b to your computer and use it in GitHub Desktop.
The simplest possible functional argument parser in Python
# copyright Scott Enderle 2014 -- CC BY-SA 3.0
# http://creativecommons.org/licenses/by-sa/3.0/
# https://gist.github.com/senderle/47bf0b2b13112cf5851b
import sys
def parse_args(names_types_defaults):
'''
Takes a list of options and parses sys.argv:
[('name', type, default_val), ...] -> namedtuple
If default_val == None, then the argument is required. Note that
it doesn't make sense to have required follow optional arguments.
This is the simplest possible functional argument parser. Just copy
and paste it into your script; it's not even worth putting in a
module. If you're going to import something, import argparse.
'''
names_types_defaults = [('command', str, '')] + names_types_defaults
names = [name for name, typ, default in names_types_defaults]
args = dict(zip(names, sys.argv))
Arg_list = collections.namedtuple('Arg_list', names)
try:
converted = [typ(args[name]) if name in args else default
for name, typ, default in names_types_defaults]
except Exception as e:
print_usage(args['command'], names_types_defaults, die=False)
print
raise
if None in converted:
print_usage(args['command'], names_types_defaults)
return Arg_list(*converted)
def print_usage(command, n_t_d, die=True):
n_t_d = n_t_d[1:]
arg_list = ' '.join(n for n, t, d in n_t_d)
required = (n for n, t, d in n_t_d if d is None)
optional = (n for n, t, d in n_t_d if d is not None)
print 'usage: ', command, arg_list
print
print 'required: ', ', '.join(required)
print 'optional: ', ', '.join(optional)
if die: sys.exit(0)
@senderle
Copy link
Author

senderle commented Sep 5, 2014

I find it useful to include at least a primitive command-line interface in all my scripts, and argparse, light as it is, is still heavier than necessary in many cases. Copy and paste it into your script and call it with a list of (arg_name, arg_converter, arg_default) tuples -- one for each legal argument. I ask only that you include a comment linking back to this gist.

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