Python argparse.Action() Examples

The following are 30 code examples for showing how to use argparse.Action(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module argparse , or try the search function .

Example 1
Project: tox   Author: tox-dev   File: __init__.py    License: MIT License 6 votes vote down vote up
def cli_skip_missing_interpreter(parser):
    class SkipMissingInterpreterAction(argparse.Action):
        def __call__(self, parser, namespace, values, option_string=None):
            value = "true" if values is None else values
            if value not in ("config", "true", "false"):
                raise argparse.ArgumentTypeError("value must be config, true or false")
            setattr(namespace, self.dest, value)

    parser.add_argument(
        "-s",
        "--skip-missing-interpreters",
        default="config",
        metavar="val",
        nargs="?",
        action=SkipMissingInterpreterAction,
        help="don't fail tests for missing interpreters: {config,true,false} choice",
    ) 
Example 2
Project: jbox   Author: jpush   File: pytestplugin.py    License: MIT License 6 votes vote down vote up
def pytest_addoption(parser):
    group = parser.getgroup("sqlalchemy")

    def make_option(name, **kw):
        callback_ = kw.pop("callback", None)
        if callback_:
            class CallableAction(argparse.Action):
                def __call__(self, parser, namespace,
                             values, option_string=None):
                    callback_(option_string, values, parser)
            kw["action"] = CallableAction

        group.addoption(name, **kw)

    plugin_base.setup_options(make_option)
    plugin_base.read_config() 
Example 3
Project: jbox   Author: jpush   File: pytestplugin.py    License: MIT License 6 votes vote down vote up
def pytest_addoption(parser):
    group = parser.getgroup("sqlalchemy")

    def make_option(name, **kw):
        callback_ = kw.pop("callback", None)
        if callback_:
            class CallableAction(argparse.Action):
                def __call__(self, parser, namespace,
                             values, option_string=None):
                    callback_(option_string, values, parser)
            kw["action"] = CallableAction

        group.addoption(name, **kw)

    plugin_base.setup_options(make_option)
    plugin_base.read_config() 
Example 4
Project: ironpython2   Author: IronLanguages   File: test_argparse.py    License: Apache License 2.0 6 votes vote down vote up
def test(self):

        def get_my_type(string):
            return 'my_type{%s}' % string

        parser = argparse.ArgumentParser()
        parser.register('type', 'my_type', get_my_type)
        parser.add_argument('-x', type='my_type')
        parser.add_argument('y', type='my_type')

        self.assertEqual(parser.parse_args('1'.split()),
                         NS(x=None, y='my_type{1}'))
        self.assertEqual(parser.parse_args('-x 1 42'.split()),
                         NS(x='my_type{1}', y='my_type{42}'))


# ============
# Action tests
# ============ 
Example 5
Project: BinderFilter   Author: dxwu   File: test_argparse.py    License: MIT License 6 votes vote down vote up
def test(self):

        def get_my_type(string):
            return 'my_type{%s}' % string

        parser = argparse.ArgumentParser()
        parser.register('type', 'my_type', get_my_type)
        parser.add_argument('-x', type='my_type')
        parser.add_argument('y', type='my_type')

        self.assertEqual(parser.parse_args('1'.split()),
                         NS(x=None, y='my_type{1}'))
        self.assertEqual(parser.parse_args('-x 1 42'.split()),
                         NS(x='my_type{1}', y='my_type{42}'))


# ============
# Action tests
# ============ 
Example 6
Project: oss-ftp   Author: aliyun   File: test_argparse.py    License: MIT License 6 votes vote down vote up
def test(self):

        def get_my_type(string):
            return 'my_type{%s}' % string

        parser = argparse.ArgumentParser()
        parser.register('type', 'my_type', get_my_type)
        parser.add_argument('-x', type='my_type')
        parser.add_argument('y', type='my_type')

        self.assertEqual(parser.parse_args('1'.split()),
                         NS(x=None, y='my_type{1}'))
        self.assertEqual(parser.parse_args('-x 1 42'.split()),
                         NS(x='my_type{1}', y='my_type{42}'))


# ============
# Action tests
# ============ 
Example 7
Project: pydatalab   Author: googledatalab   File: task.py    License: Apache License 2.0 6 votes vote down vote up
def make_datalab_help_action(self):
    """Custom action for --datalab-help.

    The action output the package specific parameters and will be part of "%%ml train"
    help string.
    """
    datalab_help = self.datalab_help
    epilog = self.datalab_epilog

    class _CustomAction(argparse.Action):

      def __init__(self, option_strings, dest, help=None):
        super(_CustomAction, self).__init__(
            option_strings=option_strings, dest=dest, nargs=0, help=help)

      def __call__(self, parser, args, values, option_string=None):
        print('\n\n'.join(datalab_help))
        if epilog:
          print(epilog)

        # We have printed all help string datalab needs. If we don't quit, it will complain about
        # missing required arguments later.
        quit()
    return _CustomAction 
Example 8
Project: pydatalab   Author: googledatalab   File: task.py    License: Apache License 2.0 6 votes vote down vote up
def make_datalab_help_action(self):
    """Custom action for --datalab-help.

    The action output the package specific parameters and will be part of "%%ml train"
    help string.
    """
    datalab_help = self.datalab_help
    epilog = self.datalab_epilog

    class _CustomAction(argparse.Action):

      def __init__(self, option_strings, dest, help=None):
        super(_CustomAction, self).__init__(
            option_strings=option_strings, dest=dest, nargs=0, help=help)

      def __call__(self, parser, args, values, option_string=None):
        print('\n\n'.join(datalab_help))
        if epilog:
          print(epilog)

        # We have printed all help string datalab needs. If we don't quit, it will complain about
        # missing required arguments later.
        quit()
    return _CustomAction 
Example 9
Project: MDT   Author: robbert-harms   File: shell_utils.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_argparse_extension_checker(choices, dir_allowed=False):
    """Get an :class:`argparge.Action` class that can check for correct extensions.

    Returns:
        argparse.Action: a class (not an instance) of an argparse action.
    """

    class Act(argparse.Action):
        def __call__(self, parser, namespace, fname, option_string=None):
            is_valid = any(map(lambda choice: fname[-len(choice):] == choice, choices))

            if not is_valid and dir_allowed and os.path.isdir(fname):
                is_valid = True

            if is_valid:
                setattr(namespace, self.dest, fname)
            else:
                option_string = '({})'.format(option_string) if option_string else ''
                parser.error("File doesn't end with one of {}{}".format(choices, option_string))

    return Act 
Example 10
Project: augur   Author: nextstrain   File: __init__.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def add_version_alias(parser):
    """
    Add --version as a (hidden) alias for the version command.

    It's not uncommon to blindly run a command with --version as the sole
    argument, so its useful to make that Just Work.
    """

    class run_version_command(argparse.Action):
        def __call__(self, *args, **kwargs):
            opts = SimpleNamespace()
            sys.exit( version.run(opts) )

    return parser.add_argument(
        "--version",
        nargs  = 0,
        help   = argparse.SUPPRESS,
        action = run_version_command) 
Example 11
Project: armi   Author: terrapower   File: entryPoint.py    License: Apache License 2.0 6 votes vote down vote up
def storeBool(boolDefault, ep):
    class _StoreBoolAction(argparse.Action):
        def __init__(self, option_strings, dest, help=None):
            super(_StoreBoolAction, self).__init__(
                option_strings=option_strings,
                dest=dest,
                nargs=0,
                const=boolDefault,
                default=False,
                required=False,
                help=help,
            )

        def __call__(self, parser, namespace, values, option_string=None):
            ep.cs[self.dest] = self.const
            ep.settingsProvidedOnCommandLine.append(self.dest)
            ep.cs.failOnLoad()

    return _StoreBoolAction 
Example 12
Project: armi   Author: terrapower   File: entryPoint.py    License: Apache License 2.0 6 votes vote down vote up
def setSetting(ep):
    class _SetSettingAction(argparse.Action):
        """This class loads the command line supplied setting values into the
        :py:data:`armi.settings.cs`
        """

        def __call__(self, parser, namespace, values, option_string=None):
            ep.cs[self.dest] = values  # correctly converts type
            ep.settingsProvidedOnCommandLine.append(self.dest)
            ep.cs.failOnLoad()

    return _SetSettingAction


# Q: Why does this require special treatment? Why not treat it like the other
#    case settings and use setSetting action?
# A: Because caseTitle is no longer an actual cs setting. It's a instance attr. 
Example 13
Project: Fluid-Designer   Author: Microvellum   File: pytestplugin.py    License: GNU General Public License v3.0 6 votes vote down vote up
def pytest_addoption(parser):
    group = parser.getgroup("sqlalchemy")

    def make_option(name, **kw):
        callback_ = kw.pop("callback", None)
        if callback_:
            class CallableAction(argparse.Action):
                def __call__(self, parser, namespace,
                             values, option_string=None):
                    callback_(option_string, values, parser)
            kw["action"] = CallableAction

        group.addoption(name, **kw)

    plugin_base.setup_options(make_option)
    plugin_base.read_config() 
Example 14
Project: Fluid-Designer   Author: Microvellum   File: test_argparse.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test(self):

        def get_my_type(string):
            return 'my_type{%s}' % string

        parser = argparse.ArgumentParser()
        parser.register('type', 'my_type', get_my_type)
        parser.add_argument('-x', type='my_type')
        parser.add_argument('y', type='my_type')

        self.assertEqual(parser.parse_args('1'.split()),
                         NS(x=None, y='my_type{1}'))
        self.assertEqual(parser.parse_args('-x 1 42'.split()),
                         NS(x='my_type{1}', y='my_type{42}'))


# ============
# Action tests
# ============ 
Example 15
Project: ironpython3   Author: IronLanguages   File: test_argparse.py    License: Apache License 2.0 6 votes vote down vote up
def test(self):

        def get_my_type(string):
            return 'my_type{%s}' % string

        parser = argparse.ArgumentParser()
        parser.register('type', 'my_type', get_my_type)
        parser.add_argument('-x', type='my_type')
        parser.add_argument('y', type='my_type')

        self.assertEqual(parser.parse_args('1'.split()),
                         NS(x=None, y='my_type{1}'))
        self.assertEqual(parser.parse_args('-x 1 42'.split()),
                         NS(x='my_type{1}', y='my_type{42}'))


# ============
# Action tests
# ============ 
Example 16
Project: python_cross_compile_script   Author: DeadSix27   File: cross_compiler.py    License: Mozilla Public License 2.0 6 votes vote down vote up
def assembleConfigHelps(self, pdlist, type, main):
		class customArgsAction(argparse.Action):
			def __call__(self, parser, args, values, option_string=None):
				main.quietMode = True
				main.init_quietMode()
				main.prepareBuilding(64)
				main.build_mingw(64)
				main.initBuildFolders()
				for k, v in pdlist.items():
					if '_disabled' not in v:
						if '_info' in v:
							beforePath = os.getcwd()
							path = main.getPackagePath(k, v, type)
							main.cchdir(path)
							if os.path.isfile(os.path.join(path, "configure")):
								os.system("./configure --help")
							if os.path.isfile(os.path.join(path, "waf")):
								os.system("./waf --help")
							main.cchdir(beforePath)
							print("-------------------")
				setattr(args, self.dest, values)
				parser.exit()
		return customArgsAction 
Example 17
Project: aws-encryption-sdk-cli   Author: aws   File: arg_parsing.py    License: Apache License 2.0 6 votes vote down vote up
def __call__(
        self,
        parser,  # type: argparse.ArgumentParser
        namespace,  # type: argparse.Namespace
        values,  # type: Union[ARGPARSE_TEXT, Sequence[Any], None]
        option_string=None,  # type: Optional[ARGPARSE_TEXT]
    ):
        # type: (...) -> None
        """Checks to make sure that the destination is empty before writing.

        :raises parser.error: if destination is already set
        """
        if getattr(namespace, self.dest) is not None:  # type: ignore # typeshed doesn't know about Action.dest yet?
            parser.error("{} argument may not be specified more than once".format(option_string))
            return
        setattr(namespace, self.dest, values)  # type: ignore # typeshed doesn't know about Action.dest yet? 
Example 18
def choices_with_default(choices, default):
    """This closure defines an argparser custom action that ensures an argument
       value is in a list of choices, and if not, sets the argument to a default
       value.

       Implementing this argparser action instead of using only a 'choices' list
       for the argument works better for a script called from Jamf where an
       optional parameter may be omitted from the policy definition, but
       subsequent parameters are passed, ie. script.py 1 2 3 [omitted] 5 6
    """
    class customAction(argparse.Action):
        def __call__(self, parser, args, values, option_string=None):
            if (values in choices) or (values == default):
                setattr(args, self.dest, values)
            else:
                setattr(args, self.dest, default)

    return customAction 
Example 19
Project: pyRevit   Author: eirannejad   File: pytestplugin.py    License: GNU General Public License v3.0 6 votes vote down vote up
def pytest_addoption(parser):
    group = parser.getgroup("sqlalchemy")

    def make_option(name, **kw):
        callback_ = kw.pop("callback", None)
        if callback_:
            class CallableAction(argparse.Action):
                def __call__(self, parser, namespace,
                             values, option_string=None):
                    callback_(option_string, values, parser)
            kw["action"] = CallableAction

        group.addoption(name, **kw)

    plugin_base.setup_options(make_option)
    plugin_base.read_config() 
Example 20
Project: abkhazia   Author: bootphon   File: abkhazia_main.py    License: GNU General Public License v3.0 6 votes vote down vote up
def load_config(self):
        """Load the config file optionally given by --config argument

        Return the string read from sys.argv, with '--config
        <config-file>' removed

        """
        parser = argparse.ArgumentParser(add_help=False)

        class _ConfigAction(argparse.Action):
            def __call__(self, parser, namespace, value, option_string=None):
                if not os.path.isfile(value):
                    raise IOError(
                        'configuration file not found {}'.format(value))

                print('loading configuration from {}'.format(value))
                utils.config.read(value)

        # add a configuration argument
        parser.add_argument(
            '-c', '--config', metavar='<config-file>', action=_ConfigAction)

        return parser.parse_known_args()[1] 
Example 21
Project: ros_buildfarm   Author: ros-infrastructure   File: argument.py    License: Apache License 2.0 6 votes vote down vote up
def add_argument_os_code_name_and_arch_tuples(parser, required=True):
    class _AddUbuntuTupleAction(argparse.Action):

        def __call__(self, parser, args, values, option_string=None):
            import sys
            print('WARNING: ' + self.help, file=sys.stderr)
            for value in values:
                if value.count(':') != 1:
                    raise argparse.ArgumentError(
                        argument=self,
                        message='expected 2 parts separated by colons')
            setattr(
                args, 'os_name_and_os_code_name_and_arch_tuples',
                [('ubuntu:' + value).split(':') for value in values])
            setattr(args, self.dest, values)

    parser.add_argument(
        '--os-code-name-and-arch-tuples',
        nargs='+',
        required=required, action=_AddUbuntuTupleAction,
        help="DEPRECATED: Use '--os-name-and-os-code-name-and-arch-tuples'") 
Example 22
Project: gcblue   Author: gcblue   File: test_argparse.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test(self):

        def get_my_type(string):
            return 'my_type{%s}' % string

        parser = argparse.ArgumentParser()
        parser.register('type', 'my_type', get_my_type)
        parser.add_argument('-x', type='my_type')
        parser.add_argument('y', type='my_type')

        self.assertEqual(parser.parse_args('1'.split()),
                         NS(x=None, y='my_type{1}'))
        self.assertEqual(parser.parse_args('-x 1 42'.split()),
                         NS(x='my_type{1}', y='my_type{42}'))


# ============
# Action tests
# ============ 
Example 23
Project: mutatest   Author: EvanKepner   File: cli.py    License: MIT License 5 votes vote down vote up
def get_constrained_float_action(
    min_val: Optional[float] = None, max_val: Optional[float] = None
) -> Type[argparse.Action]:
    class ConstrainedFloatAction(argparse.Action):
        """Custom action for ensuring floats arguments meet these."""

        def __call__(self, parser, namespace, values, option_string=None):  # type: ignore
            if min_val is not None and values < min_val:
                parser.error("{0} must be no smaller than {1}.".format(option_string, min_val))
            if max_val is not None and values > max_val:
                parser.error("{0} must be no greater than {1}.".format(option_string, max_val))

            setattr(namespace, self.dest, values)

    return ConstrainedFloatAction 
Example 24
Project: knack   Author: microsoft   File: arguments.py    License: MIT License 5 votes vote down vote up
def _get_parent_class(self, **kwargs):
        # wrap any existing action
        action = kwargs.get('action', None)
        parent_class = argparse.Action

        # action is either a user-defined Action class or a string referring a library-defined Action
        if isinstance(action, type) and issubclass(action, argparse.Action):
            parent_class = action
        elif isinstance(action, str):
            parent_class = self.command_loader.cli_ctx.invocation.parser._registries['action'][action]  # pylint: disable=protected-access
        return parent_class 
Example 25
Project: knack   Author: microsoft   File: test_experimental.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        from knack.help_files import helps

        class LoggerAction(argparse.Action):

            def __call__(self, parser, namespace, values, option_string=None):
                print("Side-effect from some original action!", file=sys.stderr)

        class ExperimentalTestCommandLoader(CLICommandsLoader):
            def load_command_table(self, args):
                super(ExperimentalTestCommandLoader, self).load_command_table(args)
                with CommandGroup(self, '', '{}#{{}}'.format(__name__)) as g:
                    g.command('arg-test', 'example_arg_handler')
                return self.command_table

            def load_arguments(self, command):
                with ArgumentsContext(self, 'arg-test') as c:
                    c.argument('arg1', help='Arg1', is_experimental=True, action=LoggerAction)

                super(ExperimentalTestCommandLoader, self).load_arguments(command)

        helps['grp1'] = """
    type: group
    short-summary: A group.
"""
        self.cli_ctx = DummyCLI(commands_loader_cls=ExperimentalTestCommandLoader) 
Example 26
Project: knack   Author: microsoft   File: test_preview.py    License: MIT License 5 votes vote down vote up
def setUp(self):
        from knack.help_files import helps

        class LoggerAction(argparse.Action):

            def __call__(self, parser, namespace, values, option_string=None):
                print("Side-effect from some original action!", file=sys.stderr)

        class PreviewTestCommandLoader(CLICommandsLoader):
            def load_command_table(self, args):
                super(PreviewTestCommandLoader, self).load_command_table(args)
                with CommandGroup(self, '', '{}#{{}}'.format(__name__)) as g:
                    g.command('arg-test', 'example_arg_handler')
                return self.command_table

            def load_arguments(self, command):
                with ArgumentsContext(self, 'arg-test') as c:
                    c.argument('arg1', help='Arg1', is_preview=True, action=LoggerAction)

                super(PreviewTestCommandLoader, self).load_arguments(command)

        helps['grp1'] = """
    type: group
    short-summary: A group.
"""
        self.cli_ctx = DummyCLI(commands_loader_cls=PreviewTestCommandLoader) 
Example 27
Project: dialogbot   Author: shibing624   File: io.py    License: Apache License 2.0 5 votes vote down vote up
def check(validator):
    class CustomAction(argparse.Action):
        def __call__(self, parser, namespace, values, option_string=None):
            validator(values)
            setattr(namespace, self.dest, values)

    return CustomAction 
Example 28
Project: dialogbot   Author: shibing624   File: io.py    License: Apache License 2.0 5 votes vote down vote up
def check_size(min_size=None, max_size=None):
    class CustomAction(argparse.Action):
        def __call__(self, parser, namespace, values, option_string=None):
            validate((values, self.type, min_size, max_size, self.dest))
            setattr(namespace, self.dest, values)

    return CustomAction 
Example 29
Project: mars   Author: mars-project   File: base_app.py    License: Apache License 2.0 5 votes vote down vote up
def arg_deprecated_action(new_arg):  # pragma: no cover
    class ArgDeprecated(argparse.Action):
        def __call__(self, parser, namespace, values, option_string=None):
            logger.warning('Argument %s deprecated. Use %s instead',
                           '|'.join(self.option_strings), new_arg)
            setattr(namespace, self.dest, values)
    return ArgDeprecated 
Example 30
Project: torf   Author: rndusr   File: conftest.py    License: GNU General Public License v3.0 5 votes vote down vote up
def pytest_addoption(parser):
    class IntList(argparse.Action):
        def __call__(self, parser, namespace, values, option_string=None):
            setattr(namespace, self.dest, tuple(int(value) for value in values.split(',')))
    parser.addoption('--piece-sizes', default=(8,), action=IntList,
                     help='Comma-separated list of piece sizes to use for test torrents')
    parser.addoption('--piece-counts', default=(1, 2, 3, 4, 6, 9), action=IntList,
                     help='Comma-separated list of number of pieces to use for test torrents')
    parser.addoption('--file-counts', default=(1, 2, 3, 4), action=IntList,
                     help='Comma-separated list of number of files to use for test torrents')
    parser.addoption('--fuzzy', action='store_true',
                     help='Whether to randomize file sizes for --file-counts >= 4')