| by Arround The Web | No comments

Python Command Line Parsing Tutorial

The parsing for command line arguments was formerly included in the default Python library “argparse”. By enabling user input values to be somehow parsed and then used, “argparse”. It offers flexibility and reuses your code in place of manually setting variables as part of the code.

Example 1

We will implement the succeeding code to show the structure and usage of an argparse library.

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('--name', type=str, required=True)

args = parser.parse_args()

print('Hi,', args.name)

The “argparse” library would be imported at the commencement of the code. The parser is initialized by ArgumentParser(), so we’ll be able to begin adding custom parameters. Use parser.add_argument() function to add desired arguments. The “name”, “type”, and “required” will be given as the arguments of this method. The ‘required’ attribute is a Boolean indicating whether the following command line field is executed, and the “type” argument shows the variable type specified as an input. We set the value of the “type” argument as “str” and “required” as “True”. The function parse_args() will be called. The “args.name” attribute seems to be the name of such an argument identified with the add_argument() function.

The previous code produces this type of result as shown:

As we can see, this will raise an error since the “name” argument is necessary but is lacking. When we add –name, we get the following output:

Example 2

There are certain situations when we don’t want to argue regarding the name that might be used for the flag. One may utilize a positional parameter to avoid having to supply the –name flag before entering the actual value.

Here, we will multiply the positional arguments by specifying the parameters.

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('--i', type=int, required=True)

parser.add_argument('--j', type=int, required=True)

args = parser.parse_args()

product = args.i * args.j

print('Product:', product)

The parser was first generated after importing the “argparse” module. The variables “i” and “j”, two integer-type arguments that must be true, were then added. After that, product formulae will be applied after parsing the parameters. We employ the print() function to display the product.

Example 3

In this instance, we do multiplication without specifying the positional parameters.

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('k', type=int)

parser.add_argument('l', type=int)

args = parser.parse_args()

product = args.k * args.l

print('Product:', product)

First, integrating the “argparse” package, the parser was initially constructed using the ArgumentParser() method. The “k” and “l” are the two arguments specified with the integer type. Although positional arguments keep a command line clearer, we do not provide the “required” attribute here. Afterward, the given parameters were parsed with the help of the parse_args() method. We will define a product function using the variables “k” and “l”. To show the outcome, we will utilize the print statement.

Example 4

Optional arguments might be helpful whenever we want to provide a user with some choice to use functionality. We simply specify the optional parameter using the add_argument() function to add an optional argument.

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('--name', type=str, required=True)

parser.add_argument('--Class', type=int)

args = parser.parse_args()

if args.Class:

  print(args.name, 'in', args.Class, 'class.')

else:

  print('Hey,', args.name + '!')

We start the program by incorporating the “argparse” library. We first established a parser using the ArgumentParser() method to execute two parser arguments. Now, we will call add_argument() function to add different parameters. These arguments include two variables, name and class, where the “name” argument is of the type “string”, and it must be true. The “class” parameter has the type “integer”.

Moreover, after parsing the parameters, we utilize the “if-else” condition. Inside this, we have been applying the print() function twice, once by the “if” statement and again by the “else” statement, to represent the output. The arguments in print() methods vary in both these cases. The arguments given in the first print() function include name and class. At the same time, the arguments presented in the second print() method include args.name.

After running the code, we obtain the two outputs as given below. We get the first output after using the optional arguments and the second without the optional arguments.

From the previous two different outputs, we can observe that there is a difference between both outputs because of using the optional arguments in one and not in the other.

Example 5

Let’s imagine that rather than asking the user to provide “x” and “y” inputs, we want to have the user enter a range of numbers and the script, which would then return the total of all those numbers. As we cannot predict how many values a user will enter, it isn’t necessary to build a new argument for every new value. The number (or inputs) the argument can accept may be specified using the “nargs” option in the add_argument() function.

We will provide multiple input arguments and print the result in this case.

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('--values', type=int, nargs=5)

args = parser.parse_args()

sum = sum(args.values)

print('Sum:', sum)

We initiate by importing the “argparse” library, which is required for executing the previous code. We will create a parser by calling the ArgumentParser() method. This function contains no argument. Next, the add_argument() method will be invoked. This method has three parameters. In the case of multiple input arguments, we have utilized the “nargs” attribute inside the add_argument() method. Now, we will call the parse_args() function for parsing. We apply the sum() method to find the sum of the values. To depict the output, we utilized the print statement.

Example 6

What if we want the sum of more inputs than five values? We may make the argument accept any number of values by setting nargs=’+’.

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('--values', type=int, nargs=’+’)

args = parser.parse_args()

sum = sum(args.values)

print('Sum:', sum)

We may execute the script with just about any number of input values. Here, we use the same code as earlier, but, in this code, we will be changing ‘nargs’=5 to ‘nargs’=’+’.

Conclusion

This article covered a variety of Python command-line parsing techniques, such as simple arguments, positional arguments, optional arguments, and multiple input arguments. It also provided examples to see how the output changes depending on whether an argument is used or not. We may utilize examples to examine and comprehend whether an argument is appropriate in a certain circumstance.

 

Share Button

Source: linuxhint.com

Leave a Reply