About argparse Module in Python

0. Introduction

ArgumentParser is a class provided by the argparse module in Python.
It is used to parse command-line arguments and options, making it easier to create robust and user-friendly command-line interfaces for Python programs.

Official Document: https://docs.python.org/3/howto/argparse.html

1. Code

Demo hello.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
from argparse import ArgumentParser


def get_args():
parser = ArgumentParser()
parser.add_argument('--your_name', default='Hardy Hu', type=str)
parser.add_argument('-n', '--n', default=3, type=int, help='number of times')
parser.add_argument('--input_integers', type=int, nargs='+')
return parser.parse_args()


if __name__ == '__main__':
args = get_args()

for _ in range(args.n):
print("Hello, {}".format(args.your_name))

if args.input_integers is not None:
print("sums: {}".format(sum(args.input_integers)))

2. Run

Example Help:

1
python hello.py -h
1
2
3
4
5
6
7
usage: hello.py [-h] [--your_name YOUR_NAME] [-n N] [--input_integers INPUT_INTEGERS [INPUT_INTEGERS ...]]

optional arguments:
-h, --help show this help message and exit
--your_name YOUR_NAME
-n N, --n N number of times
--input_integers INPUT_INTEGERS [INPUT_INTEGERS ...]

Example Default:

1
python hello.py
1
2
3
Hello, Hardy Hu
Hello, Hardy Hu
Hello, Hardy Hu

Example Input args:

1
python hello.py --your_name "Jack Rose" --n 10 --input_integers 1 2 3
1
2
3
4
5
6
7
8
9
10
11
Hello, Jack Rose
Hello, Jack Rose
Hello, Jack Rose
Hello, Jack Rose
Hello, Jack Rose
Hello, Jack Rose
Hello, Jack Rose
Hello, Jack Rose
Hello, Jack Rose
Hello, Jack Rose
sums: 6

About argparse Module in Python
https://www.hardyhu.cn/2023/07/10/About-argparse-Module-in-Python/
Author
John Doe
Posted on
July 10, 2023
Licensed under