Python docopt.DocoptExit() Examples

The following are 30 code examples of docopt.DocoptExit(). 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 docopt , or try the search function .
Example #1
Source File: policy.py    From k8s-exec-plugin with Apache License 2.0 6 votes vote down vote up
def parse_line(self, policy):
        """
        Takes a single line of policy as defined in the annotations of a
        pod and returns the equivalent libcalico Rule object.
        :param policy: Policy string from annotations.
        :return: A Rule object which represent the given policy.
        """
        _log.info("Parsing policy line: '%s'", policy)
        splits = policy.split()

        try:
            args = docopt.docopt(__doc__, argv=splits)
        except docopt.DocoptExit:
            raise ValueError("Failed to parse policy: %s", policy)

        # Generate a rule object from the arguments.
        rule = self._generate_rule(args)

        return rule 
Example #2
Source File: kiwi_compat.py    From kiwi with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        try:
            self.compat_args = docopt(
                __doc__, options_first=True
            )
        except DocoptExit as e:
            message_header = '\n'.join(
                [
                    'The provided legacy kiwi commandline is invalid',
                    'or not supported. Plase check the following usage',
                    'information if you just mistyped the call:'
                ]
            )
            message_footer = '\n'.join(
                [
                    'In case of a correct legacy kiwi command but not',
                    'supported by kiwicompat, please contact us via the',
                    'github issue system at:\n',
                    'https://github.com/OSInside/kiwi/issues'
                ]
            )
            raise NotImplementedError(
                '%s\n\n%s\n\n%s' %
                (message_header, format(e), message_footer)
            ) 
Example #3
Source File: dnspod_ddns.py    From dnspod_ddns with Apache License 2.0 6 votes vote down vote up
def main():
    try:
        arguments = docopt.docopt(__doc__)
    except docopt.DocoptExit:
        print __doc__.strip()
        return
    app = App(arguments)
    action = arguments['-d']
    if action != None:
        if action in ['start', 'stop', 'restart']:
            sys.argv[1] = action
            daemon_runner = runner.DaemonRunner(app)
            daemon_runner.do_action()
        else:
            print __doc__.strip()
            return
    else:
        app.run() 
Example #4
Source File: treon.py    From treon with MIT License 6 votes vote down vote up
def main():
    try:
        arguments = docopt(__doc__, version=__version__)
    except DocoptExit:
        sys.exit(__doc__)

    setup_logging(arguments)
    LOG.info('Executing treon version %s', __version__)
    thread_count = arguments['--threads'] or DEFAULT_THREAD_COUNT
    notebooks = get_notebooks_to_test(arguments)
    tasks = [Task(notebook) for notebook in notebooks]
    print_test_collection(notebooks)
    trigger_tasks(tasks, thread_count)
    has_failed = print_test_result(tasks)

    if has_failed:
        sys.exit(-1) 
Example #5
Source File: test_konch.py    From konch with MIT License 5 votes vote down vote up
def test_parse_args():
    try:
        args = konch.parse_args()
        assert "--shell" in args
        assert "init" in args
        assert "<config_file>" in args
        assert "--name" in args
    except DocoptExit:
        pass 
Example #6
Source File: docopt_command.py    From deepWordBug with Apache License 2.0 5 votes vote down vote up
def docopt_full_help(docstring, *args, **kwargs):
    try:
        return docopt(docstring, *args, **kwargs)
    except DocoptExit:
        raise SystemExit(docstring) 
Example #7
Source File: sqltomvt.py    From openmaptiles-tools with MIT License 5 votes vote down vote up
def get_layers(self) -> Iterable[Tuple[str, Layer]]:
        all_layers = [(v.id, v) for v in self.tileset.layers]
        if not all_layers:
            raise DocoptExit('Could not find any layer definitions')
        duplicates = find_duplicates([k for k, v in all_layers])
        if duplicates:
            raise DocoptExit(f'Duplicate layer IDs found: {", ".join(duplicates)}')
        if not self.layer_ids:
            yield from all_layers
            return
        found_layers = set()
        skipped_layers = set()
        for layer_id, layer in all_layers:
            if (layer_id in self.layer_ids) != self.exclude_layers:
                found_layers.add(layer_id)
                yield layer_id, layer
            else:
                skipped_layers.add(layer_id)
        expected_result = skipped_layers if self.exclude_layers else found_layers
        if self.layer_ids != expected_result:
            unknown = sorted(self.layer_ids - expected_result)
            raise DocoptExit(
                f"Unable to find layer [{', '.join(unknown)}]. Available layers:\n" +
                '\n'.join(f"* {k}" + (
                    f"\n{v.description}" if v.description else ''
                ) for k, v in all_layers)
            ) 
Example #8
Source File: utils.py    From openmaptiles-tools with MIT License 5 votes vote down vote up
def parse_zxy_param(param):
    zxy = param.strip()
    if not re.match(r'^\d+[/, ]+\d+[/, ]+\d+$', zxy):
        raise DocoptExit('Invalid <tile_zxy> - must be in the form "zoom/x/y"')
    zoom, x, y = [int(v) for v in re.split(r'[/, ]+', zxy)]
    return zoom, x, y 
Example #9
Source File: test_main.py    From acl2017-interactive_summarizer with Apache License 2.0 5 votes vote down vote up
def test_args_url_and_file(self):
        self.assertRaises(DocoptExit, docopt, to_string(main_doc), 'lsa --url=URL --file=FILE'.split(), version=__version__) 
Example #10
Source File: test_main.py    From acl2017-interactive_summarizer with Apache License 2.0 5 votes vote down vote up
def test_args_two_commands(self):
        self.assertRaises(DocoptExit, docopt, to_string(main_doc), 'lsa luhn'.split(), version=__version__) 
Example #11
Source File: test_main.py    From acl2017-interactive_summarizer with Apache License 2.0 5 votes vote down vote up
def test_args_none(self):
        self.assertRaises(DocoptExit, docopt, to_string(main_doc), None, version=__version__) 
Example #12
Source File: stalk.py    From git-stalk-cli with MIT License 5 votes vote down vote up
def run():
    """Parsing the command line arguments using argparse and calls the update
    or show_contri function as required"""
    try:
        args = docopt(__doc__, version=__version__)
    except DocoptExit:
        print(__doc__)
        sys.exit(1)

    if args["--update"]:
        update()
    else:
        show_contri(args) 
Example #13
Source File: kiwi.py    From kiwi with GNU General Public License v3.0 5 votes vote down vote up
def main():
    """
    kiwi - main application entry point

    Initializes a global log object and handles all errors of the
    application. Every known error is inherited from KiwiError,
    everything else is passed down until the generic Exception
    which is handled as unexpected error including the python
    backtrace
    """
    docopt.__dict__['extras'] = extras
    try:
        App()
    except KiwiError as e:
        # known exception, log information and exit
        log.error('%s: %s', type(e).__name__, format(e))
        sys.exit(1)
    except KeyboardInterrupt:
        log.error('kiwi aborted by keyboard interrupt')
        sys.exit(1)
    except docopt.DocoptExit as e:
        # exception thrown by docopt, results in usage message
        usage(e)
        sys.exit(1)
    except SystemExit as e:
        # user exception, program aborted by user
        sys.exit(e)
    except Exception:
        # exception we did no expect, show python backtrace
        log.error('Unexpected error:')
        raise 
Example #14
Source File: config_test.py    From dusty with MIT License 5 votes vote down vote up
def test_config_set_fails_with_no_args(self):
        with self.assertRaises(docopt.DocoptExit):
            self.run_command('config set') 
Example #15
Source File: __main__.py    From catcher with Apache License 2.0 5 votes vote down vote up
def main(args=None):
    try:
        arguments = docopt(__doc__, argv=args, version=APPVSN)
    except DocoptExit as usage:
        print(usage)
        sys.exit(1)
    path = os.getcwd()
    logger.configure(arguments['--log-level'], not arguments['--no-color'])
    result = run_tests(path, arguments)
    if result:
        sys.exit(0)
    else:
        sys.exit(1) 
Example #16
Source File: command.py    From mech with MIT License 5 votes vote down vote up
def run(self):
        raise docopt.DocoptExit() 
Example #17
Source File: test_arguments.py    From we-get with MIT License 5 votes vote down vote up
def test_required_argument_sort_type(self):
        sys.argv = ['prog_name', '--sort-type']
        self.assertRaises(docopt.DocoptExit, docopt.docopt, __doc__) 
Example #18
Source File: cli_core.py    From aliyun-log-cli with MIT License 5 votes vote down vote up
def docopt_ex(doc, usage, method_param_usage, hlp=True, ver=None):
    argv = sys.argv[1:]

    # support customized help
    if len(argv) <= 0 or "--help" in argv[0]:
        print(usage)
        return

    first_cmd = argv[0]

    try:
        return docopt(doc, help=hlp, version=ver)
    except DocoptExit as ex:
        # show customized error
        if first_cmd == "configure":
            print("Invalid parameters.\n")
            print("Usage:\n" + MORE_DOCOPT_CMD)
            return
        elif first_cmd == "log" and len(argv) > 1:
            second_cmd = argv[1]
            header_printed = False
            for cmd in doc.split("\n"):
                if "aliyunlog log " + second_cmd + " " in cmd:
                    if not header_printed:
                        print("Invalid parameters.\n")
                        print("Usage:")
                        header_printed = True

                    print(cmd)

            if header_printed and second_cmd in method_param_usage:
                print("\nOptions:")
                print(method_param_usage[second_cmd])
                print(GLOBAL_OPTIONS_STR)
            else:
                print("Unknown subcommand.")
                print(usage)

        else:
            print("Unknown command.\n")
            print(usage) 
Example #19
Source File: test_cli.py    From dcos-launch with Apache License 2.0 5 votes vote down vote up
def test_noop():
    """Ensure docopt exit (displays usage)
    """
    with pytest.raises(DocoptExit):
        main([])
    with pytest.raises(DocoptExit):
        main(['foobar']) 
Example #20
Source File: test_arguments.py    From we-get with MIT License 5 votes vote down vote up
def test_required_argument_search(self):
        sys.argv = ['prog_name', '--search']
        self.assertRaises(docopt.DocoptExit, docopt.docopt, __doc__) 
Example #21
Source File: test_arguments.py    From we-get with MIT License 5 votes vote down vote up
def test_required_argument_target(self):
        sys.argv = ['prog_name', '--target']
        self.assertRaises(docopt.DocoptExit, docopt.docopt, __doc__) 
Example #22
Source File: test_arguments.py    From we-get with MIT License 5 votes vote down vote up
def test_required_argument_filter(self):
        sys.argv = ['prog_name', '--filter']
        self.assertRaises(docopt.DocoptExit, docopt.docopt, __doc__) 
Example #23
Source File: test_arguments.py    From we-get with MIT License 5 votes vote down vote up
def test_required_argument_results(self):
        sys.argv = ['prog_name', '--results']
        self.assertRaises(docopt.DocoptExit, docopt.docopt, __doc__) 
Example #24
Source File: test_arguments.py    From we-get with MIT License 5 votes vote down vote up
def test_required_argument_quality(self):
        sys.argv = ['prog_name', '--quality']
        self.assertRaises(docopt.DocoptExit, docopt.docopt, __doc__) 
Example #25
Source File: test_arguments.py    From we-get with MIT License 5 votes vote down vote up
def test_no_required_argument_list(self):
        sys.argv = ['prog_name', '--list']
        try:
            docopt.docopt(__doc__)
        except docopt.DocoptExit:
            self.fail('--list required argument!') 
Example #26
Source File: test_arguments.py    From we-get with MIT License 5 votes vote down vote up
def test_no_required_argument_links(self):
        sys.argv = ['prog_name', '--links']
        try:
            docopt.docopt(__doc__)
        except docopt.DocoptExit:
            self.fail('--links required argument!') 
Example #27
Source File: test_arguments.py    From we-get with MIT License 5 votes vote down vote up
def test_no_required_argument_get_list(self):
        sys.argv = ['prog_name', '--get-list']
        try:
            docopt.docopt(__doc__)
        except docopt.DocoptExit:
            self.fail('--get-list required argument!') 
Example #28
Source File: test_arguments.py    From we-get with MIT License 5 votes vote down vote up
def test_no_required_argument_version(self):
        sys.argv = ['prog_name', '--version']
        try:
            docopt.docopt(__doc__)
        except docopt.DocoptExit:
            self.fail('--version required argument!') 
Example #29
Source File: test_core_we_get.py    From we-get with MIT License 5 votes vote down vote up
def test_parse_arguments(argv, exp_res):
    wg = WG()
    if argv is None:
        with pytest.raises(DocoptExit):
            wg.parse_arguments()
        assert vars(wg) == exp_res
        with pytest.raises(DocoptExit):
            wg.parse_arguments(argv)
        assert vars(wg) == exp_res
    else:
        wg.parse_arguments(argv)
        assert vars(wg) == exp_res 
Example #30
Source File: test_cli.py    From lbry-sdk with MIT License 5 votes vote down vote up
def test_can_parse_api_method_docs(self):
        failures = []
        for name, fn in Daemon.callable_methods.items():
            try:
                docopt.docopt(fn.__doc__, ())
            except docopt.DocoptLanguageError as err:
                failures.append(f"invalid docstring for {name}, {err.args[0]}")
            except docopt.DocoptExit:
                pass
        if failures:
            self.fail("\n" + "\n".join(failures))