Try using Python argparse's action API

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.

Example

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

Try using Python argparse's action API
Try using Pleasant's API (python / FastAPI)
Try using the Wunderlist API in Python
Try using the Kraken API in Python
Try using Tweepy [Python2.7]
Try using the BitFlyer Ligntning API in Python
Try using ChatWork API and Qiita API in Python
Try using the DropBox Core API in Python
[Python] Try using Tkinter's canvas
Try using Kubernetes Client -Python-
Try using the Twitter API
Try using the Twitter API
Try using the PeeringDB 2.0 API
Try using Janus gateway's Admin API
Data acquisition using python googlemap api
Try python
Try using LevelDB in Python (plyvel)
Try using the Python Cmd module
Run Ansible from Python using API
Try using Leap Motion in Python
Try using Amazon DynamoDB from Python
Mouse operation using Windows API in Python
Try mathematical formulas using Σ with python
Try using Dialogflow (formerly API.AI) Python SDK #dialogflow
Try using Python with Google Cloud Functions
Try using Junos On-box Python # 2 Commit Script
Get Youtube data in Python using Youtube Data API
I tried using UnityCloudBuild API from Python
Try to operate Excel using Python (Xlwings)
Try using Junos On-box Python # 1 Op Script
Try hitting the YouTube API in Python
Creating Google Spreadsheet using Python / Google Data API
Try using Tkinter
Try using docker-py
Try using cookiecutter
Try using geopandas
Try using Selenium
Try using scipy
Python> try: / except:
Try using pandas.DataFrame
Try using django-swiftbrowser
Try using matplotlib
Try using tf.metrics
Try using PyODE
Scraping using Python
Procedure to use TeamGant's WEB API (using python)
[Python] Get all comments using Youtube Data API
Python: Try using the UI on Pythonista 3 on iPad
Get image URL using Flickr API in Python
Try using the Python web framework Tornado Part 1
Let's judge emotions using Emotion API in Python
Recent ranking creation using Qiita API with Python
Manipulate objects using Blender 2.8's low-level Python API
Try using the collections module (ChainMap) of python3
Anonymous upload of images using Imgur API (using Python)
Try using tensorflow ① Build python environment and introduce tensorflow
Try using kabu station API of kabu.com Securities
Try using the Python web framework Tornado Part 2
Try accessing the YQL API directly from Python 3
Try scraping with Python.
[First API] Try to get Qiita articles with Python