Wednesday, December 7, 2022

Learning how to feed arguments to command line - Argparse

Beginner on Argparse. The following are from the Official documentation.

The argparse module’s support for command-line interfaces is built around an instance of argparse.ArgumentParser. It is a container for argument specifications and has options that apply the parser as whole. The first descriptive message for the program is determined from sys.argv[0] or from the prog= argument. 

parser = argparse.ArgumentParser(
                    prog = 'ProgramName',
                    description = 'What the program does',
                    epilog = 'Text at the bottom of help')

After importing the library, argparse.ArgumentParser() initializes the parser so that you can start to add custom arguments. 

The ArgumentParser.add_argument() method attaches individual argument specifications to the parser. It supports positional arguments, options that accept values, and on/off flags:

parser.add_argument('filename')           # positional argument
parser.add_argument('-c', '--count')      # option that takes a value
parser.add_argument('-v', '--verbose',
                    action='store_true')  # on/off flag

The ArgumentParser.parse_args() method runs the parser and places the extracted data in a argparse.Namespace object:

args = parser.parse_args()
print(args.filename, args.count, args.verbose)

No comments:

Post a Comment