Skip to content
On this page

argparse

In command-line programs, you often need to retrieve command-line arguments. While Python's built-in sys.argv provides a list of all arguments, it can become cumbersome for complex scenarios. The argparse library simplifies argument parsing significantly.

Example: Backing Up a MySQL Database

Suppose you want to create a command-line program to back up a MySQL database with the following parameters:

  • host: MySQL hostname or IP (defaults to localhost).
  • port: MySQL port number (int, defaults to 3306).
  • user: MySQL username (required).
  • password: MySQL password (required).
  • gz: Whether to compress the backup (defaults to False).
  • outfile: The backup file location (required).

The argparse implementation for this might look like this:

python
import argparse

def main():
    parser = argparse.ArgumentParser(
        prog='backup',  # Program name
        description='Backup MySQL database.',  # Description
        epilog='Copyright(r), 2023'  # Additional information
    )

    # Define positional argument
    parser.add_argument('outfile')
    
    # Define keyword arguments
    parser.add_argument('--host', default='localhost')
    parser.add_argument('--port', default=3306, type=int)  # Ensure int type
    parser.add_argument('-u', '--user', required=True)  # Short and long form
    parser.add_argument('-p', '--password', required=True)
    parser.add_argument('--database', required=True)
    
    # Boolean flag for gz compression
    parser.add_argument('-gz', '--gzcompress', action='store_true', help='Compress backup files by gz.')

    # Parse arguments
    args = parser.parse_args()

    # Print parsed arguments
    print('parsed args:')
    print(f'outfile = {args.outfile}')
    print(f'host = {args.host}')
    print(f'port = {args.port}')
    print(f'user = {args.user}')
    print(f'password = {args.password}')
    print(f'database = {args.database}')
    print(f'gzcompress = {args.gzcompress}')

if __name__ == '__main__':
    main()

Usage

When you run the script with valid parameters:

bash
$ ./backup.py -u root -p hello --database testdb backup.sql

You get:

parsed args:
outfile = backup.sql
host = localhost
port = 3306
user = root
password = hello
database = testdb
gzcompress = False

If you omit required parameters, argparse will provide an error message:

bash
$ ./backup.py --database testdb backup.sql
usage: backup [-h] [--host HOST] [--port PORT] -u USER -p PASSWORD --database DATABASE outfile
backup: error: the following arguments are required: -u/--user, -p/--password

Help Option

Using -h displays a helpful message:

bash
$ ./backup.py -h                          
usage: backup [-h] [--host HOST] [--port PORT] -u USER -p PASSWORD --database DATABASE outfile

Backup MySQL database.

positional arguments:
  outfile

optional arguments:
  -h, --help            show this help message and exit
  --host HOST
  --port PORT
  -u USER, --user USER
  -p PASSWORD, --password PASSWORD
  --database DATABASE
  -gz, --gzcompress     Compress backup files by gz.

Copyright(r), 2023

Summary

Using argparse streamlines the process of parsing command-line arguments, allowing you to define parameter types and easily retrieve validated input. This makes your command-line interface more user-friendly and robust.

argparse has loaded