0000

argparse

11 Jul 2021 • viridi | History | Comment

Learning second part of argparse to taste the DRY (don’t repeat yourself) principle [1] and simplify the example.

codes

File is arg_parse.py

"""
	arg_parse.py
"""

import argparse

def parse_arguments():
	parser = argparse.ArgumentParser(description='Argument get parse via --commands')
	parser.add_argument("-x", metavar='value', required=True, help='first value to parse')
	parser.add_argument("-y", metavar='value', required=True, help='second value to parse')
	
	args = parser.parse_args()
	
	return args

def main():
	print('first value is ', args.x, sep='')
	print('second value is ', args.y, sep='')
	
if __name__ == '__main__':
	args = parse_arguments()
	main()

results

Previous file can be executed as follows with the results

L:\home\butir\code\0\07\1>py arg_parse.py -h
usage: arg_parse.py [-h] -x value -y value

Argument get parse via --commands

optional arguments:
  -h, --help  show this help message and exit
  -x value    first value to parse
  -y value    second value to parse

to see the help,

L:\home\butir\code\0\07\1>py arg_parse.py
usage: arg_parse.py [-h] -x value -y value
arg_parse.py: error: the following arguments are required: -x, -y

L:\home\butir\code\0\07\1>py arg_parse.py -y
usage: arg_parse.py [-h] -x value -y value
arg_parse.py: error: argument -y: expected one argument

L:\home\butir\code\0\07\1>py arg_parse.py -y 2.5
usage: arg_parse.py [-h] -x value -y value
arg_parse.py: error: the following arguments are required: -x

L:\home\butir\code\0\07\1>py arg_parse.py -y 2.5 -x
usage: arg_parse.py [-h] -x value -y value
arg_parse.py: error: argument -x: expected one argument

to test whether all two arguments are provided, and

L:\home\butir\code\0\07\1>py arg_parse.py -y 2.5 -x -220
first value is -220
second value is 2.5

to get the intended result. See documentation [2] for further information.

notes

  1. Louis de Bruijn, “Write Better Python Scripts”, BetterProgramming, 26 May 2020, url https://betterprogramming.pub/ce58c1ebf690 [20210711].
  2. Tshepang Lekhonkhobe, “Argparse Tutorial”, Python » 3.9.6 Documentation » Python HOWTOs, Python Software Foundation, 10 Jul 2021, url https://docs.python.org/3/howto/argparse.html [20210711].

 

introductionrefsifmain