Python argparse.Action() Examples

The following are code examples for showing how to use argparse.Action(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pyblish-win   Author: pyblish   File: test_argparse.py    GNU Lesser 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 2
Project: flasky   Author: RoseOu   File: pytestplugin.py    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: xia2   Author: xia2   File: conftest.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def pytest_addoption(parser):
    """
    Option '--regression-full' needs to be used to run all regression tests,
    including the full-length xia2 runs.
    """

    class RFAction(argparse.Action):
        def __call__(self, parser, namespace, values, option_string):
            namespace.regression = True
            namespace.regression_full = True

    parser.addoption(
        "--regression-full",
        nargs=0,
        action=RFAction,
        help="run all regression tests, this will take a while. Implies --regression",
    ) 
Example 4
Project: Flask_Blog   Author: sugarguo   File: pytestplugin.py    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 5
Project: Flask_Blog   Author: sugarguo   File: pytestplugin.py    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 6
Project: NiujiaoDebugger   Author: MrSrc   File: test_argparse.py    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 7
Project: tox   Author: tox-dev   File: __init__.py    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 8
Project: jbox   Author: jpush   File: pytestplugin.py    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 9
Project: jbox   Author: jpush   File: pytestplugin.py    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 10
Project: Mahjong-Solitaire   Author: MEASHY   File: pytestplugin.py    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 11
Project: Mahjong-Solitaire   Author: MEASHY   File: pytestplugin.py    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 12
Project: oa_qian   Author: sunqb   File: pytestplugin.py    Apache License 2.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 13
Project: ironpython2   Author: IronLanguages   File: test_argparse.py    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 14
Project: xuemc   Author: skycucumber   File: pytestplugin.py    GNU General Public License v2.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 15
Project: chihu   Author: yelongyu   File: pytestplugin.py    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 16
Project: chihu   Author: yelongyu   File: pytestplugin.py    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 17
Project: oss-ftp   Author: aliyun   File: test_argparse.py    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 18
Project: MDT   Author: robbert-harms   File: shell_utils.py    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 19
Project: url_shortener   Author: martydill   File: pytestplugin.py    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 20
Project: DevFest-MaxBond   Author: aiyyoi   File: pytestplugin.py    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 21
Project: mutatest   Author: EvanKepner   File: cli.py    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 22
Project: pyblish-win   Author: pyblish   File: test_argparse.py    GNU Lesser 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 23
Project: pyblish-win   Author: pyblish   File: test_argparse.py    GNU Lesser 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 24
Project: pyblish-win   Author: pyblish   File: test_argparse.py    GNU Lesser 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 25
Project: AshsSDK   Author: thehappydinoa   File: argparser.py    MIT License 5 votes vote down vote up
def choices(self, val):
        # argparse.Action will always try to set this value upon
        # instantiation, but this value should be dynamically
        # generated from the command table keys. So make this a
        # NOOP if argparse.Action tries to set this value.
        pass 
Example 26
Project: Parallel.GAMIT   Author: demiangomez   File: Utils.py    GNU General Public License v3.0 5 votes vote down vote up
def required_length(nmin,nmax):
    class RequiredLength(argparse.Action):
        def __call__(self, parser, args, values, option_string=None):
            if not nmin<=len(values)<=nmax:
                msg='argument "{f}" requires between {nmin} and {nmax} arguments'.format(
                    f=self.dest,nmin=nmin,nmax=nmax)
                raise argparse.ArgumentTypeError(msg)
            setattr(args, self.dest, values)
    return RequiredLength 
Example 27
Project: NiujiaoDebugger   Author: MrSrc   File: test_argparse.py    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 28
Project: NiujiaoDebugger   Author: MrSrc   File: test_argparse.py    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 29
Project: NiujiaoDebugger   Author: MrSrc   File: test_argparse.py    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 30
Project: knack   Author: microsoft   File: arguments.py    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 31
Project: knack   Author: microsoft   File: test_preview.py    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 32
Project: dialogbot   Author: shibing624   File: io.py    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 33
Project: dialogbot   Author: shibing624   File: io.py    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 34
Project: mars   Author: mars-project   File: base_app.py    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 35
Project: SimpleParsing   Author: lebrice   File: dataclass_wrapper.py    MIT License 5 votes vote down vote up
def __init__(self, option_strings, dest, field, **kwargs):
        self.field = field
        logger.debug(f"Creating Custom Action for field {field}")
        super().__init__(option_strings, dest, **self.field.arg_options) 
Example 36
Project: sippv   Author: evertrol   File: args.py    ISC License 5 votes vote down vote up
def parse():
    def nargs_range(nmin, nmax):
        class NargsRange(argparse.Action):
            def __call__(self, parser, args, values, option_string=None):
                if not nmin <= len(values) <= nmax:
                    msg = '"{f}" requires between {nmin} and {nmax} arguments'.format(
                        f=self.dest, nmin=nmin, nmax=nmax)
                    raise argparse.ArgumentTypeError(msg)
                setattr(args, self.dest, values)
        return NargsRange

    parser = argparse.ArgumentParser()
    parser.add_argument('files', nargs='+',
                        help="Input FITS files")
    parser.add_argument('-o', '--order', type=int,
                        help="PV order")
    parser.add_argument('-r', '--radial', action='store_true',
                        help="Use the radial term")
    parser.add_argument('-n', '--ndata', type=int, default=[64, 64],
                        action=nargs_range(1, 2), nargs='+',
                        help="Use n x n pixels to solve")
    parser.add_argument('--ext', action='append',
                        help="Extension to correct; "
                        "option can be used multiple times. "
                        "Default is the primary hdu.")
    parser.add_argument('-v', '--verbose', action='count', default=0,
                        help="Verbose level")
    args = parser.parse_args()

    if len(args.ndata) == 1:
        args.ndata = [args.ndata[0], args.ndata[0]]
    if not args.ext:
        args.ext = [0]

    return args 
Example 37
Project: sippv   Author: evertrol   File: wcs-addpv.py    ISC License 5 votes vote down vote up
def parse_args():
    def nargs_range(nmin, nmax):
        class NargsRange(argparse.Action):
            def __call__(self, parser, args, values, option_string=None):
                if not nmin <= len(values) <= nmax:
                    msg = '"{f}" requires between {nmin} and {nmax} arguments'.format(
                        f=self.dest, nmin=nmin, nmax=nmax)
                    raise argparse.ArgumentTypeError(msg)
                setattr(args, self.dest, values)
        return NargsRange


    parser = argparse.ArgumentParser()
    parser.add_argument('files', nargs='+',
                        help="Input FITS files")
    parser.add_argument('-o', '--order', type=int,
                        help="PV order")
    parser.add_argument('-r', '--radial', action='store_true',
                        help="Use the radial term")
    parser.add_argument('-n', '--ndata', type=int, default=[64, 64],
                        action=nargs_range(1, 2), nargs='+',
                        help="Use n x n pixels to solve")
    parser.add_argument('--ext', action='append',
                        help="Extension to correct; "
                        "option can be used multiple times. "
                        "Default is the primary hdu.")
    parser.add_argument('-v', '--verbose', action='count', default=0,
                        help="Verbose level")
    args = parser.parse_args()

    if len(args.ndata) == 1:
        args.ndata = [args.ndata[0], args.ndata[0]]
    if not args.ext:
        args.ext = [0]

    return args 
Example 38
Project: ptdt   Author: ypaialex   File: ptdt.py    GNU General Public License v3.0 5 votes vote down vote up
def required_length(nmin,nmax):
    '''
    Raises error through argparse if length of optional
    arguments for an option is not within specified bounds.
    
    '''
    class RequiredLength(argparse.Action):
        def __call__(self, parser, args, values, option_string=None):
            if not nmin<=len(values)<=nmax:
                msg='argument "{f}" requires between {nmin} and {nmax} arguments'.format(f=self.dest,nmin=nmin,nmax=nmax)
                raise argparse.ArgumentTypeError(msg)
            setattr(args, self.dest, values)
    return RequiredLength 
Example 39
Project: ironpython2   Author: IronLanguages   File: test_argparse.py    Apache License 2.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 40
Project: ironpython2   Author: IronLanguages   File: test_argparse.py    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 41
Project: ironpython2   Author: IronLanguages   File: test_argparse.py    Apache License 2.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 42
Project: analyzePF   Author: analyzeDFIR   File: pytestplugin.py    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 43
Project: python-scriptharness   Author: scriptharness   File: config.py    Mozilla Public License 2.0 5 votes vote down vote up
def add_argument(self, parser):
        """If self.definition['options'] is set, add the appropriate argument
        to the parser.

        Args:
          parser (argparse.ArgumentParser): the parser to add the argument to.

        Returns:
          argparse.Action: on success.

        Raises:
          ScriptHarnessException: on argparse.ArgumentParser.add_argument
            error.
        """
        if not self.definition.get('options'):
            return

        args = self.definition['options']
        kwargs = {
            'dest': self.name,
            'action': self.definition.get('action', None),
        }
        for key in self.definition.keys():
            if key not in ('dest', 'action', 'options', 'validate_cb',
                           'incompatible_vars', 'required_vars',
                           'optional_vars', 'parent_parser'):
                kwargs[key] = self.definition[key]
        try:
            return parser.add_argument(*args, **kwargs)
        except ValueError as exc_info:
            raise ScriptHarnessException(
                "Error adding %s argument to parser!" % self.name,
                exc_info
            ) 
Example 44
Project: oss-ftp   Author: aliyun   File: test_argparse.py    MIT License 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 45
Project: oss-ftp   Author: aliyun   File: test_argparse.py    MIT License 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 46
Project: oss-ftp   Author: aliyun   File: test_argparse.py    MIT License 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 47
Project: training_results_v0.6   Author: mlperf   File: data.py    Apache License 2.0 5 votes vote down vote up
def set_resnet_aug(aug):
    # standard data augmentation setting for resnet training
    aug.set_defaults(random_crop=0, random_resized_crop=1)
    aug.set_defaults(random_mirror=1)
    aug.set_defaults(min_random_area=0.08)
    aug.set_defaults(max_random_aspect_ratio=4./3., min_random_aspect_ratio=3./4.)
    aug.set_defaults(brightness=0.4, contrast=0.4, saturation=0.4, pca_noise=0.1)

# Action to translate --set-data-aug-level <N> arg to its component settings. 
Example 48
Project: training_results_v0.6   Author: mlperf   File: data.py    Apache License 2.0 5 votes vote down vote up
def set_resnet_aug(aug):
    # standard data augmentation setting for resnet training
    aug.set_defaults(random_crop=0, random_resized_crop=1)
    aug.set_defaults(random_mirror=1)
    aug.set_defaults(min_random_area=0.08)
    aug.set_defaults(max_random_aspect_ratio=4./3., min_random_aspect_ratio=3./4.)
    aug.set_defaults(brightness=0.4, contrast=0.4, saturation=0.4, pca_noise=0.1)

# Action to translate --set-data-aug-level <N> arg to its component settings. 
Example 49
Project: WebPocket   Author: TuuuNya   File: argparse_completer.py    GNU General Public License v3.0 5 votes vote down vote up
def _resolve_choices_for_arg(self, action: argparse.Action, used_values=()) -> List[str]:
        if action.dest in self._arg_choices:
            args = self._arg_choices[action.dest]

            # is the argument a string? If so, see if we can find an attribute in the
            # application matching the string.
            if isinstance(args, str):
                try:
                    args = getattr(self._cmd2_app, args)
                except AttributeError:
                    # Couldn't find anything matching the name
                    return []

            # is the provided argument a callable. If so, call it
            if callable(args):
                try:
                    if self._cmd2_app is not None:
                        try:
                            args = args(self._cmd2_app)
                        except TypeError:
                            args = args()
                    else:
                        args = args()
                except TypeError:
                    return []

            try:
                iter(args)
            except TypeError:
                pass
            else:
                # filter out arguments we already used
                args = [arg for arg in args if arg not in used_values]

                if len(args) > 0:
                    return args

        return [] 
Example 50
Project: eclcli   Author: nttcom   File: shell.py    Apache License 2.0 5 votes vote down vote up
def obsoleted_by(new_dest):
    class ObsoletedByAction(argparse.Action):
        def __call__(self, parser, namespace, values, option_string=None):
            old_dest = option_string or self.dest
            print('%s is obsolete! See help for more details.' % old_dest)
            setattr(namespace, new_dest, values)
    return ObsoletedByAction