Python's Command Line Parsing Module argparse
Description
argparse
is one of the Python standard libraries that helps in handling arguments passed from the command-line. While it is possible to receive input arguments using sys.argv
, using argparse
allows for advanced features such as specifying the type and whether an argument is mandatory.
Code
argparse.ArgumentParser
: Creates an object.add_argument()
: Method to register an argument to be accepted.parse_args()
: Method to parse the received arguments.
# 테스트 파일 작성
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-e", "--epoch", type=int)
parser.add_argument("-s", "--seed", type=int)
parser.add_argument("-a", "--activ_fn", type=str)
args = parser.parse_args()
print(type(args))
print("args:", args)
print("epoch:", args.epoch)
print("seed:", args.seed)
print("activ_fn:", args.activ_fn)
The type of args
here is <class 'argparse.Namespace'>
, and you can see that it looks like a dictionary when printed. It has each argument’s name as an attribute. There are two ways to enter this in the console window.
python test.py -epo 10 -s 2 -a relu
python test.py -epo=10 -s=2 -a=relu
# 콘솔창에서 실행
>python test.py -epo 10 -s 2 -a relu
<class 'argparse.Namespace'>
args: Namespace(epoch=10, seed=2, activ_fn='relu')
epoch: 10
seed: 2
activ_fn: relu
Variable Name --foo
The name of an argument is entered in the form of "-f"
or "--foo"
. Conventionally, a single dash -
is used for abbreviations, and two dashes --
are used for the full name, but the code will run even if you write -foo
.
Type type
The type
option allows specifying the type. Setting it to int
means that when the input argument is 1, it’s passed not as the string ‘1’, but as the number 1.
Number of Arguments nargs
The nargs
option allows determining how many arguments to receive. Thus, by using this option, a list can be passed as an argument.
# test.py 코드
parser.add_argument("--dx", type=float, nargs=3)
parser.add_argument("--dy", type=float, nargs=2)
args = parser.parse_args()
print("dx:", args.dx, ", type of dx:", type(args.dx))
print("dy:", args.dy, ", type of dy:", type(args.dy))
# 콘솔창에서 실행
>python test.py --dx 0.1 0.01 0.001 --dy 0.2 0.02
dx: [0.1, 0.01, 0.001] , type of dx: <class 'list'>
dy: [0.2, 0.02] , type of dy: <class 'list'>
Using +
or *
means you don’t have to specify the number of arguments, and one or more arguments are stored in a list. The difference between the two is that +
requires at least one argument to be entered, while *
does not require any arguments to be entered.
Default Value default
The default
option allows setting a default value.
parser.add_argument("-e", "--epoch", type=int, defalut=100000)
Others
There are also options like action
, required
, help
, metavar
, etc.1
Environment
- OS: Windows11
- Version: Python 3.9.13