🗂️ INDEX

글 작성자: Universe7202

참고 : 링크

<< What is argparse >>


python을 실행할때 파일 이름 말고도 여러 옵션들을 적거나 값들을 추가적으로 적어주는 것을 본적이 있을 것이다.

python에는 여러가지 모듈을 지원해주는데 sys 모듈을 쓰면 가능하다.
하지만 sys 모듈을 사용하면 사용자로 부터 어떤 옵션, 값을 받을지 모르기 때문에, 많은 예외가 발생한다.

sys 말고 argparse 라는 모듈을 사용하면 쉽게 해결이 된다.

 

<< argparse example >>


아래 내용부터는 코드와 코드 설명을 위주로 argparse 모듈에 대해 설명 해보겠다.

 

== Example_1 ==

ArgumentParser 라는 함수를 이용해 parser 를 생성.
add_argument 함수를 이용해 변수와 type, help 를 정의해준다.
parse_args() 함수를 통해 사용자로 부터 입력받은 값들이 저장된 변수를 args 에 저장한다.

import argparse

def main():
	parser = argparse.ArgumentParser();
	parser.add_argument("X", type=int, help="What is the first number?")
	parser.add_argument("Y", type=int, help="What is the second number?")

	args = parser.parse_args()
	X = args.X
	Y = args.Y
	print("%d + %d = %d" % (X,Y,X+Y))

main()

result

C:\Users\whdal\Desktop\Casper\code\python>argparser_example.py -h
usage: argparser_example.py [-h] X Y


positional arguments:
X What is the first number?
Y What is the second number?


optional arguments:
-h, --help show this help message and exit


C:\Users\whdal\Desktop\Casper\code\python>argparser_example.py 1 2
1 + 2 = 3

 

 

 

== Example_2 ==

description을 통해 코드에 대한 소개를 작성 할 수 있다.
add_argument에서 help가 인자(변수 이름)에 대한 설명을 적는 곳이었다면, metavar는 인자의 이름을 명시하는데 사용된다.
default는 인자가 주어지지 않을때의 기본값을 지정하는데에 사용된다.
choices는 가능한 인자 목록을 제한하는데 사용된다.
연산에 대한 add_argument에서는 dest 옵션을 사용하지 않았다. 변수명이 지정되지 않았다면, ‘–op’에서 ‘–‘만 뗀 뒷부분을 변수명으로 사용한다.

import argparse

def main():
	parser = argparse.ArgumentParser(description = 'This code is written for practice about argparser ')
	parser.add_argument('x', type=float, metavar='First_number', help='What is the first number?')
	parser.add_argument('y', type=float, metavar='Second_number', help='what is the second number?')
	parser.add_argument('--op', type=str, default='add', choices=['add','sub','mul','div'], help='What operation?')
	args = parser.parse_args()

	x = args.x
	y = args.y
	op = args.op
	print(calc(x,y,op))

def calc(x,y,op):
	if op == 'add':
		return x+y
	elif op == 'sub':
		return x-y
	elif op == 'mul':
		return x*y
	elif op == 'div':
		return x/y

main()

result

C:\Users\whdal\Desktop\Casper\code\python>argparser_example.py -h
usage: argparser_example.py [-h] [--op {add,sub,mul,div}]
First_number Second_number


This code is written for practice about argparser


positional arguments:
First_number What is the first number?
Second_number what is the second number?


optional arguments:
-h, --help show this help message and exit
--op {add,sub,mul,div}
What operation?


C:\Users\whdal\Desktop\Casper\code\python>argparser_example.py 1 2 --op sub
-1.0

 

 

 

 

== Example_3 ==


마지막 예제이다. 만약 사용자가 몇개의 값을 입력하는지 모르는 상황에서 코딩을 하면 에러가 뜰 수 가 있다.
이렇듯 여러 개의 인자를 입력받을 경우 nargs 라는 옵션을 추가하면 여러 개의 인자를 하나의 리스트 변수에 저장된다.

import argparse

def main():
	parser = argparse.ArgumentParser(description='Enter any numbers to sum')
	parser.add_argument('x',type=float,nargs='+')
	args = parser.parse_args()
	x = args.x

	sum = 0.0

	for input in x:
		sum += input
	print("Total : ",sum)
main()

result

C:\Users\whdal\Desktop\Casper\code\python>argparser_example.py -h
usage: argparser_example.py [-h] x [x ...]


Enter any numbers to sum


positional arguments:
x


optional arguments:
-h, --help show this help message and exit


C:\Users\whdal\Desktop\Casper\code\python>argparser_example.py 1 2 3 4 5
Total : 15.0