Explain Codes LogoExplain Codes Logo

Display help message with Python argparse when script is called without any arguments

python
prompt-engineering
best-practices
tools
Nikita BarsukovbyNikita Barsukov·Dec 25, 2024
TLDR

Trigger an argparse help message by default when no arguments are passed with this snippet:

import argparse, sys class ArgumentParserError(Exception): pass class ShowHelpParser(argparse.ArgumentParser): def error(self, message): self.print_help() raise ArgumentParserError(message) parser = ShowHelpParser() parser.add_argument('action', help='the action to perform') try: args = parser.parse_args(sys.argv[1:]) or parser.error("You forgot to provide arguments! 🙀") except ArgumentParserError: sys.exit(2) # This is your script's way of saying, "I am technically leaving, but I'm not happy about it."

This neat snippet creates a custom parser by subclassing argparse.ArgumentParser and raising a special exception if arguments are missing. The try-except block handles this to display help and exit gracefully.

Peeling the onion: argparse and errors

The argparse expectation

The argparse module is designed with the expectation that at least one command-line argument will be passed. It’s like a ride at the fair, "you must be at least one argument tall to ride this script". If users forget to provide this crucial input, we gracefully present the help message.

Custom error tricks with argparse

By default, argparse will display an error message and the usage information when the command line args are not as expected. We customise this by subclassing ArgumentParser and providing a custom error method that calls print_help instead, it's like {insert witty joke here}.

Leaving in style with sys.exit(2)

Using sys.exit(2) ensures that the script exits with a status code indicating an error, but only after displaying the help message. The choice of 2 here is like the script's passive-aggressive way of saying, "I did my job, but I want you to know I'm not happy about it."

Catching other stones: beyond basic argparse errors

When you're dealing with more complex command structures, add_subparsers() can feel like navigating a maze blindfolded. Here, the default function feature of argparse's set_defaults can be the guiding hand, providing a specific action when a subparser is called without arguments.

Missing positional arguments: the forgotten soldiers

Handling errors related to missing positional arguments can be tricky. It's like a party where argparse counts the guests and finds someone missing. We can apply a focused try-except around parse_args to catch the ArgumentParserError and ensure an appropriate help message is revealed, like a magician revealing his tricks!

Polishing the script: usability and beyond

Display a summary with print_usage

Sometimes, a long lecture isn't what is needed. ArgumentParser.print_usage() provides a quick summary of command line structure without the detailed explanations and metadata of the full help message. It's like a quick PSA before the main event.

Default values: the argparse safety net

Consider setting default values using parse_args as an if-else condition to check for arguments, much like setting a safety net when the circus trapeze artist (user) fails to land a jump. Your script becomes more flexible and user-friendly in the absence of provided input.

Exit codes: the final communication

Ensure that sys.exit provides a fitting exit code that appropriately reflects the script's state. Like a police officer using hand signals to manage traffic, non-zero exit codes like 1 or 2 indicate errors in the script's execution.

The treasure trove: tips and tricks

Default values: the knight in shining armor

Setting default functions using set_defaults() is akin to having a knight in shining armor at the ready, providing your script with a meaningful activity in the sight of no arguments.

The sys.argv radar

Use sys.argv to check if the script is called without arguments like a radar scanning the horizon. If it finds no incoming planes (arguments), it signals the usage instructions.

The enriched parse_args() breeze

Just like a master composer orchestrating a symphony, employ parse_args() to capture the essence of user input and guide them with the help message, delivering a sonata of helpful command line syntax.