Many Python programs receive arguments from the command-line: this reduces the needs for constants and settings files. With argparse, a module, we can handle these arguments.
To use argparse, we must first call ArgumentParser
. Then we call add_argument
to set up the arguments, and finally we call parse_args
to parse them.
This program receives a "file" argument and then opens the specified file and prints out its contents. The file name is not stored in the program source code.
ArgumentParser
and specify its description. The description is shown when the help command is specified.add_argument
. We specify "store" as the action, and also make "file" required.parse_args
. The "file" argument will be available at args.file
.open()
and read()
to with args.file
as the file name.import argparse # Step 1: create argument parser with description. parser = argparse.ArgumentParser(description="Print file contents.") # Step 2: add file argument, and use store for the action. parser.add_argument("--file", action="store", help="print the file contents", required=True) # Step 3: parse the arguments. args = parser.parse_args() # Step 4: print out the specified file's contents. with open(args.file, "r") as f: print(f.read())python3 program.py --file example.txtSome example text.
Using argument parsing allows Python programs to be configured from the command-line, without requiring edits to the source code or settings files. Argparse leads to more robust programs.