“Explain Open Source project series” launched — let the people who are interested in open source project no longer fear, let the initiator of open source project no longer feel lonely. Follow along as you discover the joys of programming, use, and how easy it is to get involved in open source projects. Welcome to contact us to contribute to us, so that more people fall in love with open source, open source contribution ~
preface
Have you ever wondered how a command gets parsed when you type it on the command line? Ever consider implementing your own command-line tool to perform and process tasks for you? Did you know that Python has a rich library at your side to help you easily build command-line tools?
Take your time. This first installment of the Python command line tour will take you step-by-step through command line parsing using Python’s built-in Argparse standard library, followed by a series of articles about the differences and similarities between featured third-party command line libraries. And experience the journey of discovery in its entirety.
This series of articles uses Python 3 as the interpreter by default. If you are still using Python 2, be aware of the differences in syntax and library usageCopy the code
introduce
Argparse, Python’s built-in standard library, provides an easy way to write command-line interfaces. When you define parameters in your program, Argparse takes command line input from sys.argv, parses it, responds to correct or invalid input, and automatically generates help information and instructions.
Quick start
Setting up the parser
The first step is to set up the parser on which subsequent command line parsing depends, which converts the command line string into a Python object. By instantiating argparse.ArgumentParser, given some optional arguments, we can set up a parser:
import argparse
parser = argparse.ArgumentParser(
description='My Cmd Line Program'.)Copy the code
Define the parameters
Use the argumentParser. add_argument method to set the argument information for the parser to tell it what in the command line string should be parsed into what types of Python objects, such as:
# add the nums parameter as num in the usage information
The value is of type int and supports multiple inputs, at least one of which must be provided
parser.add_argument('nums', metavar='num', type=int, nargs='+',
help='a num for the accumulator')
Add the --sum argument. The corresponding attribute is accumulate
If --sum is not provided, the default is Max function, otherwise sum is used
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the nums (default: find the max)')
Copy the code
Parsing command line
With the arguments defined, you can use the argumenteParser.parse_args method to parse a set of command line argument strings.
By default, the argument is taken from sys.argv[1:], which is a list of strings corresponding to a command (without a filename) that you type at the command line. For example, if python3 cmd.py –sum 1, 2, 3, sys.argsv[1:] is [‘–sum’, ‘1’, ‘2’, ‘3’].
Of course, you can also specify a set of command-line argument strings using the parse_args parameter:
args = parser.parse_args(['--sum'.'1'.'0'.'1'])
print(args) Accumulate =
, nums=[-1, 0, 1]
Copy the code
The business logic
Once the command line is parsed, we can obtain the value of each parameter from the parsed result, and then do further processing according to our business requirements. For example, for the numS parameters defined above, we can use the accumulate method as the result of the parse to maximize or sum them (depending on whether –sum is provided).
result = args.accumulate(args.nums)
print(result) # based on the above [' - sum ', '1', '0', '1'] parameter, the accumulate as the sum function, the result is 0
Copy the code
Code to comb
Are the steps for completing a command line tool fairly straightforward? Let’s summarize the above code to have a clearer understanding:
# cmd.py
import argparse
# 1. Set up the parser
parser = argparse.ArgumentParser(
description='My Cmd Line Program'.)# 2. Define parameters
parser.add_argument('nums', metavar='num', type=int, nargs='+',
help='a num for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the nums (default: find the max)')
Parse the command line
args = parser.parse_args()
# 4. Business logic
result = args.accumulate(args.nums)
print(result)
Copy the code
If we need to sum a set of numbers, we simply execute:
$ python3 cmd.py --sum -1 0 1
0
Copy the code
If we need to maximize a set of numbers, we simply do:
$ python3 cmd.py -1 0 1
1
Copy the code
If the given argument is not a number, an error message is displayed:
$ python3 cmd.py a b cusage: cmd.py [-h] [--sum] num [num ...] cmd.py: error: argument num: invalid int value: 'a'Copy the code
We can also view its automatically generated instructions and help with the -h or –help arguments:
usage: cmd.py [-h] [--sum] num [num ...] My Cmd Line Program positional arguments: num a num for the accumulator optional arguments: -h, --help show this help message and exit --sum sum the nums (default: find the max)Copy the code
summary
How’s that? After demystifying the command line tool, do you find that it is not as difficult as expected? A simple yet powerful grace?
But that’s not all argparse has. We haven’t covered complex cases like various types of parameters, parameter prefixes, parameter groups, mutex options, nested parsing, custom help, and so on.
In the next article, take a closer look at Argparse and its power.