Python command line parameter parsing tutorial
1. Basic introduction: sys.argv quick acquisition
If you just want to get the original string typed by the user,sys.argvis the fastest way. It is a list, the first element is always the name of the script itself (e.g.script.py), followed by any space-separated input.
Save the above code asbasic_argv.py, run in the terminal:
The output will be:
Although this method is straightforward, its shortcomings are also obvious: No type checking, no constraint logic, no help documentation - if the tool is slightly more complicated, you and your users will collapse.
2. Core tool: argparse standard library
As long as your command line tool requires a more formal user experience, Python comes withargparseThat's the first choice. It does not require additional installation and can be automatically generated-h/--helpHelp documentation and covers most command line scenarios.
2.1 Three steps to build the framework
useargparseThe process is very simple, only three steps:
- Create a
ArgumentParserObject (equivalent to a "parameter storage box") - pass
add_argument()Add various parameter rules to the box - Call
parse_args()Parse the parameters and get an attributed object
It's that simple! runpython my_cli_tool.py -h, you will immediately see a clearly structured help message.
2.2 Five commonly used parameter types
① Positional parameters (required, no short/long options)
Positional parameters are bound in the order entered by the user, and are suitable for core content that logically must be filled in first, such as file paths and operation names.
② Optional parameters (with short/long options)
Optional parameters can be given in any order, suitable for non-core content such as switches and configuration items. Short options are usually single letters (e.g.-u), long options are more readable (e.g.--user)。
③ Optional parameters with default values
Setting default values for optional parameters can reduce the user's burden. Default values are listed in the help documentation.(default: xxx)automatically displayed.
④ Type conversion and verification
By default, all parameters are treated as strings. passtypecan be automatically converted toint、floatOther types, and even custom verification functions.
Tip: The custom validation function will immediately throw a clear error when the user enters an illegal value, which is a much better experience than parsing and then checking.
⑤ Boolean switch parameters
This parameter does not need to be followed by a value. As long as it appears in the command line, it will be automatically set toTrue(orFalse). passactionParameter control.
⑥ Limit selected parameters
usechoicesLimit the input to a value in the specified list, and the help document will automatically list these options.
2.3 Complete practical example: database backup tool
Integrate the above knowledge points and write a simple but complete MySQL backup tool template.
run nowpython db_backup.py -hTake a look at the automatically generated help document, and you will feel real peace of mind - you no longer have to write a bunch of instructions by hand.
2.4 Advanced: Grouping + Subcommands
When the number of parameters exceeds 10, or there are multiple independent functions in a tool (such as "backup" and "restore"), you can use grouping and subcommands to make the user's input more organized.
Parameter grouping
By grouping related parameters under the same heading, the help documentation immediately becomes clear:
Subcommands
Subcommands are equivalent to splitting a large tool into several independent small commands, likegit addandgit commitThat way. usesubparsersCan be achieved easily.
3. Modern alternative (requires installation)
AlthoughargparseIt is powerful enough, but if you are pursuing more concise syntax or more modern interactive experience, you can take a look at the following two third-party libraries.
3.1 Click
ClickUse decorators to define commands with very elegant syntax. It also thoughtfully provides functions such as password hiding.
Install:pip install click
3.2 Typer (based on Click)
TyperFully embracing Python type hints, the readability and maintainability of the code are directly improved, and automatic completion is also supported.
Install:pip install typer
4. Summary of best practices
- must be written
help: This is the most basic respect for users (and yourself in the future) - Set reasonable default values: For example, port default
3306, format defaultjson - Parameter naming should be intuitive: Try to use complete words for long options, and use meaningful single letters for short options.
- Validate input early: Take advantage
typeCustom verification function is much more friendly than checking after parsing - Complex tools use subcommands: Avoid stacking all parameters together
5. Quick decision table
No matter which one you end up choosing for your project,
argparseThese are the basics that every Python developer must have a solid grasp of. On this basis, just choose more modern alternatives based on specific needs.

