Python argparse.Action() Examples

The following are 30 code examples of argparse.Action(). 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 also want to check out all available functions/classes of the module argparse , or try the search function .
Example #1
Source File: pytestplugin.py    From Fluid-Designer with GNU General Public License v3.0 7 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 #2
Source File: __init__.py    From augur with 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 #3
Source File: task.py    From pydatalab with 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 #4
Source File: cross_compiler.py    From python_cross_compile_script with 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 #5
Source File: arg_parsing.py    From aws-encryption-sdk-cli with 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 #6
Source File: better-jamf-policy-deferral.py    From better-jamf-policy-deferral with GNU General Public License v3.0 6 votes vote down vote up
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 #7
Source File: pytestplugin.py    From pyRevit with 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 #8
Source File: task.py    From pydatalab with 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
Source File: shell_utils.py    From MDT with 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
Source File: abkhazia_main.py    From abkhazia with 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 #11
Source File: entryPoint.py    From armi with 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 #12
Source File: pytestplugin.py    From jbox with 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 #13
Source File: pytestplugin.py    From jbox with 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 #14
Source File: entryPoint.py    From armi with 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 #15
Source File: argument.py    From ros_buildfarm with 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 #16
Source File: test_argparse.py    From gcblue with 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 #17
Source File: __init__.py    From tox with 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 #18
Source File: pytestplugin.py    From planespotter with MIT License 5 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

        zeroarg_callback = kw.pop("zeroarg_callback", None)
        if zeroarg_callback:
            class CallableAction(argparse.Action):
                def __init__(self, option_strings,
                             dest, default=False,
                             required=False, help=None):
                        super(CallableAction, self).__init__(
                            option_strings=option_strings,
                            dest=dest,
                            nargs=0,
                            const=True,
                            default=default,
                            required=required,
                            help=help)

                def __call__(self, parser, namespace,
                             values, option_string=None):
                    zeroarg_callback(option_string, values, parser)
            kw["action"] = CallableAction

        group.addoption(name, **kw)

    plugin_base.setup_options(make_option)
    plugin_base.read_config() 
Example #19
Source File: argument.py    From ros_buildfarm with Apache License 2.0 5 votes vote down vote up
def check_len_action(minargs, maxargs):
    class CheckLength(argparse.Action):

        def __call__(self, parser, args, values, option_string=None):
            if len(values) < minargs:
                raise argparse.ArgumentError(
                    argument=self,
                    message='expected at least %s arguments' % (minargs))
            elif len(values) > maxargs:
                raise argparse.ArgumentError(
                    argument=self,
                    message='expected at most %s arguments' % (minargs))
            setattr(args, self.dest, values)
    return CheckLength 
Example #20
Source File: abkhazia_features.py    From abkhazia with GNU General Public License v3.0 5 votes vote down vote up
def add_kaldi_options(cls, parser):
        """Add the optional parameters from the kaldi feature extractor"""

        def action(name):
            """Append the parsed value to cls.parsed_options"""
            class customAction(argparse.Action):
                def __call__(self, parser, args, value, option_string=None):
                    cls.parsed_options.append((name, value))
            return customAction

        kaldi.add_options_executable(
            parser, cls.kaldi_bin,
            action=action,
            ignore=cls.ignored_options,
            overload=cls.overloaded_options) 
Example #21
Source File: userconfigaction.py    From python-otcclient with MIT License 5 votes vote down vote up
def __init__(self,
                 option_strings,
                 dest,
                 nargs=None,
                 const=None,
                 default=None,
                 type=None,  # @ReservedAssignment
                 choices=None,
                 required=False,
                 help=None,  # @ReservedAssignment
                 metavar=None):
        argparse.Action.__init__(self,
                                 option_strings=option_strings,
                                 dest=dest,
                                 nargs=nargs,
                                 const=const,
                                 default=default,
                                 type=type,
                                 choices=choices,
                                 required=required,
                                 help=help,
                                 metavar=metavar,
                                 )
        for name, value in sorted(locals().items()):
            if name == 'self' or value is None:
                continue
#            print('  %s = %r' % (name, value))
        return 
Example #22
Source File: base.py    From dffml with MIT License 5 votes vote down vote up
def list_action(list_cls):
    """
    Action to take a list of values and make them values in the list of type
    list_class. Which will be a class descendent from AsyncContextManagerList.
    """
    LIST_ACTIONS.setdefault(
        list_cls,
        type(
            f"Parse{list_cls.__qualname__}Action",
            (ParseExpandAction,),
            {"LIST_CLS": list_cls},
        ),
    )
    return LIST_ACTIONS[list_cls] 
Example #23
Source File: test_argparse.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_argument(self):
        argument = argparse.Action(
            option_strings=[],
            dest='x',
            type=float,
            nargs='?',
            default=2.5,
            choices=[0.5, 1.5, 2.5],
            help='H HH H',
            metavar='MV MV MV')
        string = (
            "Action(option_strings=[], dest='x', nargs='?', "
            "const=None, default=2.5, type=%r, choices=[0.5, 1.5, 2.5], "
            "help='H HH H', metavar='MV MV MV')" % float)
        self.assertStringEqual(argument, string) 
Example #24
Source File: test_argparse.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_optional(self):
        option = argparse.Action(
            option_strings=['--foo', '-a', '-b'],
            dest='b',
            type='int',
            nargs='+',
            default=42,
            choices=[1, 2, 3],
            help='HELP',
            metavar='METAVAR')
        string = (
            "Action(option_strings=['--foo', '-a', '-b'], dest='b', "
            "nargs='+', const=None, default=42, type='int', "
            "choices=[1, 2, 3], help='HELP', metavar='METAVAR')")
        self.assertStringEqual(option, string) 
Example #25
Source File: test_argparse.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_user_defined_action(self):

        class Success(Exception):
            pass

        class Action(object):

            def __init__(self,
                         option_strings,
                         dest,
                         const,
                         default,
                         required=False):
                if dest == 'spam':
                    if const is Success:
                        if default is Success:
                            raise Success()

            def __call__(self, *args, **kwargs):
                pass

        parser = argparse.ArgumentParser()
        self.assertRaises(Success, parser.add_argument, '--spam',
                          action=Action, default=Success, const=Success)
        self.assertRaises(Success, parser.add_argument, 'spam',
                          action=Action, default=Success, const=Success)

# ================================
# Actions returned by add_argument
# ================================ 
Example #26
Source File: test_argparse.py    From Fluid-Designer with GNU General Public License v3.0 5 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 #27
Source File: test_argparse.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_optional(self):
        option = argparse.Action(
            option_strings=['--foo', '-a', '-b'],
            dest='b',
            type='int',
            nargs='+',
            default=42,
            choices=[1, 2, 3],
            help='HELP',
            metavar='METAVAR')
        string = (
            "Action(option_strings=['--foo', '-a', '-b'], dest='b', "
            "nargs='+', const=None, default=42, type='int', "
            "choices=[1, 2, 3], help='HELP', metavar='METAVAR')")
        self.assertStringEqual(option, string) 
Example #28
Source File: entryPoint.py    From armi with Apache License 2.0 5 votes vote down vote up
def loadSettings(cs):
    class LoadSettingsAction(argparse.Action):
        """This class loads the command line supplied settings file into the
        :py:data:`armi.settings.cs`
        """

        def __call__(self, parser, namespace, values, option_string=None):
            # since this is a positional argument, it can be called with values is
            # None (i.e. default)
            if values is not None:
                cs.loadFromInputFile(values)

    return LoadSettingsAction 
Example #29
Source File: entryPoint.py    From armi with Apache License 2.0 5 votes vote down vote up
def setCaseTitle(cs):
    class _SetCaseTitleAction(argparse.Action):
        """This class sets the case title to the supplied value of the
        :py:data:`armi.settings.cs`
        """

        def __call__(self, parser, namespace, value, option_string=None):
            cs.caseTitle = value

    return _SetCaseTitleAction


# Careful, this is used by physicalProgramming 
Example #30
Source File: manage.py    From evesrp with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def shell_context():
    ctx = dict(
        app=flask.current_app,
        db=db)
    for cls in ('Request', 'Action', 'ActionType', 'Modifier',
                'AbsoluteModifier', 'RelativeModifier'):
        ctx[cls] = getattr(models, cls)
    for cls in ('Entity', 'User', 'Group', 'Note', 'APIKey', 'Permission',
            'Division', 'Pilot'):
        ctx[cls] = getattr(auth.models, cls)
    ctx['PermissionType'] = auth.PermissionType
    return ctx