d
Amit DhamuSoftware Engineer
 

Using argparse For Script Arguments

2 minute read 00000 views

argparse is a good way of passing and parsing arguments to your Python scripts. By setting a description as the example below shows, it means -h or --help also gets populated automatically explaining usage guidelines for the script.

The below example shows one required and one optional parameter (which has a default)

#!/usr/bin/env python3

import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description='A description of your script'
    )
    parser.add_argument(
        '-s',
        metavar='Server',
        type=str,
        required=True,
        help='Which server are you targeting?'
    )
    parser.add_argument(
        '-p',
        metavar='Port',
        type=str,
        default='22',
        help='What port do you want to use?'
    )

    args = parser.parse_args()

    print(args)