본문 바로가기
Python

[Python] argparse module

by llHoYall 2021. 2. 3.

The argparse module makes it easy to write user-friendly command-line interfaces.

Basics of argparse Module

Let's make the application for argparse module, and using it.

 

main.py

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    args = parser.parse_args()

That's it. How easy and how simple!

 

Now, use our application.

$ python main.py xxx

$ python main.py -h

This is the magic of the argparse module.

Adding More Arguments

Adding simple arguments

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('-arg1')
    parser.add_argument('--arg2')
    args = parser.parse_args()

    print(args.arg1)
    print(args.arg2)

I will use this structure, and from now on I will omit the duplicated code.

If you see the result, you will be able to know how to use this.

Adding arguments with description

parser.add_argument('--arg3', help='This is the arg3')

 

Adding both short/long arguments

parser.add_argument('-arg4', '--arg4')

Adding on/off arguments

parser.add_argument('--arg5', action='store_true')

print(args.arg5)

Adding arguments with type

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

print(args.arg6)

You can also use other types like float and str.

Adding arguments with a default value

parser.add_argument('--arg7', default='Hello')

print(args.arg7)

Adding arguments with available value list

parser.add_argument('--arg8', choices=['apple', 'banana','cherry'])
parser.add_argument('--arg9', type=int, choices=range(1,4))

print(args.arg8)
print(args.arg9)

Adding arguments with a number of command-line arguments parameter

parser.add_argument('--arg10', type=int, nargs=2)
parser.add_argument('--arg11', type=int, nargs='+')
parser.add_argument('--arg12', type=int, nargs='*')
parser.add_argument('--arg13', type=int, nargs='?')

print(args.arg10)
print(args.arg11)
print(args.arg12)
print(args.arg13)

As you can see from the result, number means a number of arguments, + means one or more arguments, * means zero or more arguments, and ? means zero or one argument.

Replenishment

I used the short parameters in the add_argument() function for a simple explanation.

But, you can use any combination of the parameters.

Try it and make your application.

댓글