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.
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 argparseparser = 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 argparseparser = 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