Today, in the 27th installment of our Python series, we’ll take a look at Argparse, the command-line argument tool in Python.

The command-line parameter tool is a very common tool. For example, when we do experiments and want to adjust parameters, if the parameters are hard-coded in the code, we need to modify the corresponding code and logic every time we modify parameters, which is obviously not convenient. It is better to set the necessary parameters to be passed in from the command line so that we only need to modify them at run time.

sys.argv

The easiest way to parse arguments passed from the command line is through sys.argv, which retrieves arguments passed from the command line.

import sys



print(sys.argv)

Copy the code

The usage is simple, just call sys.argv. Argv is an array that can be accessed by subscripts if there are multiple arguments. It is important to note, however, that the results stored in argv start with a Python call.

Let’s take a look at an example where we pass in random arguments like print sys.argv.

python test.py -a -c -d=222 

>>>['test.py'.'-a'.'-c'.'-d=222']

Copy the code

This means that python runs the test.py file name as one of the arguments, so we need to start with argv[1] to get the custom argument.

The advantage of sys.argv is that we only need to access it to get the arguments passed in. But the disadvantage is also obvious, is too few features. If we were looking at other god’s code, we wouldn’t be able to figure out what parameters to pass in at run time and what each parameter means.

To solve this problem, we need to use a tool that encapsulates more functionality and is at the heart of this article, ArgParse.

Basic usage

Argparse is a Python library. We need to import argparse first. Argparse is a Python library that comes with Python and does not need to be installed.

Before we can use it, we need to initialize the parse, which is a parameter parser.

ArgumentParser can be passed a string indicating the purpose

parser = argparse.ArgumentParser()

parser.parse_args()

Copy the code

At this point, we already have a parser. We can pass -h, which stands for help, at run time to see the parameters defined in the current parser. And since we don’t have anything right now, all we can display is help.


Will choose parameters

First, we’ll look at mandatory parameters, which are defined the same way as mandatory parameters in functions, that is, parameters that we need to run the program. If not, then the program should not execute will report an error and prompt.

The way to define mandatory arguments is very simple; we just pass in the name of the argument through add_argument.

import argparse



parser = argparse.ArgumentParser("For test the parser")

parser.add_argument('test')

args = parser.parse_args()



print(args.test)

Copy the code

This defines a parameter named test, which we can access through args.test.

Py -h: test.py -h: test.py -h: test.py -h: test.py


The required parameter is passed in as test without prefix. So we can just run python test.py XXX.

Optional parameters

If there are mandatory parameters, there are optional parameters. Since optional parameters are optional, we need to add the identifier – or — before the parameter when we use it. For example, if we call the parameter test, we can define it as -test or –test, either way, or we can define both.

parser.add_argument('-test'.'--test')

Copy the code

The optional arguments include test and –test.


Print the name of the parameter, but it does not tell us what the parameter does. For example, the “help” parameter is followed by “show this help message” and “exit”. What if we also want help to tell us what the argument does?

We can use the help parameter to pass in the prompt that we want to print, so that the user can know about the parameter when using it.

For example, let’s change this line to:

parser.add_argument('-test'.'--test', help='just for help')

Copy the code

So when we run it, we should see the message:


The default value

If you have a lot of arguments, sometimes you don’t want to specify a value for each one, but you want to have a default value if you don’t. This is a perfectly normal idea, and it’s easy to do, specifying it with the default parameter.

import argparse



parser = argparse.ArgumentParser("For test the parser")

parser.add_argument('-test'.'--test', default=1, help='just for help')

args = parser.parse_args()



print(args.test)

Copy the code

For example, we set the default value of the test parameter to 1 in our code. When we run, if we do not set the test parameter, the program will use its default value of 1.

However, the default value information will not be printed in help, so we need to tell the user what the default value is in the prompt.

type

We can define the default value of a parameter, and of course we can define its type.

Since the arguments passed by the command line are all strings by default, using STR would have to convert itself if we wanted to do math, which would be inconvenient. We can match the type as soon as the argument is passed in, so that if the argument is of the wrong type, an error is reported.

This is also easy to do with the type parameter.

parser.add_argument('-test'.'--test', default=1, type=int, help='just for help')

Copy the code

For example, if we define a parameter of type int and we pass it a type mismatch, we will get an error:


It is clear in the error message that we are getting an invalid int, which is ABC.

An optional value

It also supports optional values, which is pretty straightforward, meaning we want to limit the range of parameters passed in to just a few values. For example, we want to pass in a value that is either 0 or 1, or one of several specific values, which we can do with the Choices argument.

The choices argument passes in a list, which is our restricted range, and only values in that range are allowed.

parser.add_argument('-test'.'--test', default=1, choices=[2.3.4], type=int, help='just for help')

Copy the code

If we run test=1, we get an error telling us that the value passed in is not in the choices range.


This is an interesting example. If you look closely, you will see that we have set the default value to 1, but there is no 1 in the optional value. This is also allowed, the default value may not be in the optional value range, but when we pass in 1 the optional value check is triggered.

action

Action is a magic and useful operation that specifies how arguments should be handled. Our default is store, which means store, which we all understand. In addition, there is store_true, which means true if present and false otherwise.

parser.add_argument('-test'.'--test', action='store_true', help='just for help')

Copy the code

When we change the definition of the test parameter to this, we can compare the results of the run.


In addition to store_true, there is store_const, which is specified as a fixed value when present.

parser.add_argument('-test'.'--test', action='store_const', const=23, help='just for help')

Copy the code

So when we specify the -test argument, it will automatically be assigned 23.

In addition to these two, another common parameter is append, which automatically stores the same parameter multiple times into a list.

parser.add_argument('-test'.'--test', action='append', type=int, help='just for help')

Copy the code

nargs

Nargs is also a very useful parameter that allows you to do some fancy manipulation with parameters. Nargs takes the following arguments, starting with N, which is an integer. Represents the ability to receive N parameter values, which will be stored in a list.

parser.add_argument('-test'.'--test', nargs=2, type=int, help='just for help')

Copy the code

Another argument passed in is ‘+’ or ‘*’, which can store any number of values into a list.

parser.add_argument('-test'.'--test', nargs=The '*', type=int, help='just for help')

Copy the code

conclusion

With Parser, it’s much easier to handle command-line arguments in Python, and we can do all sorts of customizations. In addition to what we have introduced above, there are some other methods that are relatively less common, so I will not exhaust them all, and interested students can learn about them by themselves.

This is the end of today’s article, if you like this article, please invite a wave of quality sanlian, give me a little support (follow, forward, like).

– END –

Original link, ask a concern