Previously, I wrote an article as How to use OptParser, but apparently argparse.ArgumentParser is better.
So a note on how to use argparse.ArgumentParser
# -*- coding:utf-8 -*-
from optparse import OptionParser
from argparse import ArgumentParser
if __name__ == '__main__':
"""Character string to be displayed when a command error occurs"""
desc = u'{0} [Args] [Options]\nDetailed options -h or --help'.format(__file__)
# %prog cannot be output
# usage = u'%prog [Args] [Options]\nDetailed options -h or --help'
parser = ArgumentParser(description=desc)
# _parser = OptionParser(usage=usage, version=1.0)
#String
parser.add_argument(
'-q', '--query',
type = str, #Specify the type of value to receive
dest = 'query', #Save destination variable name
required = True, #Required item
help = 'Word to search' # --Statement to display when helping
)
# _parser.add_argument(
# '-q', '--query',
# action = 'store',
# type = 'str', #Specify the type of value to receive
# dest = 'download_date', #Save destination variable name
# help = 'Word to search' # --Statement to display when helping
# )
#Numerical value
parser.add_argument(
'-w', '--worker',
type = int,
dest = 'worker',
default = 1,
help = 'Number of multi-processes'
)
#Boolean value
parser.add_argument(
'-b', '--bool',
action = 'store_true', # store_True puts True in dest(store_There is also false)
dest = 'bool'
)
# """Set the default value for each option"""
# _parser.set_defaults(worker = 1)
"""Perspective options"""
args = parser.parse_args()
# _options, _args = _parser.parse_args()
"""The value specified in the option is args.<Variable name>Can be obtained with"""
query, worker, bool = args.query, args.worker, args.bool
# query, worker, bool = _options.query, _options.worker, _options.bool
if worker > 100
#When generating an error ↓ Like this
parser.error('Too many processes')
print args
I don't think optparse and argparse will change that much It seems that various functions have been added to argparse, as the details have changed, but basically this is enough.
http://docs.python.jp/2/library/argparse.html
Recommended Posts