Python argparse: Difference between revisions
From wikinotes
(15 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
Argparse | Argparse is a builting python library for building commandline interfaces.<br> | ||
The help menu is generated automatically. | |||
= | = 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"> | ||
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 | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- | </blockquote><!-- Example --> | ||
= | = Arguments = | ||
<blockquote> | |||
== Argument Types == | |||
<blockquote> | <blockquote> | ||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
(nothing) | # number of args | ||
nargs='+' | (nothing) # positional | ||
nargs='?' | nargs=1 # flag with N args | ||
nargs='*' | nargs='+' # flag with one or more args (args.arg = []) | ||
action='store_true' | 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> | ||
Samples: | |||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
# 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') | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- | </blockquote><!-- Argument Types --> | ||
</blockquote><!-- Arguments --> | |||
= | = Parsers = | ||
<blockquote> | <blockquote> | ||
== Helpstring Formatting == | |||
<blockquote> | |||
You can preserve whitespace/newlines with custom formatters. | |||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
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()) | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- | </blockquote><!-- Helpstring Formatting --> | ||
= SubParsers = | == SubParsers == | ||
<blockquote> | <blockquote> | ||
Subparsers let you bind a different parser to sub-commands.<br> | |||
(ex. <code>git checkout ${params}</code> vs <code>git fetch ${params}</code>) | |||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
parser = argparse.ArgumentParser( | # create parser | ||
git_parser = argparse.ArgumentParser() | |||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
# | # 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") | |||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
# | # add arguments to subparsers | ||
git_checkout_parser.add_argument("file_or_commit", help="file/commit to checkout") | |||
</syntaxhighlight> | </syntaxhighlight> | ||
<syntaxhighlight lang="python"> | |||
<syntaxhighlight lang=" | # 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": | |||
# ... | |||
</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}
vsgit 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": # ...