argparse is a command-line parsing package for python that allows you to write highly readable programs as needed.
Many tutorials on the Internet more lengthy and diffuse, did not achieve the purpose of concise and good grasp, this article for the project on the use of argparse, with examples of the various parameters to explain, and strive to achieve the purpose of letting readers understand the second.
Let's start with the code.
import argparse if __name__ == '__main__': # Create command line parser handles and customize description information parser = (description='test the argparse package') # Define mandatory parameters positionArg parser.add_argument('positionArg') # Define optional parameter verbosity1 parser.add_argument('--verbosity1', '-v1', help='test the optional arguments') # Define the optional parameter verbosity2 and indicate that this option does not need to receive parameters by setting store_true, if no action is set, the default is to receive parameters, otherwise an error is reported parser.add_argument('--verbosity2', '-v2', action='store_true', help='test the action arg') # Specify the parameter type (default is str) parser.add_argument('x', type=int, help='test the type') # Optional range for setting parameters parser.add_argument('--verbosity3', '-v3', type=str, choices=['one', 'two', 'three', 'four'], help='test choices') # Set parameter defaults parser.add_argument('--verbosity4', '-v4', type=str, choices=['one', 'two', 'three'], default=1, help='test default value') args = parser.parse_args() # Returns a namespace print(args) params = vars(args) # Returns a dictionary of the attributes and attribute values of args for k, v in (): print(k, v)
Code samples written on the detailed comments, watch the comments can also understand each roughly.
More details on some of the special points below
action='store_true'
Indicates that the option does not need to take an argument, and sets the argument to true, but of course, if -v2 is not specified, the argument is false.
But if you remove action='store_true', you have to specify a value for -v2.
Program Usage Help
For example, if the program is named , the following statement can be executed at the command line:
python3 -h
Run to get help documentation for the function's usage:
The complete command line parameter execution commands and effects are as follows:
Of course, the value of the parameter can also be written in the form of an assignment, as shown below (equivalent to the command in the above figure):
python3 hehe -v1=verb1 --verbosity2 1 -v3=one -v4=two
The Namespace printed in the middle is the namespace returned by parameter parsing.
So, combined with examples, very concise and easy to understand, share. Of course, there are some other uses, here is only a list of some of the most common uses, in the use of the need, you can check the documentation.
The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.