A convenient argparse module for getting arguments in Python.
If you specify action in add_argument, you can assign how to store the value when there is an argument.
Perhaps the most commonly used is to specify store_true
and just use it to flag.
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("--hoge", action="store_true")
>>> args = parser.parse_args(["--hoge"])
>>> args.hoge
True
So, if you pass an object that implements the API to this action, you can make any preparations, so I tried using it.
argparse.Action
Write a class that inherits ʻargparse.Action and has a
call` method according to argparse documentation.
print_action.py
import argparse
class PrintAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
print "[{}] option add value [{}] as attr [{}]".format(
option_string, values, self.dest)
setattr(namespace, self.dest, values)
The __call__
method should receive the following four arguments.
--parser
: add_argument ArgumentParser object
--space
: namespace object returned by parse_args ()
--values
: Argument values. If the type of add_argument is specified, the type is converted first.
--ʻOption_string`: Option string when it is an option argument. It is not passed if it is a positional argument.
Try using the above PrintAction
.
>>> import argparse
>>> from print_action import PrintAction
>>>
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("--hoge", action=PrintAction)
>>> args = parser.parse_args("--hoge huga".split(' '))
[--hoge] option add value [huga] as attr [hoge]
>>> args.hoge
'huga'
Basically, after processing values
appropriately, you can add it to namespace
by using the argument name (self.dest
) as the attribute name.
__init__
should also be overridden if necessary. ʻArgparse.Action.initsays, "It must accept two positional arguments and all keyword arguments passed to ArgumentParser.add_argument () except the action itself." (Httpss (: //docs.python.jp/3/library/argparse.html#action-classes), in short, seems to be able to check in
init whether the usage of action in ʻadd_argument
is appropriate.Take an integer or <int> [KMG]
as an argument, and in the latter case convert it to an integer ʻaction`.
calc_suffix_action.py
import argparse
class CalcSuffixAction(argparse.Action):
def __init__(self, option_strings, dest, nargs=None, **kwargs):
"""
Optional.`add_argument`Here if you want to determine if the other arguments are appropriate for action
This time`__call__`Receive in method`values`I'm hoping that isn't a list
`nargs`Try to limit.
"""
if nargs is not None and nargs != '?':
raise ValueError("Invalid `nargs`: multiple arguments not allowed")
super(CalcSuffixAction, self).__init__(option_strings, dest, **kwargs)
def __call__(self, parser, namespace, values, option_string=None):
try:
if values.endswith('K'):
digit = int(values[:-1]) * 1000
elif values.endswith('M'):
digit = int(values[:-1]) * 1000000
elif values.endswith('G'):
digit = int(values[:-1]) * 1000000000
elif not isinstance(values, int):
digit = int(values)
else:
digit = values
except ValueError:
parser.error("Invalid argument ({})".format(values))
setattr(namespace, self.dest, digit)
I will try it.
>>> import argparse
>>> from calc_suffix_action import CalcSuffixAction
>>>
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument("--hoge", action=CalcSuffixAction)
>>>
>>> parser.parse_args("--hoge 1024".split(' '))
Namespace(hoge=1024)
>>> parser.parse_args("--hoge 4K".split(' '))
Namespace(hoge=4000)
>>> parser.parse_args("--hoge 32M".split(' '))
Namespace(hoge=32000000)
>>> parser.parse_args("--hoge 1G".split(' '))
Namespace(hoge=1000000000)
>>> parser.parse_args("--hoge 3T".split(' '))
usage: [-h] [--hoge HOGE]
: error: Invalid argument (3T)
Recommended Posts