Python argparse

From wikinotes
Revision as of 23:25, 5 March 2020 by Will (talk | contribs) (→‎argument types)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Argparse enables you to provide command-line interfaces for python scripts. It is a wonderful, powerful system that unfortunately comes with atrocious defaults.

Simple Example

if __name__ == '__main__':
	import argparse

   parser = argparse.ArgumentParser(											## init & setup
               formatter_class = argparse.RawTextHelpFormatter,
               description     = '\n'.join((
                  'Generates a report of logged hours for every project,        ',
                  'and every contributing user within specific period of time.  ',
                  'Report is output in the form of an excel spreadsheet .xlsx   ',
                  'Report is generated from the eventMonth_database.            ')),
      )

   parser.add_argument(																## Positional Argument
      '-o','--output-file',                          help=(
            'filePath to save spreadsheet to \n'
            '                                \n'
            'ex: C:/Users/willp/Desktop/temp \n'),
      )

	cliargs = parser.parse_args()													## Parse Args
	print cliargs.output_file														## Access Arguments

argument types

Summary

(nothing)                     ## positional
nargs='+'                     ## list                                 (args.arg  = [])
nargs='?'                     ## single arg, or none (uses default=)  (args.arg  = None, 'var')  #(set const=val to know when flag issued with no arguments)
nargs='*'                     ## None, or multiple arguments          (args.arg  = None, [], ['a','b',...])
action='store_true'           ## flag with no args                    (args.arg = True/False)
action='store_false'

Detailed

   parser.add_argument(																## Positional
      'output-file',                          help='\n'.join((
            'filePath to save spreadsheet to ',
            '                                ',
            'ex: C:/Users/willp/Desktop/temp ')),
      )

   parser.add_argument(																## single argument
      '-s','--start-date',        nargs='?',  help='\n'.join((
            'date to start from              ',
            '                                ',
            'ex: 2015/10/01                  ')),
      )

   parser.add_argument(																## single argument
      '-p','--filter-projeccts'   nargs='+',  help='\n'.join((
            'filePath to save spreadsheet to ',
            '                                ',
            'ex: 2015/10/01                  ')),
      )

   parser.add_argument(																## flags with no args
      '-p','--filter-projeccts'               help='\n'.join((
            'filePath to save spreadsheet to ',
            '                                ',
            'ex: 2015/10/01                  ')),
				action='store_true',
      )

Specific Datatypes

nargs = '+'				## Lists
type  = str				## str, int, float

Argument Properties

parser.add_argument(
	'-p','--filter-projects'	## short/long flags (can support multiple letters)
	default = 'monday'			## default value
	metavar = 'varA'				## example variable  --start-date [varA ...]
	)

SubParsers

Sometimes a single CLI interface provides access to a handful of related classes. These classes may take entirely different parameters. In this case, you would implement a subparser for that set of commands.


parser = argparse.ArgumentParser(
      formatter_class = argparse.RawTextHelpFormatter,
      description     = 'A collection of tools for operating on config files',
   )
subparsers = parser.add_subparsers( dest='subparser_name')
## Subparser1 (ModifyKeyVals)
##
modkeyval_parser = subparsers.add_parser( 'ModifyKeyVals', help='Flexible tool to modify configfiles that use the key=value format')

modkeyval_parser.add_argument(
      '-f', '--filepath', help='Path to the configfile we are processing',
      metavar = '/etc/rc.conf',
   )

modkeyval_parser.add_argument(
      '-v', '--verbose', help='Enable detailed logging',
      metavar = '/etc/rc.conf',
   )



## Subparser2 (SSHConfig)
##
sshconfig_parser = subparsers.add_parser( 'SSHConfig', help='modify ~/.ssh/ssh_config "Host" entries. Expects to be run as the user whose ssh_config you are modifying.')

sshconfig_parser.add_argument(
      '-hs', '--host', nargs='+', help='SSH Host value(s)',
      metavar = ['gitbox', '192.168.1.202'],
      )
## Using Variables from SubParsers
##

args = parser.parse_args()
if   args.subparser_name == 'ModifyKeyVals':
	filepath = args.filepath

elif args.subparser_name == 'SSHConfig':
	host     = args.host


python myscript.py ModifyKeyVals -f /path/to/file -v