preamble
argsparse is a standard module for python's command line parsing, built into python and does not need to be installed. This library allows us to pass arguments to a program and have it run directly from the command line.
* really, today is my first time to learn argsparse. because I can't use it, naturally there is no motivation to learn. But now the computer is a bit laggy, every time I open pycharm is too laggy, forcing me to start using the command line to test the code.
Pass a parameter
We first create a new desktop "arg learning" folder, the folder in the new file, to see an example of the use of the simplest argsparse library.
import argparse parser = (description='Pass a number on the command line') #type is the data type of the parameter to be passed in help is the hint for that parameter parser.add_argument('integers', type=str, help='incoming numbers') args = parser.parse_args() # Get the incoming parameters print(args)
In this code, we pass a number at the command line. The way to use this is to open the command line and first cd the working directory to arg learning
cd desktop/argdo
Then type python -h or python --help on the command line, in this case I type
python -h
The results of the run as seen on the command line are as follows
usage: [-h] integers Passing numbers on the command line positional arguments: integers incoming numeric optional arguments: -h, --help show this help message and exit
Now we pass in a parameter 5 on the command line.
python 5
Run it, and the resulting run is
Namespace(integers='5')
Manipulating the args dictionary
Actually getting this result Namespace(integers='5') is a data type similar to a python dictionary.
We can extract this parameter using arg.parameter name
import argparse parser = (description='Pass a number on the command line') #type is the data type of the parameter to be passed in help is the hint for that parameter parser.add_argument('integers', type=str, help='incoming numbers') args = parser.parse_args() # Get the integers parameter print()
Run python 5 on the command line , which results in
5
Pass multiple parameters
Now pass multiple arguments on the command line, such as 1, 2, 3, and 4.
python 1 2 3 4
runtime error (computing)
usage: [-h] integers : error: unrecognized arguments: 2 3 4
Can not recognize 2 3 4, look at the source code we know that the integers parameter is a positional parameter, indicating that the first number 1 is recognized. Here we need to change the code
import argparse parser = (description='Pass a number on the command line') parser.add_argument('integers', type=str, nargs='+',help='incoming numbers') args = parser.parse_args() print()
nargs is used to indicate the number of arguments passed in, and '+' indicates that at least one argument was passed in. At this point, re-running python 1 2 3 4 on the command line gives you
['1', '2', '3', '4']
Changing the data type
The type parameter in add_argument sets the data type of the incoming argument. We see that there is a keyword type in the code, which can be passed in as list, str, tuple, set, dict, etc. For example, if we change the above type=str to type=int, then we can do the four rules. For example, we put the above type = str, changed to type = int, then we can do the four operations.
import argparse parser = (description='Pass a number on the command line') parser.add_argument('integers', type=int, nargs='+',help='incoming numbers') args = parser.parse_args() #Summing up incoming data print(sum()
Type python 1 2 3 4 at the command line, and the result will be
10
position parameter
When you pass parameters on the command line, the results will often be different depending on the order in which the parameters are passed in, because of the positional parameters, such as
import argparse parser = (description='Name') parser.add_argument('param1', type=str,help='Surname') parser.add_argument('param2', type=str,help='Name') args = parser.parse_args() #Print Name print(args.param1+args.param2)
Typing python Zhang San and python San Zhang on the command line gives the following results, respectively
John Doe
cap (a poem)
triple
If we change the code
parser.add_argument('param1', type=str,help='Surname')
cap (a poem)
parser.add_argument('param2', type=str,help='Name')mutual
Switch positions, i.e., lines 4 and 5 of code, and re-run the
python Zhang San and python San Zhang, the results are as follows
triple
cap (a poem)
John Doe
Optional parameters
To avoid the above bug with positional parameters on the command line (it's easy to forget the order), you can use an optional parameter, which is kind of like a keyword passing parameter, but you need to precede the keyword with --, e.g.
import argparse parser = (description='Name') parser.add_argument('--family', type=str,help='Surname') parser.add_argument('--name', type=str,help='Name') args = parser.parse_args() #Print Name print(+)
At the command line, type
python --family=sheet of paper --name=surname San
running result
John Doe
Optional parameters are more cumbersome to write, but they increase readability on the command line and are less likely to cause data to be misplaced because of the order in which the parameters are passed in.
default value
There is a default parameter in add_argument. Sometimes it is necessary to set a default value for an argument, i.e., if the value of the argument is not passed on the command line, the program uses the default value. If the parameter is passed on the command line, the program uses the value passed. See the following example
import argparse parser = (description='Name') parser.add_argument('--family', type=str, default='Zhang',help='Surname') parser.add_argument('--name', type=str, default='Three', help='Name') args = parser.parse_args() #Print Name print(+)
At the command line, type python, python --family=Lee, etc.
The results of the runs are
John Doe
cap (a poem)
Li San (1913-1995), third governor of Hainan
Required parameters
The add_argument has a required parameter that sets whether the argument is required or not.
import argparse parser = (description='Name') parser.add_argument('--family', type=str, help='Surname') parser.add_argument('--name', type=str, required=True, default='', help='Name') args = parser.parse_args() #Print Name print(+)
Type python --family=chang on the command line and run the result
usage: [-h] [--family FAMILY] --name NAME : error: the following arguments are required: --name
Because the optional parameter name has required=True, it must be passed in. If we change it to False, the program runs as follows
sheet of paper
The above is python argparse module pass parameter usage example details, more information about python argparse module pass parameter please pay attention to my other related articles!