Explain Codes LogoExplain Codes Logo

How can I read and process (parse) command line arguments?

python
prompt-engineering
functions
advanced-parsing
Alex KataevbyAlex Kataev·Jan 1, 2025
TLDR

If you need to tackle command line arguments in Python, opt for argparse module. Let's see this in a trimmed-down example for parsing an integer list:

import argparse # Initiate the parser (let the parsing magic begin!) parser = argparse.ArgumentParser(description="A little demo with an integer list.") # Define arguments parser.add_argument('ints', metavar='N', type=int, nargs='+', help='just an integer, nothing fancy') # Run parse_args() (cast the parsing spell!) args = parser.parse_args() # Directly interact with args.ints print(args.ints)

Hit your script with arguments like: python script.py 1 2 3. Now, the argparse module will autonomously create help and usage messages and throw errors if a user presents invalid arguments. Talk about being self-dependent!

Squeeze the most out of argparse

When your python scripts start acting like a movie and bring about more complications, argparse steps in to manage multiple argument types. Flexible to specify the behaviour (action) of each argument, customisable variable names (dest), and control the range of values (choices), all make it a sweetheart for building robust command-line interfaces (CLIs).

Tackling flags with style

Dealing with toggles like --verbose or --quiet in your CLI? Give a round of applause to store_true and store_false in argparse. They morph flags into corresponding boolean values making it a piece of cake to switch features on and off in your application:

# Make some verbose noise, will ya? parser.add_argument('--verbose', action='store_true', help='crank up the output verbosity')

Bossing complex tasks with sub-commands

For tasks that compete with the complexity of quantum physics, argparse supports sub-commands. This structures your CLI as a network of mini-actions, each having its own handler, kinda like git does with commands such as push, pull, and commit.

Getting to know metavar

Neat freaks, assemble! The metavar keyword let's you give a user-friendly name to positional arguments that it displays in help messages.

Switching gears to sys.argv

Find argparse too "extra" for your script? Say hello to sys.argv, a simpler alternative. Import the sys module, and all the passed arguments are at your disposal as a list. Just note, sys.argv[0] is the script name itself, not an argument.

Parsing all the way with sys.argv

Here's the fastest way to print arguments sans the script name:

import sys # Me and the arguments, no script name, promise! print(sys.argv[1:])

However, sys.argv neither provides custom error or help texts like argparse does, nor has the capacity to cook you dinner. Jokes apart, remember unlike argparse, the order of arguments matters with sys.argv.

Advanced parsing tricks: The cloaked Dumbledore of Python

Once argparse becomes your best coding mate, there's a sea of advanced techniques waiting to be dived into for specific requirements.

Fencing arguments with multiple choices

Gotta restrict over-adventurous user inputs? Use the choices parameter to block invalid entries. This guarantees that arguments stay in a set range - only what's acceptable.

# This path, grasshopper parser.add_argument('--direction', choices=['up', 'down', 'left', 'right'], help='pick a path')

Pouring in variable number of arguments

Employ the nargs option to process a variable count of arguments for options, providing a Vegas-level flexibility to user inputs:

# Bring on the tags, all of them! parser.add_argument('--tags', nargs='*', help='To tag, or not to tag')

Molding types and conversions

Sharpshooter targeting specific input types? Specify the type for your arguments. Use Python's built-in types or custom conversion functions for outfitting and validating user inputs.

# Only integer ports allowed here, mate! parser.add_argument('--port', type=int, help='Enter a port number, please')