What is the `prog` argument in argparse module in Python?

Python provides a built-in module, argparse, to parse command-line arguments. This makes working with the command line very easy and hassle-free as compared to using sys.argv and manually parsing the arguments.

The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.

Prog

By default, the --help option will display the name of the current script that is running, regardless of where you invoke it from. For example, the following code will show main.py as the program name.

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()

argparser uses the sys.argv[0] argument to get the name of the program. This default behaviour can be overwritten by setting the prog argument when creating the parser object, as shown below.

import argparse
parser = argparse.ArgumentParser(prog='MyProgram')
parser.add_argument('--foo', help='foo help')
args = parser.parse_args()

This code will now show the name of the program as MyProgram instead of main.py.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved