Skip to content

Instantly share code, notes, and snippets.

@bpeterso2000
Forked from ff6347/example-argsparse.py
Last active August 29, 2015 14:00
Show Gist options
  • Save bpeterso2000/6b92fad0eb10802b5a41 to your computer and use it in GitHub Desktop.
Save bpeterso2000/6b92fad0eb10802b5a41 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
argparse sample code
~~~~~~~~~~~~~~~~~~~~
Not the complete list of add_argument parameters, just the most common
----------------------------------------------------------------------
arg name or optional flags:
positional (required option): "foo"
options: "-f", "--foo"
action=<keyword>
* store_true: Special case of const, sets flag to True when flag is found.
* store_true: Special case of const, sets flag to False when flag is found.
* store_const: Used with an optional flag to assign a value when set.
* append_const: store each constant set by specified flags in a list
* append: allows option multiple times, stores values in a list
nargs: The number of command-line arguments to consume.
<int>: Specified value.
'?': Zero or One.
'*': Zero or more.
'+': One or more.
default=<value>
Default value is option is omitted.
type=<type>
Convert the arg string to a specified Python <type>.
choices=[item1, item2, ...]
Arg value must appear in the specified list.
help='<description>'
Brief description of what the argument does.
dest='<name>'
Name of the attribute to store the result in.
metavar='<name>'
Name of the argument when included in usage messages.
References:
* Primary Reference: https://docs.python.org/dev/library/argparse.html#prog
* Original forked from: https://gist.github.com/fabiantheblind/5916265
* Added some docstring info from: https://gist.github.com/dsc/3855240
* For a more advanced example of a custom action (not included here) visit
https://gist.github.com/brantfaircloth/1443543
"""
__version__ = '0.1'
__license__ = '''
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.'''
import argparse
import sys
from pprint import pprint
class CustomAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
print('%r %r %r' % (namespace, values, option_string))
setattr(namespace, self.dest, values)
def main(args):
pprint(args)
if __name__ == '__main__':
# explicitly setting prog & usage to demo default settings
boilerplate_parser = argparse.ArgumentParser(
add_help=False,
prog=sys.argv[0],
usage='%(prog)s [options]',
description='Demonstration of argparse')
boilerplate_parser.add_argument(
'--version',
action='version',
version='%(prog)s ' + __version__ + __license__)
# inherits common base (parent) parser ...
# add_help=False in the parent's parameters is required for this to work
# overrides epilog
# formatter_class:
# RawDescriptionHelpFormatter: desc & epilog should displayed as-is
# RawTextHelpFormatter: maintains whitespace for help & arg descriptions
# ArgumentDefaultsHelpFormatter: adds default values to arg help messages
# MetavarTypeHelpFormatter: uses name of type arg for each argument
# as the display name for its values (rather than dest):
epilog = '''this epilog description indenting is messed up to demo
raw formatting'''
parser = argparse.ArgumentParser(parents=[boilerplate_parser],
epilog=epilog, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-f', '--flag', action='store_true',
help='optional flag, True when specfied else False')
parser.add_argument('--integer', type=int, dest='number',
help='an integer')
parser.add_argument('--choice', choices=['one', 'two', 'three'],
help='chose one, two or three')
parser.add_argument('--int_choice', type=int, choices=[1, 2, 3],
help='chose a number from 1 to 3')
#parser.parse_args('--foo=FOO'.split())
parser.add_argument('--custom', action=CustomAction)
parser.add_argument('required', help='required positional arg')
parser.add_argument('filenames', nargs='*',
help='zero or more positional args')
args = parser.parse_args()
main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment