Python click.argument() Examples

The following are 30 code examples of click.argument(). 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 click , or try the search function .
Example #1
Source File: policies.py    From python-viptela with GNU General Public License v3.0 6 votes vote down vote up
def definition(ctx, name, json, definition_type):  #pylint: disable=unused-argument
    """
    Show policy definition information
    """
    policy_definitions = PolicyDefinitions(ctx.auth, ctx.host)
    policy_data = PolicyData(ctx.auth, ctx.host)
    pp = pprint.PrettyPrinter(indent=2)

    if name:
        policy_definition_dict = policy_definitions.get_policy_definition_dict(definition_type)
        if name in policy_definition_dict:
            policy_definition = policy_data.export_policy_definition_list(policy_definition_dict[name]['type'].lower())
            # list_keys(policy_definition['definition'])
            pp.pprint(policy_definition)
    else:
        policy_definition_list = policy_data.export_policy_definition_list(definition_type)
        pp.pprint(policy_definition_list) 
Example #2
Source File: tokens_to_top_bigrams.py    From textkit with MIT License 6 votes vote down vote up
def tokens2topbigrams(sep, measure, freq, scores, tokens):
    '''Find top most interesting bi-grams in a token document.
    Uses the --measure argument to determine what measure to use to define
    'interesting'.
    '''

    content = read_tokens(tokens)
    bcf = nltk.collocations.BigramCollocationFinder.from_words(content)
    bcf.apply_freq_filter(freq)

    nltk_measure = MEASURES[measure]
    bigrams = bcf.score_ngrams(nltk_measure)

    out = [b[0] for b in bigrams]
    if scores:
        out = [b[0] + tuple([str(b[1])]) for b in bigrams]
    write_csv(out, str(sep)) 
Example #3
Source File: method_terminal_commands.py    From cellphonedb with MIT License 6 votes vote down vote up
def check_subsampling_params(ctx: Context, argument: Argument, value) -> Any:
    subsampling = ctx.params.get('subsampling')

    if not subsampling and value is not None:
        tpl = 'This parameter ({}) only applies to subsampling, to enable it add `--subsampling` to your command'
        app_logger.error(tpl.format(argument.name))
        ctx.abort()

    if argument.name == 'subsampling_log' and subsampling and value is None:
        app_logger.error('''In order to perform subsampling you need to specify whether to log1p input counts or not:
            to do this specify in your command as --subsampling-log [true|false]''')
        ctx.abort()

    defaults = {
        'subsampling_num_pc': 100,
        'subsampling_num_cells': None
    }

    if subsampling and value is None:
        return defaults.get(argument.name, None)

    return value 
Example #4
Source File: test.py    From click-default-group with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_default_if_no_args():
    cli = DefaultGroup()

    @cli.command()
    @click.argument('foo', required=False)
    @click.option('--bar')
    def foobar(foo, bar):
        click.echo(foo)
        click.echo(bar)

    cli.set_default_command(foobar)
    assert r.invoke(cli, []).output.startswith('Usage:')
    assert r.invoke(cli, ['foo']).output == 'foo\n\n'
    assert r.invoke(cli, ['foo', '--bar', 'bar']).output == 'foo\nbar\n'
    cli.default_if_no_args = True
    assert r.invoke(cli, []).output == '\n\n' 
Example #5
Source File: __main__.py    From passpy with GNU General Public License v3.0 6 votes vote down vote up
def get_command(self, ctx, cmd_name):
        """Allow aliases for commands.
        """
        if cmd_name == 'list':
            cmd_name = 'ls'
        elif cmd_name == 'search':
            cmd_name = 'find'
        elif cmd_name == 'gen':
            cmd_name = 'generate'
        elif cmd_name == 'add':
            cmd_name = 'insert'
        elif cmd_name in ['remove', 'delete']:
            cmd_name = 'rm'
        elif cmd_name == 'rename':
            cmd_name = 'mv'
        elif cmd_name == 'copy':
            cmd_name = 'cp'

        # TODO(benedikt) Figure out how to make 'show' the default
        # command and pass cmd_name as the first argument.
        rv = click.Group.get_command(self, ctx, cmd_name)
        if rv is not None:
            return rv 
Example #6
Source File: __main__.py    From passpy with GNU General Public License v3.0 6 votes vote down vote up
def init(ctx, gpg_ids, path):
    """Initialize new password storage and use `gpg-id` for encryption.
    Mutliple gpg-ids may be specified, in order to encrypt each
    password with multiple ids.  This command must be run first before
    a password store can be used.  If the specified `gpg-id` is
    different from the ye used in any existing files, these files will
    be reencrypted to use the new id.  Note that use of an gpg agent
    is recommended so that the batch decryption does not require as
    much user intervention.  If `--path` or `-p` is specified, along
    with an argument, a specific gpg-id or a set of gpg-ids is
    assigned for that specific sub folder of the password store.  If
    only the gpg-id is given, and it is an empty string then the
    current `.gpg-id` file for the specfified `sub-folder` (or root if
    unspecified) is removed.

    """
    try:
        ctx.obj.init_store(list(gpg_ids), path=path)
    except PermissionError:
        click.echo(MSG_PERMISSION_ERROR)
        return 1

    click.echo('Password store initialised for {0}.'
               .format(','.join(gpg_ids))) 
Example #7
Source File: test_cli.py    From profiling with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_customized_cli():
    cli = ProfilingCLI(default='bar')
    @cli.command(aliases=['fooo', 'foooo'])
    def foo():
        pass
    @cli.command()
    @click.argument('l', default='answer')
    @click.option('-n', type=int, default=0)
    def bar(l, n=0):
        click.echo('%s: %d' % (l, n))
    assert len(cli.commands) == 2
    ctx = click.Context(cli)
    assert cli.get_command(ctx, 'foo').name == 'foo'
    assert cli.get_command(ctx, 'fooo').name == 'foo'
    assert cli.get_command(ctx, 'foooo').name == 'foo'
    assert cli.get_command(ctx, 'bar').name == 'bar'
    assert cli.get_command(ctx, 'hello.txt').name == 'bar'
    assert 'Usage:' in cli_runner.invoke(cli, []).output
    assert cli_runner.invoke(cli, ['zero']).output == 'zero: 0\n'
    assert cli_runner.invoke(cli, ['one', '-n', '1']).output == 'one: 1\n'
    assert cli_runner.invoke(cli, ['-n', '42']).output == 'answer: 42\n'
    assert 'no such option' in cli_runner.invoke(cli, ['-x']).output 
Example #8
Source File: options.py    From yatsm with MIT License 6 votes vote down vote up
def arg_job_number(f):
    def callback(ctx, param, value):
        try:
            value = int(value)
        except:
            raise click.BadParameter('Must specify an integer >= 0')

        if value < 0:
            raise click.BadParameter('Must specify an integer >= 0')
        elif value == 0:
            return value
        else:
            return value - 1

    return click.argument('job_number', nargs=1, callback=callback,
                          metavar='<job_number>')(f)


# CLI OPTIONS 
Example #9
Source File: options.py    From yatsm with MIT License 6 votes vote down vote up
def arg_date(var='date', metavar='<date>', date_frmt_key='date_frmt'):
    def _arg_date(f):
        def callback(ctx, param, value):
            try:
                value = dt.strptime(value, ctx.params[date_frmt_key])
            except KeyError:
                raise click.ClickException(
                    'Need to use `date_format_opt` when using `date_arg`')
            except ValueError:
                raise click.BadParameter(
                    'Cannot parse {v} to date with format {f}'.format(
                        v=value, f=ctx.params['date_frmt']))
            else:
                return value
        return click.argument(var, metavar=metavar, callback=callback)(f)
    return _arg_date 
Example #10
Source File: __main__.py    From profiling with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def profiler_arguments(f):
    @click.argument('argv', nargs=-1)
    @click.option('-m', 'module', type=Module(),
                  help='Run library module as a script.')
    @click.option('-c', 'command', type=Command(),
                  help='Program passed in as string.')
    @wraps(f)
    def wrapped(argv, module, command, **kwargs):
        if module is not None and command is not None:
            raise click.UsageError('Option -m and -c are exclusive')
        script = module or command
        if script is None:
            # -m and -c not passed.
            try:
                script_filename, argv = argv[0], argv[1:]
            except IndexError:
                raise click.UsageError('Script not specified')
            script = Script().convert(script_filename, None, None)
        kwargs.update(script=script, argv=argv)
        return f(**kwargs)
    return wrapped 
Example #11
Source File: cjio.py    From cjio with MIT License 6 votes vote down vote up
def cli(context, input, ignore_duplicate_keys):
    """Process and manipulate a CityJSON file, and allow
    different outputs. The different operators can be chained
    to perform several processing in one step, the CityJSON model
    goes through the different operators.

    To get help on specific command, eg for 'validate':

    \b
        cjio validate --help

    Usage examples:

    \b
        cjio example.json info validate
        cjio example.json assign_epsg 7145 remove_textures export output.obj
        cjio example.json subset --id house12 save out.json
    """
    context.obj = {"argument": input} 
Example #12
Source File: cfy.py    From cloudify-cli with Apache License 2.0 6 votes vote down vote up
def validate_name(ctx, param, value):
    if value is None or ctx.resilient_parsing:
        return

    if not value:
        raise CloudifyValidationError(
            'ERROR: The `{0}` argument is empty'.format(param.name)
        )

    quoted_value = urlquote(value, safe='')
    if value != quoted_value:
        raise CloudifyValidationError(
            'ERROR: The `{0}` argument contains illegal characters. Only '
            'letters, digits and the characters "-", "." and "_" are '
            'allowed'.format(param.name)
        )

    return value 
Example #13
Source File: policies.py    From python-viptela with GNU General Public License v3.0 6 votes vote down vote up
def central(ctx, name, json):  #pylint: disable=unused-argument
    """
    Show central policy information
    """
    central_policy = CentralPolicy(ctx.auth, ctx.host)
    policy_data = PolicyData(ctx.auth, ctx.host)
    pp = pprint.PrettyPrinter(indent=2)

    if name:
        central_policy_dict = central_policy.get_central_policy_dict()
        if name in central_policy_dict:
            if json:
                pp.pprint(central_policy_dict[name])
            else:
                preview = central_policy.get_central_policy_preview(central_policy_dict[name]['policyId'])
                pp.pprint(preview)
    else:
        central_policy_list = policy_data.export_central_policy_list()
        pp.pprint(central_policy_list) 
Example #14
Source File: cli.py    From ampy with MIT License 6 votes vote down vote up
def ls(directory, long_format, recursive):
    """List contents of a directory on the board.

    Can pass an optional argument which is the path to the directory.  The
    default is to list the contents of the root, /, path.

    For example to list the contents of the root run:

      ampy --port /board/serial/port ls

    Or to list the contents of the /foo/bar directory on the board run:

      ampy --port /board/serial/port ls /foo/bar

    Add the -l or --long_format flag to print the size of files (however note
    MicroPython does not calculate the size of folders and will show 0 bytes):

      ampy --port /board/serial/port ls -l /foo/bar
    """
    # List each file/directory on a separate line.
    board_files = files.Files(_board)
    for f in board_files.ls(directory, long_format=long_format, recursive=recursive):
        print(f) 
Example #15
Source File: cli.py    From ampy with MIT License 6 votes vote down vote up
def mkdir(directory, exists_okay):
    """
    Create a directory on the board.

    Mkdir will create the specified directory on the board.  One argument is
    required, the full path of the directory to create.

    Note that you cannot recursively create a hierarchy of directories with one
    mkdir command, instead you must create each parent directory with separate
    mkdir command calls.

    For example to make a directory under the root called 'code':

      ampy --port /board/serial/port mkdir /code
    """
    # Run the mkdir command.
    board_files = files.Files(_board)
    board_files.mkdir(directory, exists_okay=exists_okay) 
Example #16
Source File: policies.py    From python-viptela with GNU General Public License v3.0 6 votes vote down vote up
def security(ctx, name, json):  #pylint: disable=unused-argument
    """
    Show security policy information
    """
    security_policy = SecurityPolicy(ctx.auth, ctx.host)
    policy_data = PolicyData(ctx.auth, ctx.host)
    pp = pprint.PrettyPrinter(indent=2)

    if name:
        security_policy_dict = security_policy.get_security_policy_dict()
        if name in security_policy_dict:
            if json:
                pp.pprint(security_policy_dict[name])
            else:
                preview = security_policy.get_security_policy_preview(security_policy_dict[name]['policyId'])
                pp.pprint(preview)
    else:
        security_policy_list = policy_data.export_security_policy_list()
        pp.pprint(security_policy_list) 
Example #17
Source File: main.py    From pgcli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def execute_from_file(self, pattern, **_):
        if not pattern:
            message = "\\i: missing required argument"
            return [(None, None, None, message, "", False, True)]
        try:
            with open(os.path.expanduser(pattern), encoding="utf-8") as f:
                query = f.read()
        except IOError as e:
            return [(None, None, None, str(e), "", False, True)]

        if self.destructive_warning and confirm_destructive_query(query) is False:
            message = "Wise choice. Command execution stopped."
            return [(None, None, None, message)]

        on_error_resume = self.on_error == "RESUME"
        return self.pgexecute.run(
            query, self.pgspecial, on_error_resume=on_error_resume
        ) 
Example #18
Source File: rerun.py    From renku-python with Apache License 2.0 6 votes vote down vote up
def edit_inputs(client, workflow):
    """Edit workflow inputs."""
    for input_ in workflow.inputs:
        new_path = click.prompt(
            '{0._id}'.format(input_),
            default=input_.consumes.path,
        )
        input_.consumes.path = str(
            Path(os.path.abspath(new_path)).relative_to(client.path)
        )

    for step in workflow.subprocesses:
        for argument in step.arguments:
            argument.value = click.prompt(
                '{0._id}'.format(argument),
                default=argument.value,
            )

    return workflow 
Example #19
Source File: create_update.py    From packit with MIT License 6 votes vote down vote up
def create_update(
    config, dist_git_branch, koji_build, update_notes, update_type, path_or_url
):
    """
    Create a bodhi update for the selected upstream project

    PATH_OR_URL argument is a local path or a URL to the upstream git repository,
    it defaults to the current working directory
    """
    api = get_packit_api(config=config, local_project=path_or_url)
    branches_to_update = get_branches(*dist_git_branch.split(","), default="master")
    click.echo(f"Syncing from the following branches: {', '.join(branches_to_update)}")

    for branch in branches_to_update:
        api.create_update(
            koji_builds=koji_build,
            dist_git_branch=branch,
            update_notes=update_notes,
            update_type=update_type,
        ) 
Example #20
Source File: ghost.py    From ghost with Apache License 2.0 5 votes vote down vote up
def put_key(key_name,
            value,
            description,
            meta,
            modify,
            add,
            lock,
            key_type,
            stash,
            passphrase,
            backend):
    """Insert a key to the stash

    `KEY_NAME` is the name of the key to insert

    `VALUE` is a key=value argument which can be provided multiple times.
    it is the encrypted value of your key
    """
    stash = _get_stash(backend, stash, passphrase)

    try:
        click.echo('Stashing {0} key...'.format(key_type))
        stash.put(
            name=key_name,
            value=_build_dict_from_key_value(value),
            modify=modify,
            metadata=_build_dict_from_key_value(meta),
            description=description,
            lock=lock,
            key_type=key_type,
            add=add)
        click.echo('Key stashed successfully')
    except GhostError as ex:
        sys.exit(ex) 
Example #21
Source File: leanproject.py    From mathlib-tools with Apache License 2.0 5 votes vote down vote up
def parse_project_name(name: str, ssh: bool = True) -> Tuple[str, str, str]:
    """Parse the name argument for get_project
    Returns (name, url, branch).
    If name is not a full url, the returned url will be a https or ssh
    url depending on the boolean argument ssh.
    """
    # This is split off the actual command function for
    # unit testing purposes
    if ':' in name:
        pieces = name.split(':')
        if len(pieces) >= 3:
            name = ':'.join(pieces[:-1])
            branch = pieces[-1]
        elif 'http' in pieces[0] or '@' in pieces[0]:
            branch = ''
        else:
            name, branch = pieces
    else:
        branch = ''

    if not name.startswith(('git@', 'http')):
        if '/' not in name:
            org_name = 'leanprover-community/'+name
        else:
            org_name, name = name, name.split('/')[1]
        if ssh:
            url = 'git@github.com:'+org_name+'.git'
        else:
            url = 'https://github.com/'+org_name+'.git'
    else:
        url = name
        name = name.split('/')[-1].replace('.git', '')

    return name, url, branch 
Example #22
Source File: leanproject.py    From mathlib-tools with Apache License 2.0 5 votes vote down vote up
def get_project(name: str, new_branch: bool, directory: str = '') -> None:
    """Clone a project from a GitHub name or git url.

    Put it in dir if this argument is given.
    A GitHub name without / will be considered as
    a leanprover-community project.
    If the name ends with ':foo' then foo will be interpreted
    as a branch name, and that branch will be checked out.

    This will fail if the branch does not exist. If you want to create a new
    branch, pass the `-b` option."""

    # check whether we can ssh into GitHub
    try:
        assert PARAMIKO_OK
        client = paramiko.client.SSHClient()
        client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
        client.connect('github.com', username='git')
        client.close()
        ssh = True
    except paramiko.PasswordRequiredException:
        password = getpass('Please provide password for encrypted SSH private key: ')
        client = paramiko.client.SSHClient()
        client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
        client.connect('github.com', username='git', password=password)
        client.close()
        ssh = True
    except (AssertionError, AuthenticationException, SSHException):
        ssh = False

    name, url, branch = parse_project_name(name, ssh)
    if branch:
        name = name + '_' + branch
    directory = directory or name
    if directory and Path(directory).exists():
        raise FileExistsError('Directory ' + directory + ' already exists')
    try:
        LeanProject.from_git_url(url, directory, branch, new_branch,
                                 cache_url, force_download)
    except GitCommandError as err:
        handle_exception(err, 'Git command failed') 
Example #23
Source File: commands.py    From lecli with MIT License 5 votes vote down vote up
def updateteam(command, teamid, userkey):
    """Update a team by adding or deleting a user."""
    if command == 'add_user':
        api.add_user_to_team(teamid, userkey)
    elif command == 'delete_user':
        api.delete_user_from_team(teamid, userkey)
    else:
        click.echo('Missing argument "command".') 
Example #24
Source File: test_click_type.py    From bitmath with MIT License 5 votes vote down vote up
def test_click_BitmathType_good_two_args(self):
        @click.command()
        @click.argument('arg1', type=BitmathType())
        @click.argument('arg2', type=BitmathType())
        def func(arg1, arg2):
            click.echo(arg1)
            click.echo(arg2)

        result = self.runner.invoke(func, ['1337B', '0.001GiB'])
        self.assertFalse(result.exception)
        self.assertEqual(result.output.splitlines(), [str(bitmath.Byte(1337)),
                                                      str(bitmath.GiB(0.001))]) 
Example #25
Source File: grpc_shell.py    From SROS-grpc-services with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def subscribe(ctx, path, delimiter, trigger, interval, suppress_redundant, heartbeat_interval):
    '''
        Fills subscribe RPC with given data.
        First positional argument is path you wish to subscribe to.
    '''
    delimiter = str(delimiter) if delimiter else default_delimiter
    if interval:
        interval = interval*10**9
    ctx.obj['manager'].rpcs[ctx.obj['RPC_TYPE']][ctx.obj['RPC_NAME']].subscription(path=path,
                                                                                   delimiter=delimiter,
                                                                                   trigger=trigger,
                                                                                   interval=interval,
                                                                                   suppress_redundant=suppress_redundant,
                                                                                   heartbeat_interval=heartbeat_interval) 
Example #26
Source File: flasher.py    From pros-cli2 with Mozilla Public License 2.0 5 votes vote down vote up
def lsusb(cfg):
    if len(prosflasher.ports.list_com_ports()) == 0 or prosflasher.ports.list_com_ports() is None:
        click.echo('No serial ports found.')
    else:
        click.echo('Available Ports:')
        click.echo(prosflasher.ports.create_port_list(cfg.verbosity > 0))


# @flasher_cli.command(name='dump-cortex', short_help='Dumps user flash contents to a specified file')
# @click.option('-v', '--verbose', is_flag=True)
# @click.argument('file', default=sys.stdout, type=click.File())
# def dump_cortex(file, verbose):
#     pass 
Example #27
Source File: test_click_type.py    From bitmath with MIT License 5 votes vote down vote up
def test_click_BitmathType_bad_spaces_in_value(self):
        @click.command()
        @click.argument('arg', type=BitmathType())
        def func(arg):
            click.echo(arg)

        result = self.runner.invoke(func, ['1000', 'EB'])
        self.assertTrue(result.exception) 
Example #28
Source File: test_click_type.py    From bitmath with MIT License 5 votes vote down vote up
def test_click_BitmathType_good_spaces_in_value(self):
        @click.command()
        @click.argument('arg1', type=BitmathType())
        @click.argument('arg2', type=BitmathType())
        def func(arg1, arg2):
            click.echo(arg1)
            click.echo(arg2)

        result = self.runner.invoke(func, ['100 MiB', '200 KiB'])
        self.assertFalse(result.exception)
        self.assertEqual(result.output.splitlines(), [str(bitmath.MiB(100)),
                                                      str(bitmath.KiB(200))]) 
Example #29
Source File: test_click_type.py    From bitmath with MIT License 5 votes vote down vote up
def test_click_BitmathType_bad_wtfareyoudoing(self):
        @click.command()
        @click.argument('arg', type=BitmathType())
        def func(arg):
            click.echo(arg)

        result = self.runner.invoke(func, ['2098329324kdsjflksdjf'])
        self.assertTrue(result.exception) 
Example #30
Source File: commands.py    From poker with MIT License 5 votes vote down vote up
def range_(range, no_border, html):
    """Prints the given range in a formatted table either in a plain ASCII or HTML.
    The only required argument is the range definition, e.g. "A2s+ A5o+ 55+"
    """
    from .hand import Range

    border = not no_border
    result = Range(range).to_html() if html else Range(range).to_ascii(border)
    click.echo(result)