Parse Args in Python: What you must know

By JoeVu, at: June 15, 2023, 7:06 a.m.

Estimated Reading Time: 7 min read

Parse Args in Python: What you must know
Parse Args in Python: What you must know

Parse Args in Python: What you must know

 

Introduction

In many Python applications, particularly those run from the command line, it's essential to handle command-line arguments effectively. Parsing arguments allows your script to accept inputs from users, making it more flexible and powerful. Python's argparse module provides a robust way to handle command-line arguments, making it easy to build user-friendly command-line interfaces. In this guide, we'll explore how to use argparse to parse command-line arguments in Python.

Have you ever seen sth like that?

import sys

def main():
    if len(sys.argv) < 3:
        print("Not enough arguments!")
        return
    
    arg1 = sys.argv[1]
    arg2 = sys.argv[2]
    
    if arg1 == 'option1':
        print(f"Option 1 selected with value {arg2}")
    elif arg1 == 'option2':
        print(f"Option 2 selected with value {arg2}")
    else:
        print("Unknown option!")

if __name__ == "__main__":
    main()

 

What is the issues with this script?

  1. No Help Message: The script does not provide any help or usage message to guide the user on how to use it.
     
  2. Minimal Error Handling: The script only checks if there are fewer than two arguments and prints a vague error message.
     
  3. Poor Argument Validation: The script does not validate the arguments beyond checking if the first argument matches 'option1' or 'option2'.
     
  4. Hardcoded Logic: The logic is hardcoded and inflexible, making it difficult to extend or modify.

 

What is argparse?

argparse is a module in the Python standard library that helps you create command-line interfaces. It allows you to define the arguments your program requires, parse those arguments, and automatically generate help and usage messages. This makes it easier to handle command-line input and provide a better user experience.

 

Basic Usage of argparse


Step 1: Import argparse

First, you need to import the argparse module:

import argparse

 

Step 2: Create a Parser

Next, create an ArgumentParser object. This object will hold all the information necessary to parse the command-line arguments:

parser = argparse.ArgumentParser(description='Example script to demonstrate argparse.')

 

Step 3: Define Arguments

You can define the arguments your program requires using the add_argument method. Each argument needs a name and, optionally, a type, default value, help message, and other attributes:

parser.add_argument('input', type=str, help='Input file path')
parser.add_argument('output', type=str, help='Output file path')
parser.add_argument('--verbose', action='store_true', help='Increase output verbosity'

 

Step 4: Parse Arguments

Once you've defined the arguments, use the parse_args method to parse the arguments from the command line:

args = parser.parse_args()

 

Step 5: Use Arguments

After parsing, you can access the arguments as attributes of the args object:

input_path = args.input
output_path = args.output
verbose = args.verbose

if verbose:
    print(f'Input file: {input_path}')
    print(f'Output file: {output_path}')

 

Sample Scripts

Here's a complete example script that demonstrates the basic usage of argparse:

import argparse

def main():
    parser = argparse.ArgumentParser(description='Example script to demonstrate argparse.')
    parser.add_argument('input', type=str, help='Input file path')
    parser.add_argument('output', type=str, help='Output file path')
    parser.add_argument('--verbose', action='store_true', help='Increase output verbosity')

    args = parser.parse_args()

    input_path = args.input
    output_path = args.output
    verbose = args.verbose

    if verbose:
        print(f'Input file: {input_path}')
        print(f'Output file: {output_path}')
    
    # Add your main script logic here

if __name__ == '__main__':
    main()


If we run this script, it will tell you how to use the script properly

❯ python test_script.py
usage: test_script.py [-h] [--verbose] input output
test_script.py: error: the following arguments are required: input, output

 

Advanced Features


Positional and Optional Arguments

  • Positional Arguments: These are mandatory and must be provided in the correct order.
     
  • Optional Arguments: These are optional and can be provided in any order. They typically start with - or --.
     

Argument Types and Default Values

You can specify the type of an argument (e.g., int, float, str) and set default values:

parser.add_argument('--count', type=int, default=1, help='Number of times to repeat the message')

 

Choices

You can restrict an argument to a set of predefined choices:

parser.add_argument('--method', choices=['add', 'subtract', 'multiply', 'divide'], help='Mathematical operation to perform')

 

Required Arguments

Optional arguments can be made required:

parser.add_argument('--log', required=True, help='Log file path')

 

Generating Help and Usage Messages

The argparse module automatically generates help and usage messages for your script. Run your script with the -h or --help flag to see these messages:

$ python script.py -h

Output:

usage: script.py [-h] [--verbose] input output

Example script to demonstrate argparse.

positional arguments:
  input       Input file path
  output      Output file path

optional arguments:
  -h, --help  show this help message and exit
  --verbose   Increase output verbosity

 

Conclusion

Using argparse to parse command-line arguments in Python is an efficient way to create flexible and user-friendly command-line interfaces. By defining clear and comprehensive argument structures, you can enhance the usability and functionality of your scripts. Start incorporating argparse in your Python projects today and experience the benefits of streamlined argument parsing.

Few other alternatives that we can use:


Related

Python Experience

[TIPS] Python - Get current path

Read more
Python Learning

[Tips] Python DotDict Class

Read more
Subscribe

Subscribe to our newsletter and never miss out lastest news.