Python argparse: Difference between revisions
From wikinotes
Line 51: | Line 51: | ||
<blockquote> | <blockquote> | ||
<syntaxhighlight lang="python"> | <syntaxhighlight lang="python"> | ||
parser.add_argument( | parser.add_argument('-p','--filter-projects', | ||
default='monday', | |||
metavar='MON', # displayed in help as value | |||
type=str) | |||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- Argument Properties --> | </blockquote><!-- Argument Properties --> |
Revision as of 05:52, 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
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
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', default='monday', metavar='MON', # displayed in help as value type=str)
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