How can I read and process (parse) command line arguments?
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:
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:
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:
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.
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:
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.
Was this article helpful?