Home
Python
argparse (Command-Line Arguments)
This page was last reviewed on Mar 28, 2024.
Dot Net Perls
Argparse. 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.
getopt
Example. 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.
Step 1 We create an ArgumentParser and specify its description. The description is shown when the help command is specified.
Step 2 For each argument we want to handle, we must call add_argument. We specify "store" as the action, and also make "file" required.
Step 3 We parse the arguments at this stage by calling parse_args. The "file" argument will be available at args.file.
Step 4 The goal of the program is to print out the specified file, so here we call open() and read() to with args.file as the file name.
File
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.txt
Some 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 28, 2024 (edit link).
Home
Changes
© 2007-2024 Sam Allen.