Skip to content

[Python] How to use "argparse" module to give the arguments in terminal

Last Updated on 2021-04-07 by Clay

argparse is a module in Python and it can help us to set the parameters we need. The package can give our Python scripts some parameters from the terminal.

Let's take a look at a simple example.

argparse

from argparse import ArgumentParser

parser = ArgumentParser()

# basic option
parser.add_argument('-num_01', dest='a', help='the first input number')
parser.add_argument('-num_02', dest='b', help='the second input number')


Output:

-num_01 and num_02 are the parameters we need. and the "help" at the back is the description we gave to the parameter field.

And then, we define a simple function:

def sumOF(a, b):
    print(int(a)+int(b))


This function can print the answer a+b when we input a and b.

if __name__ == '__main__':
    a = parser.parse_args().a
    b = parser.parse_args().b
    sumOF(a, b)


Finally, don'y forget to store the parameters value into the variables when the program is executed.

If we forgotten the step, even if we give the parameters from outsides, the computer (or Interpreter) does not understand what we are going to do with these parameters!

The picture is too small, I'm sorry about that!

As we can see above, I have given the parameter fields -num_01 and -num_02 written in advance to 1, 7, respectively.

The next line is simply printed the answer: 8


My Idea

Is this a very convenient feature?

It is even better to execute the shell file with Linux OS! (Of course, each OS definitely has its own way of automating the process, but I'm familiar with Linux, just to mention this.)


References

Tags:

Leave a ReplyCancel reply

Exit mobile version