Python argparse: Difference between revisions

From wikinotes
 
(6 intermediate revisions by the same user not shown)
Line 1: Line 1:
Argparse is a builting python library for building commandline interfaces.
Argparse is a builting python library for building commandline interfaces.<br>
The help menu is generated automatically.


{{ TODO |
= Documentation =
this page is just bad. clean me }}
<blockquote>
{| class="wikitable"
|-
| official docs || https://docs.python.org/3/library/argparse.html
|-
|}
</blockquote><!-- Documentation -->


= Simple Example =
= Example =
<blockquote>
<blockquote>
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
Line 10: Line 17:


parser = argparse.ArgumentParser(description='Does thing real well')
parser = argparse.ArgumentParser(description='Does thing real well')
parser.add_argument('-v', '--verbose',  
parser.add_argument('-v', '--verbose',
                     action='store_true', help='enable verbose logging')
                     action='store_true', help='enable verbose logging')
args = parser.parse_args()
args = parser.parse_args()
print(args.verbose)  # True
print(args.verbose)  # True
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- init -->
</blockquote><!-- Example -->


= argument types =
= Arguments =
<blockquote>
== Argument Types ==
<blockquote>
<blockquote>
''' Summary '''
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
# number of args
# number of args
Line 25: Line 34:
nargs=1    # flag with N args
nargs=1    # flag with N args
nargs='+'  # flag with one or more args    (args.arg  = [])
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 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',...])
nargs='*'  # flag with multiple or no args (args.arg  = None, [], ['a','b',...])


Line 33: Line 43:
</syntaxhighlight>
</syntaxhighlight>


''' Examples '''
Samples:
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
# positional
# foo my/output/file
parser.add_argument('output-file',
parser.add_argument('output-file',
                     help='filepath to save spreadsheet to')
                     help='filepath to save spreadsheet to')


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


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


= Argument Properties =
= Parsers =
<blockquote>
<blockquote>
== Helpstring Formatting ==
<blockquote>
You can preserve whitespace/newlines with custom formatters.
<syntaxhighlight lang="python">
<syntaxhighlight lang="python">
parser.add_argument('-p','--filter-projects',
import argparse
                    default='monday',
import textwrap
                    metavar='MON',    # displayed in help as value
 
                    type=str)
parser = argparse.ArgumentParser(
    prog="my-program",
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description=textwrap.dedent("""
        program that does thing
        =======================
 
            * do thing
            * other thing
    """).strip())
</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":
    # ...