Python docopt.docopt() Examples

The following are 30 code examples of docopt.docopt(). 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: __main__.py    From Pointer-Generator with MIT License 6 votes vote down vote up
def main(args=None):
    args = docopt(to_string(__doc__), args, version=__version__)
    summarizer, document, items_count, reference_summary = handle_arguments(args)

    evaluated_sentences = summarizer(document, items_count)
    reference_document = PlaintextParser.from_string(reference_summary,
        Tokenizer(args["--language"]))
    reference_sentences = reference_document.document.sentences

    for name, evaluate_document, evaluate in AVAILABLE_EVALUATIONS:
        if evaluate_document:
            result = evaluate(evaluated_sentences, document.sentences)
        else:
            result = evaluate(evaluated_sentences, reference_sentences)
        print("%s: %f" % (name, result))

    return 0 
Example #2
Source File: wonderful_bing.py    From wonderful_bing with MIT License 6 votes vote down vote up
def main():
    arguments = docopt(__doc__, version=__version__)
    if not path.exists(arguments['--directory']):
        sys.exit('No such directory :(')

    try:
        wonderful_bing = WonderfulBing(arguments)
        if arguments['story']:
            print(wonderful_bing.bing.picture_story)
        else:
            wonderful_bing.rock()
    except requests.exceptions.ConnectionError:
        print("ConnectionError,check your network please.")
        print("Will try again after 5 minutes.")
        time.sleep(300)
        wonderful_bing.rock() 
Example #3
Source File: clinacl.py    From clinacl with MIT License 6 votes vote down vote up
def main():
    args = docopt.docopt(__doc__)
    if args['secretgen']:
        secretgen()
    elif args['encrypt']:
        encrypt(args['<secretkey>'], args['<nonce>'])
    elif args['decrypt']:
        decrypt(args['<secretkey>'])
    elif args['signinggen']:
        signinggen()
    elif args['verifygen']:
        verifygen(args['<signingkey>'])
    elif args['keybase']:
        if args['sign']:
            keybase_sign(args['<signingkey>'])
        elif args['verify']:
            keybase_verify()
    else:
        if args['sign']:
            sign(args['<signingkey>'])
        elif args['verify']:
            verify(args['<verifykey>']) 
Example #4
Source File: stac_validator.py    From stac-validator with Apache License 2.0 6 votes vote down vote up
def main():
    args = docopt(__doc__)
    follow = args.get("--follow")
    stac_file = args.get("<stac_file>")
    stac_spec_dirs = args.get("--spec_dirs", None)
    version = args.get("--version")
    verbose = args.get("--verbose")
    nthreads = args.get("--threads", 10)
    timer = args.get("--timer")
    log_level = args.get("--log_level", "CRITICAL")

    if timer:
        start = default_timer()

    stac = StacValidate(stac_file, stac_spec_dirs, version, log_level, follow)
    _ = stac.run(nthreads)
    shutil.rmtree(stac.dirpath)

    if verbose:
        print(json.dumps(stac.message, indent=4))
    else:
        print(json.dumps(stac.status, indent=4))

    if timer:
        print(f"Validator took {default_timer() - start:.2f} seconds") 
Example #5
Source File: ankdown.py    From ankdown with MIT License 6 votes vote down vote up
def main():
    """Run the thing."""
    apply_arguments(docopt(__doc__, version=VERSION))
    # print(yaml.dump(CONFIG))
    initial_dir = os.getcwd()
    recur_dir = os.path.abspath(os.path.expanduser(CONFIG['recur_dir']))
    pkg_arg = os.path.abspath(os.path.expanduser(CONFIG['pkg_arg']))

    if CONFIG['highlight']:
        apply_highlight_css()

    with tempfile.TemporaryDirectory() as tmpdirname:
        os.chdir(tmpdirname) # genanki is very opinionated about where we are.

        card_iterator = cards_from_dir(recur_dir)
        cards_to_apkg(card_iterator, pkg_arg)

        os.chdir(initial_dir) 
Example #6
Source File: __init__.py    From farcy with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def main():
    """Provide an entry point into Farcy."""
    args = docopt(__doc__, version='farcy v{0}'.format(__version__))
    config = Config(args['REPOSITORY'], debug=args['--debug'],
                    exclude_paths=args['--exclude-path'],
                    limit_users=args['--limit-user'],
                    log_level=args['--logging'],
                    pr_issue_report_limit=args['--comments-per-pr'],
                    pull_requests=args['--pr'],
                    start_event=args['--start'])
    if config.repository is None:
        sys.stderr.write('No repository specified\n')
        return 2

    try:
        Farcy(config).run()
    except KeyboardInterrupt:
        sys.stderr.write('Farcy shutting down. Goodbye!\n')
        return 0
    except FarcyException as exc:
        sys.stderr.write('{0}\n'.format(exc))
        return 1 
Example #7
Source File: release.py    From mdk with Apache License 2.0 6 votes vote down vote up
def main():
    """Run the release."""
    options = docopt(HELP)
    for index, step in enumerate([ensure_not_dirty,
                                  ensure_master,
                                  git_pull,
                                  ensure_passing_tests,
                                  bump_mdk_versions,
                                  ]):
        print("Step {}: {}".format(index + 1, step.__name__))
        step(options)
    print("""\
The release has been committed and tagged locally.

You can now push it upstream by running:

    git push origin master --tags
""") 
Example #8
Source File: ciftify_dlabel_to_vol.py    From ciftify with MIT License 6 votes vote down vote up
def main():
    arguments = docopt(__doc__)

    logger.setLevel(logging.WARNING)

    if arguments['--debug']:
        logger.setLevel(logging.DEBUG)
        logging.getLogger('ciftify').setLevel(logging.DEBUG)

    ## set up the top of the log
    logger.info('{}{}'.format(ciftify.utils.ciftify_logo(),
        ciftify.utils.section_header('Starting ciftify_dlabel_to_vol')))

    ciftify.utils.log_arguments(arguments)

    with ciftify.utils.TempDir() as tmpdir:
        logger.info('Creating tempdir:{} on host:{}'.format(tmpdir,
                    os.uname()[1]))
        ret = run_ciftify_dlabel_to_vol(arguments, tmpdir) 
Example #9
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 #10
Source File: ciftify_statclust_report.py    From ciftify with MIT License 6 votes vote down vote up
def main():
    arguments = docopt(__doc__)

    logger.setLevel(logging.WARNING)

    if arguments['--debug']:
        logger.setLevel(logging.DEBUG)
        logging.getLogger('ciftify').setLevel(logging.DEBUG)

    ## set up the top of the log
    logger.info('{}{}'.format(ciftify.utils.ciftify_logo(),
        ciftify.utils.section_header('Starting ciftify_statclust_report')))

    ciftify.utils.log_arguments(arguments)

    with ciftify.utils.TempDir() as tmpdir:
        logger.info('Creating tempdir:{} on host:{}'.format(tmpdir,
                    os.uname()[1]))
        ret = run_ciftify_dlabel_report(arguments, tmpdir) 
Example #11
Source File: ciftify_vol_result.py    From ciftify with MIT License 6 votes vote down vote up
def main():
    arguments       = docopt(__doc__)
    debug           = arguments['--debug']

    if debug:
        logger.setLevel(logging.DEBUG)
        logging.getLogger('ciftify').setLevel(logging.DEBUG)

    ## set up the top of the log
    logger.info('{}{}'.format(ciftify.utils.ciftify_logo(),
        ciftify.utils.section_header('Starting ciftify_vol_result')))
    ciftify.utils.log_arguments(arguments)

    settings = UserSettings(arguments)

    with ciftify.utils.TempDir() as tmpdir:
        logger.info('Creating tempdir:{} on host:{}'.format(tmpdir,
                    os.uname()[1]))
        ret = run_ciftify_vol_result(settings, tmpdir)

    logger.info(ciftify.utils.section_header('Done ciftify_vol_result'))
    sys.exit(ret) 
Example #12
Source File: render.py    From adeptRL with GNU General Public License v3.0 6 votes vote down vote up
def parse_args():
    from docopt import docopt

    args = docopt(__doc__)
    args = {k.strip("--").replace("-", "_"): v for k, v in args.items()}
    del args["h"]
    del args["help"]
    args = DotDict(args)

    args.logdir = parse_path(args.logdir)

    # TODO implement Option utility
    epoch_option = parse_none(args.epoch)
    if epoch_option:
        args.epoch = int(float(epoch_option))
    else:
        args.epoch = epoch_option
    args.start = int(float(args.start))
    args.end = int(float(args.end))
    args.gpu_id = int(args.gpu_id)
    args.seed = int(args.seed)
    return args 
Example #13
Source File: cmd.py    From scrapple with MIT License 6 votes vote down vote up
def runCLI():
    """
    The starting point for the execution of the Scrapple command line tool.

    runCLI uses the docstring as the usage description for the scrapple command. \
    The class for the required command is selected by a dynamic dispatch, and the \
    command is executed through the execute_command() method of the command class.
    """
    args = docopt(__doc__, version='0.3.0')
    try:
        check_arguments(args)
        command_list = ['genconfig', 'run', 'generate']
        select = itemgetter('genconfig', 'run', 'generate')
        selectedCommand = command_list[select(args).index(True)]
        cmdClass = get_command_class(selectedCommand)
        obj = cmdClass(args)
        obj.execute_command()
    except POSSIBLE_EXCEPTIONS as e:
        print('\n', e, '\n') 
Example #14
Source File: audfprint.py    From audfprint with MIT License 6 votes vote down vote up
def setup_matcher(args):
    """Create a new matcher objects, set parameters from docopt structure"""
    matcher = audfprint_match.Matcher()
    matcher.window = int(args['--match-win'])
    matcher.threshcount = int(args['--min-count'])
    matcher.max_returns = int(args['--max-matches'])
    matcher.search_depth = int(args['--search-depth'])
    matcher.sort_by_time = args['--sortbytime']
    matcher.exact_count = args['--exact-count'] | args['--illustrate'] | args['--illustrate-hpf']
    matcher.illustrate = args['--illustrate'] | args['--illustrate-hpf']
    matcher.illustrate_hpf = args['--illustrate-hpf']
    matcher.verbose = args['--verbose']
    matcher.find_time_range = args['--find-time-range']
    matcher.time_quantile = float(args['--time-quantile'])
    return matcher


# Command to construct the reporter object 
Example #15
Source File: ciftify_atlas_report.py    From ciftify with MIT License 6 votes vote down vote up
def main():
    arguments = docopt(__doc__)

    logger.setLevel(logging.WARNING)

    if arguments['--debug']:
        logger.setLevel(logging.DEBUG)
        logging.getLogger('ciftify').setLevel(logging.DEBUG)

    ## set up the top of the log
    logger.info('{}{}'.format(ciftify.utils.ciftify_logo(),
        ciftify.utils.section_header('Starting ciftify_atlas_report')))

    ciftify.utils.log_arguments(arguments)

    with ciftify.utils.TempDir() as tmpdir:
        logger.info('Creating tempdir:{} on host:{}'.format(tmpdir,
                    os.uname()[1]))
        ret = run_ciftify_dlabel_report(arguments, tmpdir) 
Example #16
Source File: __main__.py    From godot-gdscript-toolkit with MIT License 6 votes vote down vote up
def main():
    arguments = docopt(
        __doc__,
        version="gdparse {}".format(
            pkg_resources.get_distribution("gdtoolkit").version
        ),
    )

    if not isinstance(arguments, dict):
        print(arguments)
        sys.exit(0)

    for file_path in arguments["<file>"]:
        with open(file_path, "r") as fh:  # TODO: handle exception
            content = fh.read()
            tree = parser.parse(content)  # TODO: handle exception
            if arguments["--pretty"]:
                print(tree.pretty())
            elif arguments["--verbose"]:
                print(tree) 
Example #17
Source File: gtfs2db.py    From pygtfs with MIT License 6 votes vote down vote up
def main():
    """Script to load GTFS data into a database."""

    args = docopt(__doc__, version=__version__)
    schedule = Schedule(args['<database>'])

    if args['append']:
        append_feed(schedule, args['<feed_file>'],
                    chunk_size=int(args['--chunk-size']))
    elif args['delete']:
        delete_feed(schedule, args['<feed_file>'],
                    interactive=args['--interactive'])
    elif args['overwrite']:
        overwrite_feed(schedule, args['<feed_file>'],
                       interactive=args['--interactive'],
                       chunk_size=int(args['--chunk-size']))
    elif args['list']:
        list_feeds(schedule) 
Example #18
Source File: docopt_dispatch.py    From pgrepup with GNU General Public License v3.0 6 votes vote down vote up
def __call__(self, *args, **kwargs):
        from docopt import docopt
        arguments = docopt(*args, **kwargs)

        from ..config import load as config_load
        from ..config import ConfigFileNotFound

        try:
            config_load(arguments['-c'])
        except ConfigFileNotFound as e:
            if not arguments['config']:
                puts(colored.red(str(e)))
                sys.exit(1)

        for patterns, function in self._functions.items():
            if all(arguments[pattern] for pattern in patterns):
                function(**self._kwargify(arguments))
                return
        raise DispatchError('None of dispatch conditions %s is triggered'
                            % self._formated_patterns) 
Example #19
Source File: test_generate.py    From scrapple with MIT License 5 votes vote down vote up
def test_if_generate_instance_created():
	args = docopt(doc, "generate project1 test_project")
	gc = generate.GenerateCommand(args)
	assert_is_instance(gc, generate.GenerateCommand) 
Example #20
Source File: test_generate.py    From scrapple with MIT License 5 votes vote down vote up
def test_nonexistent_project():
	args = docopt(doc, "generate project_unknown project2")
	gc = generate.GenerateCommand(args)
	with output() as out:
		gc.execute_command()
	alert = out.getvalue().strip()
	expected_alert = "project_unknown.json does not exist. Use ``scrapple genconfig``."
	assert_in(expected_alert, alert) 
Example #21
Source File: test_generate.py    From scrapple with MIT License 5 votes vote down vote up
def test_css_scraper_generate():
	args = docopt(doc, "generate project2 project2")
	gc = generate.GenerateCommand(args)
	gc.execute_command()
	with open(os.path.join(os.getcwd(), 'project2.py'), 'r') as f:
		program = f.read()
	assert_in("from scrapple.selectors.css import CssSelector", program)
	assert_in('page0 = CssSelector("https://www.basketball-reference.com/teams/")', program) 
Example #22
Source File: test_generate.py    From scrapple with MIT License 5 votes vote down vote up
def test_xpath_scraper_generate():
	args = docopt(doc, "generate project1 project1")
	gc = generate.GenerateCommand(args)
	gc.execute_command()
	with open(os.path.join(os.getcwd(), 'project1.py'), 'r') as f:
		program = f.read()
	assert_in("from scrapple.selectors.xpath import XpathSelector", program)
	assert_in('page0 = XpathSelector("https://trakt.tv/shows/mr-robot")', program) 
Example #23
Source File: pipreqs.py    From pipenv with MIT License 5 votes vote down vote up
def main():  # pragma: no cover
    args = docopt(__doc__, version=__version__)
    log_level = logging.DEBUG if args['--debug'] else logging.INFO
    logging.basicConfig(level=log_level, format='%(levelname)s: %(message)s')

    try:
        init(args)
    except KeyboardInterrupt:
        sys.exit(0) 
Example #24
Source File: microupload.py    From intellij-micropython with Apache License 2.0 5 votes vote down vote up
def main(args: List[str]) -> None:
    global verbose
    opts = docopt(__doc__, argv=args)
    verbose = opts['--verbose']
    root = opts['PATH']

    chdir = opts['--chdir']
    if chdir:
        os.chdir(chdir)

    port = opts['PORT']
    print('Connecting to {}'.format(port), file=sys.stderr)
    board = Pyboard(port)
    files = Files(board)
    rel_root = os.path.relpath(root, os.getcwd())

    wait_for_board()

    if os.path.isdir(root):
        to_upload = [os.path.join(rel_root, x)
                     for x in list_files(root, opts['--exclude'])]
    else:
        to_upload = [rel_root]

    created_cache = set()
    for path in progress('Uploading files', to_upload):
        local_path = os.path.abspath(path)
        remote_path = os.path.normpath(path)
        if verbose:
            print('\n{} -> {}'.format(local_path, remote_path),
                  file=sys.stderr, flush=True)
        remote_dir = os.path.dirname(path)
        if remote_dir:
            make_dirs(files, remote_dir, created_cache)
        with open(local_path, 'rb') as fd:
            files.put(remote_path, fd.read())

    print('Soft reboot', file=sys.stderr, flush=True)
    soft_reset(board) 
Example #25
Source File: cli.py    From aws-okta-processor with MIT License 5 votes vote down vote up
def main():
    """Main CLI entrypoint."""
    from . import commands
    options = docopt(__doc__, version=VERSION)

    # Here we'll try to dynamically match the command the user is trying to run
    # with a pre-defined command class we've already created.
    for (k, v) in six.iteritems(options):
        if hasattr(commands, k) and v:
            module = getattr(commands, k)
            commands = getmembers(module, isclass)
            command_class = get_command(commands=commands)
            command = command_class(options)
            command.run() 
Example #26
Source File: get_snaps.py    From snapy with MIT License 5 votes vote down vote up
def main():
    arguments = docopt(__doc__)
    quiet = arguments['--quiet']
    unzip = arguments['--unzip']
    username = arguments['--username']
    
    auth_token = arguments['--auth-token']
    
    gmail = arguments['--gmail']
    if arguments['--gpasswd'] is None:
        gpasswd = getpass('Gmail password:')
    else:
        gpasswd = arguments['--gpasswd']

    path = arguments['<path>']

    if not os.path.isdir(path):
        print('No such directory: {0}'.format(arguments['<path>']))
        sys.exit(1)

    s = Snapchat()

    if auth_token:
        s.restore_token(username, auth_token, gmail, gpasswd)

    else:
        if arguments['--password'] is None:
            password = getpass('Password:')
        else:
            password = arguments['--password']

        if not s.login(username, password, gmail, gpasswd)['updates_response'].get('logged'):
            print('Invalid username or password')
            sys.exit(1)

    for snap in s.get_snaps():
        process_snap(s, snap, path, quiet, unzip) 
Example #27
Source File: cli.py    From cloudformation-environmentbase with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, quiet=False, doc=__doc__):
        """
        CLI constructor is responsible for parsing sys.argv to collect configuration information.
        If you need to change the config file from the default name set the property 'config_filename'
        from the constructor.
        quiet: is provided to suppress output, primarily for unit testing
        """
        self.quiet = quiet

        self.args = docopt(doc, version='environmentbase %s' % version.__version__)

        # Parsing this config filename here is required since
        # the file is already loaded in self.update_config()
        self.config_filename = self.args.get('--config-file') 
Example #28
Source File: findusb.py    From intellij-micropython with Apache License 2.0 5 votes vote down vote up
def main() -> None:
    opts = docopt(__doc__, argv=sys.argv[1:])
    vid_pid_list = opts['VID:PID']
    if vid_pid_list:
        ids = [parse_id(arg) for arg in sys.argv[1:]]
        for device in find_devices(ids):
            print(device)
    else:
        for port in comports():
            if port.vid is not None and port.pid is not None:
                print('%s: 0x%02x:0x%02x' % (port.device, port.vid, port.pid)) 
Example #29
Source File: microcleanfs.py    From intellij-micropython with Apache License 2.0 5 votes vote down vote up
def main(args: List[str]) -> None:
    opts = docopt(__doc__, argv=args)
    port = opts['PORT']
    force = opts['--force']

    print('Connecting to {}'.format(port), file=sys.stderr)
    board = Pyboard(port)
    files = Files(board)

    # Specifying subdirectories DOES NOT work as they will be deleted when the
    # parent directory is deleted. Specifying top level directories DOES work.
    exclude_files = ['boot.py']

    print('Removing the contents of the file system')
    wait_for_board()
    for name in files.ls(long_format=False):
        if force or name not in exclude_files:
            try:
                files.rm(name)
            except (RuntimeError, PyboardError):
                try:
                    files.rmdir(name)
                except (RuntimeError, PyboardError):
                    print('Unknown Error removing file {}'.format(name),
                          file=sys.stderr)

    print('Done') 
Example #30
Source File: yans.py    From YANS with MIT License 5 votes vote down vote up
def main():
    '''Main entry point for the yans CLI.'''
    args = docopt(__doc__, version=__version__)

    ensure_docker_machine()

    if args['--verbose']:
        logging.getLogger().setLevel(logging.DEBUG)

    topo_file = args['--topo']
    try:
        topo = Topology(topo_file)
    except TopologySpecError as err:
        sys.exit(err)

    if args['up']:
        create_links(topo.links)
        create_nodes(topo.nodes)
        for link in topo.links:
            for interface in link.interfaces:
                bind_interface(interface)
        topo.draw()
        print('To log into each node:')
        for node in topo.nodes:
            print('`$ yans -t ' + topo_file + ' console ' + node.name + '`')

    if args['destroy']:
        destroy_nodes(topo.nodes)
        destroy_links(topo.links)

    if args['console']:
        node_name = args['<node_name>']
        node = topo.node_by_name(node_name)
        if node:
            attach_node(node)
        else:
            sys.exit('Node named "' + node_name + '" is not found in ' + topo_file)