Skip to content

Instantly share code, notes, and snippets.

@aliles
Created July 13, 2011 13:00
Show Gist options
  • Save aliles/1080253 to your computer and use it in GitHub Desktop.
Save aliles/1080253 to your computer and use it in GitHub Desktop.
Simple command line parsing using Python's argparse module.
"Simple command line parsing using argparse."
from collections import namedtuple
from functools import partial
import argparse
__all__ = ['Argument', 'parse_cmdline']
class Argument(namedtuple('BaseArgument', 'short full default help')):
"""Command line argument option for command line parser.
If both short and full are None the argument is a positional argument.
Otherwise short is a single character opton and full is a long name
option.
"""
def __new__(self, short=None, full=None, default=None, help=None):
return super(Argument, self).__new__(Argument,
short, full, default, help)
def parse_cmdline(arguments, description=None, epilog=None,
known_args=False, cmdline=None):
"""Parse a command line using the arguments dictionary.
The arguments dictionary keys are the option names. Values are either
an Argument instance or a string. If the value is a string it's used for
the option flag, short or long depending on length.
"""
parser = argparse.ArgumentParser(description=description, epilog=epilog)
for name in sorted(arguments):
if isinstance(arguments[name], Argument):
_add_advanced_argument(parser, name, arguments[name])
else:
_add_simple_argument(parser, name, arguments[name])
if known_args:
return parser.parse_known_args(cmdline)
return parser.parse_args(cmdline)
def _add_simple_argument(parser, name, default):
flag = '--' + name if len(name) > 1 else '-' + name
action = 'store'
if isinstance(default, bool):
action = 'store_true' if not default else 'store_false'
parser.add_argument(flag, action=action, default=default)
def _add_advanced_argument(parser, name, args):
flags = []
if args.short:
flags.append('-' + args.short[:1])
if args.full:
flags.append('--' + args.full)
default = args.default
action = 'store'
if isinstance(default, bool):
action = 'store_true' if not default else 'store_false'
parser.add_argument(*flags, dest=name, action=action, default=default,
help=args.help)
"Demonstrate cmdline module usage."
from cmdline import Argument, parse_cmdline
if __name__ == '__main__':
arguments = {
'natural': 1,
'w': True,
'real': Argument('r', 'rea', 3.14, 'a real number'),
'hello': Argument(None, 'hello', 'world', 'a string'),
'japanese': Argument('j', 'japanese',
u'\u30cf\u30ed\u30fc\u30ef\u30fc\u30eb\u30c9', None),
'verbose': Argument('v',None, False, 'verbosity flag'),
'target': Argument(None, None, None, 'a file name'),
}
print parse_cmdline(arguments, known_args=True,
description=__doc__)
usage: cmdline_demo.py [-h] [--hello HELLO] [-j JAPANESE] [--natural NATURAL]
[-r REAL] [-v] [-w]
target
Demonstrate cmdline module usage.
positional arguments:
target a file name
optional arguments:
-h, --help show this help message and exit
--hello HELLO a string
-j JAPANESE, --japanese JAPANESE
--natural NATURAL
-r REAL, --rea REAL a real number
-v verbosity flag
-w
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment