Python argparse: Difference between revisions

From wikinotes
 
 
(15 intermediate revisions by the same user not shown)
Line 1: Line 1:
Argparse enables you to provide command-line interfaces for python scripts.
Argparse is a builting python library for building commandline interfaces.<br>
It is a wonderful, powerful system that unfortunately comes with atrocious defaults.
The help menu is generated automatically.


= Simple Example =
= Documentation =
<blockquote>
{| class="wikitable"
|-
| official docs || https://docs.python.org/3/library/argparse.html
|-
|}
</blockquote><!-- Documentation -->
 
= Example =
<blockquote>
<blockquote>
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
if __name__ == '__main__':
import argparse
import argparse


  parser = argparse.ArgumentParser( ## init & setup
parser = argparse.ArgumentParser(description='Does thing real well')
              formatter_class = argparse.RawTextHelpFormatter,
parser.add_argument('-v', '--verbose',
              description     = '\n'.join((
                    action='store_true', help='enable verbose logging')
                  '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
args = parser.parse_args()
      '-o','--output-file',                          help=(
print(args.verbose)  # True
            '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
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- init -->
</blockquote><!-- Example -->


= argument types =
= Arguments =
<blockquote>
== Argument Types ==
<blockquote>
<blockquote>
''' Summary '''
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
(nothing)                     ## positional
# number of args
nargs='+'                     ## list                                (args.arg  = [])
(nothing) # positional
nargs='?'                     ## single arg, or none (uses default=)  (args.arg  = None, 'var')  #(set const=val to know when flag issued with no arguments)
nargs=1    # flag with N args
nargs='*'                     ## None, or multiple arguments          (args.arg  = None, [], ['a','b',...])
nargs='+' # flag with one or more args    (args.arg  = [])
action='store_true'           ## flag with no args                    (args.arg = True/False)
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',...])
 
# boolean args
action='store_true'
action='store_false'
action='store_false'
</syntaxhighlight>
</syntaxhighlight>


''' Detailed '''
Samples:
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
  parser.add_argument( ## Positional
# foo my/output/file
      'output-file',                         help='\n'.join((
parser.add_argument('output-file',
            'filePath to save spreadsheet to ',
                    help='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
# foo -s today
      '-p','--filter-projeccts'  nargs='+',  help='\n'.join((
parser.add_argument('-s', '--start-date',
            'filePath to save spreadsheet to ',
                    nargs=1, help='date to start from')
            '                                ',
            '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',
      )


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


= Specific Datatypes =
= Parsers =
<blockquote>
<blockquote>
== Helpstring Formatting ==
<blockquote>
You can preserve whitespace/newlines with custom formatters.
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
nargs = '+' ## Lists
import argparse
type  = str ## str, int, float
import textwrap
</syntaxhighlight>
 
</blockquote><!-- Specific Datatypes -->
parser = argparse.ArgumentParser(
    prog="my-program",
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description=textwrap.dedent("""
        program that does thing
        =======================


= Argument Properties =
            * do thing
<blockquote>
            * other thing
<syntaxhighlight lang="python">
    """).strip())
parser.add_argument(
'-p','--filter-projects' ## short/long flags (can support multiple letters)
default = 'monday' ## default value
metavar = 'varA' ## example variable  --start-date [varA ...]
)
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Argument Properties -->
</blockquote><!-- Helpstring Formatting -->


= SubParsers =
== SubParsers ==
<blockquote>
<blockquote>
Sometimes a single CLI interface provides access to a handful
Subparsers let you bind a different parser to sub-commands.<br>
of related classes. These classes may take entirely different
(ex. <code>git checkout ${params}</code> vs <code>git fetch ${params}</code>)
parameters. In this case, you would implement a subparser for
that set of commands.
 


<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
parser = argparse.ArgumentParser(
# create parser
      formatter_class = argparse.RawTextHelpFormatter,
git_parser = argparse.ArgumentParser()
      description    = 'A collection of tools for operating on config files',
  )
subparsers = parser.add_subparsers( dest='subparser_name')
</syntaxhighlight>
</syntaxhighlight>


<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
## Subparser1 (ModifyKeyVals)
# create subparsers
##
subparsers = git_parser.add_subparsers(dest="git_subparser")
modkeyval_parser = subparsers.add_parser( 'ModifyKeyVals', help='Flexible tool to modify configfiles that use the key=value format')
git_checkout_parser = subparsers.add_parser("checkout")
 
git_fetch_parser = subparser.add_parser("fetch")
modkeyval_parser.add_argument(
git_fetch_parser = subparser.add_parser("show")
      '-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'],
      )
</syntaxhighlight>
</syntaxhighlight>


<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
## Using Variables from SubParsers
# add arguments to subparsers
##
git_checkout_parser.add_argument("file_or_commit", help="file/commit to checkout")
 
args = parser.parse_args()
if  args.subparser_name == 'ModifyKeyVals':
filepath = args.filepath
 
elif args.subparser_name == 'SSHConfig':
host    = args.host
 
 
</syntaxhighlight>
</syntaxhighlight>


 
<syntaxhighlight lang="python">
<syntaxhighlight lang="bash">
# identifying subparser, and parsing args
python myscript.py ModifyKeyVals -f /path/to/file -v
args = git_parser.parse_args()
if args.git_subparser == "checkout":
    # ...
elif args.git_subparser == "fetch":
    # ...
elif args.git_subparser == "show":
    # ...
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- SubParsers -->
</blockquote><!-- SubParsers -->
</blockquote><!-- Parsers -->

Latest revision as of 15:59, 9 April 2022

Argparse is a builting python library for building commandline interfaces.
The help menu is generated automatically.

Documentation

official docs https://docs.python.org/3/library/argparse.html

Example

import argparse

parser = argparse.ArgumentParser(description='Does thing real well')
parser.add_argument('-v', '--verbose',
                    action='store_true', help='enable verbose logging')

args = parser.parse_args()
print(args.verbose)  # True

Arguments

Argument Types

# number of args
(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',...])

# boolean args
action='store_true'
action='store_false'

Samples:

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

# foo -s today
parser.add_argument('-s', '--start-date',
                    nargs=1, help='date to start from')

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

Parsers

Helpstring Formatting

You can preserve whitespace/newlines with custom formatters.

import argparse
import textwrap

parser = argparse.ArgumentParser(
    prog="my-program",
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description=textwrap.dedent("""
        program that does thing
        =======================

            * do thing
            * other thing
    """).strip())

SubParsers

Subparsers let you bind a different parser to sub-commands.
(ex. git checkout ${params} vs git fetch ${params})

# create parser
git_parser = argparse.ArgumentParser()
# create subparsers
subparsers = git_parser.add_subparsers(dest="git_subparser")
git_checkout_parser = subparsers.add_parser("checkout")
git_fetch_parser = subparser.add_parser("fetch")
git_fetch_parser = subparser.add_parser("show")
# add arguments to subparsers
git_checkout_parser.add_argument("file_or_commit", help="file/commit to checkout")
# identifying subparser, and parsing args
args = git_parser.parse_args()
if args.git_subparser == "checkout":
    # ...
elif args.git_subparser == "fetch":
    # ...
elif args.git_subparser == "show":
    # ...