Python argparse: Difference between revisions

From wikinotes
 
Line 33: Line 33:
''' Summary '''
''' Summary '''
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
(nothing)                     ## positional
(nothing)           # positional
nargs='+'                     ## list                                (args.arg  = [])
nargs=1              # flag with N args
nargs='?'                     ## single arg, or none (uses default=)  (args.arg  = None, 'var')  #(set const=val to know when flag issued with no arguments)
nargs='+'           # flag with one or more args          (args.arg  = [])
nargs='*'                     ## None, or multiple arguments          (args.arg  = None, [], ['a','b',...])
nargs='?'           # flag with one or no args            (args.arg  = None, 'var')  #(set const=val to know when flag issued with no arguments)
action='store_true'           ## flag with no args                    (args.arg = True/False)
nargs='*'           # flag with multiple or no args        (args.arg  = None, [], ['a','b',...])
action='store_true' # flag indicates boolean              (args.arg = True/False)
action='store_false'
action='store_false'
</syntaxhighlight>
</syntaxhighlight>


''' Detailed '''
''' Examples '''
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
  parser.add_argument( ## Positional
# positional
      'output-file',                         help='\n'.join((
parser.add_argument('output-file', help='filepath to save spreadsheet to')
            'filePath to save spreadsheet to ',
            '                                ',
            'ex: C:/Users/willp/Desktop/temp ')),
      )


  parser.add_argument( ## single argument
# flag with single argument
      '-s','--start-date',       nargs='?', help='\n'.join((
parser.add_argument('-s', '--start-date', nargs=1, help='date to start from')
            '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',
      )


# boolean arguments
parser.add_argument('-v', '--verbose', action='store_true', help='verbose logging')
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- argument types -->
</blockquote><!-- argument types -->

Revision as of 05:48, 18 November 2021

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=1              # flag with N args
nargs='+'            # flag with one or more args           (args.arg  = [])
nargs='?'            # flag with one or no args             (args.arg  = None, 'var')  #(set const=val to know when flag issued with no arguments)
nargs='*'            # flag with multiple or no args        (args.arg  = None, [], ['a','b',...])
action='store_true'  # flag indicates boolean               (args.arg = True/False)
action='store_false'

Examples

# positional
parser.add_argument('output-file', help='filepath to save spreadsheet to')

# flag with single argument
parser.add_argument('-s', '--start-date', nargs=1, help='date to start from')

# boolean arguments
parser.add_argument('-v', '--verbose', action='store_true', help='verbose logging')

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