Home
Python
argparse (Command-Line Arguments)
Updated 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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 28, 2024 (edit link).
Home
Changes
© 2007-2025 Sam Allen