User Tools

Site Tools


docu:csheet:sysadm:script:python:argparse

How to use argparse on python3


The goal is to provide to your application, a strong command line options support, and be easy to program as well as to use it.

# basic initialization
import argparse
parser = argparse.ArgumentParser(description='The description of your handy tool')
 
# create a mutually exclusive group of parameters
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--ping', action='store_true', help='(example) a flag to ping your application')
group.add_argument('--health', action='store_true', help='(example) another flag to check the health of your app')
group.add_argument('--someaction', metavar='S', type=int, help='(example) an action of your application, using an integer as an argument, and showed as "S"')
 
# add a manual group of parameters (in this case, the required ones)
group2 = parser.add_argument_group('required arguments')
# add a required argument of type string
group2.add_argument('--host', metavar='HOST:PORT', required=True, type=str, help='(example) host and port of your application backend')
 
# the last argument is a 0 to N integer array called 'numbers'
# "*" means 0 to N, "+" means 1 to N
parser.add_argument('numbers', metavar='N', type=int, nargs='*', help='(example) some integer numbers')
 
# parse the args from the sys.argv without using the first parameter (which is the program name)
args = parser.parse_args(sys.argv[1:])
 
# access the parameters easily
print(args.ping)
print(args.numbers)
print(args.host)
>>> True
>>> [1, 3, 9]
>>> 127.0.0.1:3306

Invocation example:

python3 yourtool.py --ping --host=127.0.0.1:3306 1 3 9

Invoke as follows to get the help of your handy tool:

python3 yourtool.py --help
docu/csheet/sysadm/script/python/argparse.txt · Last modified: 2020/02/14 13:15 by admin