Fish Touching🐟🎣

Python Argparse

Apr 29, 2023

# Argparse

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("argumentName", help="display help msg", type=int) # no --
parser.add_argument("-v","--verbosity", help="increase output verbosity", action="store_true") # with --
args = parser.parse_args()

if args.argumentName:
	# do sth
elif args.verbosity:
	print("verbosity turned on")

# Sub-command Parser

argparse — Parser for command-line options, arguments and sub-commands — Python 3.10.6 documentation
Many programs split up their functionality into a number of sub-commands, for example, the svn program can invoke sub-commands like svn checkoutsvn update, and svn commit. Splitting up functionality this way can be a particularly good idea when a program performs several different functions which require different kinds of command-line arguments.  ArgumentParser supports the creation of such sub-commands with the  add_subparsers() method. The  add_subparsers() method is normally called with no arguments and returns a special action object. This object has a single method, add_parser(), which takes a command name and any  ArgumentParser constructor arguments, and returns an  ArgumentParser object that can be modified as usual.