Python click 模块,argument() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用click.argument()

项目:flora    作者:Lamden    | 项目源码 | 文件源码
def list(package_name):
    # lists all of the packages for a user, or all of the implementations for a package

    # <username> / <package> , <implementation>

    # detemine if there's a user and package, or just a user
    p = split_package_name(package_name)
    if p['username'] != None:
        # get all of the packages and print their names in a pretty print
        if p['package'] != None:
            # get all implementations and print their names in a pretty print
            if p['implementation'] != None:
                print('Cannot list one specific implementation. Use "print".')
                return
            return
        return

    print('Error parsing arguments. Got {}. Specify in format such that: <username>/<package> with <package> being optional.'.format(p))

# @cli.command()
# @click.argument('payload')
# def print(payload):

#   pass
项目:manage    作者:rochacbruno    | 项目源码 | 文件源码
def handle_options_and_args(_command, arguments, options):

    for argument in arguments:
        if isinstance(argument, dict):
            _command = click.argument(
                list(argument.keys())[0],
                **handle_option_and_arg_data(list(argument.values())[0])
            )(_command)
        else:
            _command = click.argument(argument)(_command)

    if isinstance(options, dict):
        for name, data in options.items():
            data = handle_option_and_arg_data(data)
            _command = click.option(name, **data)(_command)
    else:
        for name in options:
            _command = click.option(name)(_command)
    return _command
项目:freckles    作者:makkus    | 项目源码 | 文件源码
def list_modules():

    module_list = []
    get_all_modules('ansible.modules', module_list)
    return module_list

# @cli.command('get-module')
# @click.argument('module_name', nargs=1)
# @click.pass_context
# def get_module(ctx, module_name):

#     matches = [x for x in list_modules() if x.endswith(module_name)]

#     for m in matches:

#         path, name = m.rsplit('.',1)

#         module_info = read_module(m)

#         pprint.pprint(module_info["doc"]["options"])

#         # info_all = read_package(path)
#         # module_info = info_all[0][name]
#         # yaml_text = yaml.dump(module_info["doc"]["options"], default_flow_style=False)
#         # print yaml_text
项目:iocage    作者:iocage    | 项目源码 | 文件源码
def cli(rc, jails):
    """
    Looks for the jail supplied and passes the uuid, path and configuration
    location to stop_jail.
    """
    if not jails and not rc:
        ioc_common.logit({
            "level"  : "EXCEPTION",
            "message": 'Usage: iocage stop [OPTIONS] JAILS...\n'
                       '\nError: Missing argument "jails".'
        }, exit_on_error=True)

    if rc:
        ioc.IOCage(exit_on_error=True, rc=rc, silent=True).stop()
    else:
        for jail in jails:
            ioc.IOCage(exit_on_error=True, jail=jail, rc=rc).stop()
项目:iocage    作者:iocage    | 项目源码 | 文件源码
def cli(rc, jails):
    """
    Looks for the jail supplied and passes the uuid, path and configuration
    location to start_jail.
    """
    if not jails and not rc:
        ioc_common.logit({
            "level"  : "EXCEPTION",
            "message": 'Usage: iocage start [OPTIONS] JAILS...\n'
                       '\nError: Missing argument "jails".'
        }, exit_on_error=True)

    if rc:
        ioc.IOCage(exit_on_error=True, rc=rc, silent=True).start()
    else:
        for jail in jails:
            ioc.IOCage(exit_on_error=True, jail=jail, rc=rc).start()
项目:csvtotable    作者:vividvilla    | 项目源码 | 文件源码
def cli(*args, **kwargs):
    """
    CSVtoTable commandline utility.
    """
    # Convert CSV file
    content = convert.convert(kwargs["input_file"], **kwargs)

    # Serve the temporary file in browser.
    if kwargs["serve"]:
        convert.serve(content)
    # Write to output file
    elif kwargs["output_file"]:
        # Check if file can be overwrite
        if (not kwargs["overwrite"] and
                not prompt_overwrite(kwargs["output_file"])):
            raise click.Abort()

        convert.save(kwargs["output_file"], content)
        click.secho("File converted successfully: {}".format(
            kwargs["output_file"]), fg="green")
    else:
        # If its not server and output file is missing then raise error
        raise click.BadOptionUsage("Missing argument \"output_file\".")
项目:kubernetes-starterkit    作者:mdgriffith    | 项目源码 | 文件源码
def logs(config):
    pod = subprocess.check_output('kubectl get pods -l "app=api" -o name', shell=True)
    if pod == "":
        print "There is no pod running in this environment.  You may need to deploy first."
        exit(1)
    pod_name = pod.split("/")[1].strip()
    subprocess.call("kubectl logs {pod} --container flask --follow".format(pod=pod_name), shell=True)

# @click.command()
# @click.argument("config", type=StarterkitConfig(r'kube/deployments/'))
# def request_certs():
#     # Request certs
#     subprocess.call("kubectl exec ")
#     # Get status of Certs
#     subprocess.call("kubectl")
#     # If
#     pass
项目:globus-cli    作者:globus    | 项目源码 | 文件源码
def task_id_arg(*args, **kwargs):
    """
    This is the `TASK_ID` argument consumed by many Transfer Task operations.
    It accept a toggle on whether or not it is required

    Usage:

    >>> @task_id_option
    >>> def command_func(task_id):
    >>>     ...

    or

    >>> @task_id_option(required=False)
    >>> def command_func(task_id):
    >>>     ...

    By default, the task ID is made required; pass `required=False` to the
    decorator arguments to make it optional.
    """
    def inner_decorator(f, required=True):
        f = click.argument('TASK_ID', required=required)(f)
        return f
    return detect_and_decorate(inner_decorator, args, kwargs)
项目:millilauncher    作者:fhfuih    | 项目源码 | 文件源码
def launch(version, raw):
    """
    Launch Minecraft of the given version
    """
    launcher = LauncherCore(config.mc_dir, config.java_dir)
    if raw:
        click.echo(launcher.launch_raw(version, config.username, config.max_mem))
    else:
        launcher.launch(version, config.username, config.max_mem)

# @main.command('download')
# @click.argument('version')
# @click.option('-c', '--client', is_flag=True)
# @click.option('-a', '--assets', is_flag=True)
# @click.option('-l', '--libraries', is_flag=True)
# @click.option('-F', '--forge', is_flag=True)
# @click.option('-L', '--liteloader', is_flag=True)
# @click.option('-E', '--external', is_flag=True, default=False, help='Open the download link externally.\
#     Useful when you want to download files in another manner. Default is False')
# def _download(version, **components):
#     """
#     Download Minecraft, components or mods
#     """
#     pass
项目:millilauncher    作者:fhfuih    | 项目源码 | 文件源码
def config_(action, **kw):
    """
    Configure your launcher and game preferences.
    The 'action' argument is optional, and can be 'reset' or 'wizard'. 
    If it's left blank, only given options will be set.
    Else, given options will be set AFTER the corresponding action is executed.
    """
    if action == 'reset':
        ok = click.prompt('Are you sure you want to reset you settings?', confirmation_prompt=True)
        if ok:
            config.reset()
    elif action == 'wizard':
        _wizard()

    for k, v in kw.items():
        if v is None:
            break
        if isinstance(v, str) and v[0] == '=':
            v = v[1:]
        config[k.replace('-', '_')] = v
    config.save()
项目:millilauncher    作者:fhfuih    | 项目源码 | 文件源码
def list_(src, min, max):
    """
    List Minecraft versions in a range(if given).
    The 'src' argument can be 'local'(default) or 'remote'.
    The former will check valid Minecraft versions on your computer.
    The latter will get a list of valid versions released by Mojang.
    """
    if src == 'local':
        launcher = LauncherCore(config.mc_dir, config.java_dir)
        vlist = launcher.versions.list
        try:
            begin = vlist.index(min)
        except ValueError:
            begin = 0
        try:
            end = vlist.index(max) + 1
        except ValueError:
            end = len(vlist)
        click.echo('\n'.join(vlist[begin:end]))
    else:
        pass
项目:crc-diagram    作者:IuryAlves    | 项目源码 | 文件源码
def main(source, out, raw, format, view):
    """
    Generate CRCDiagrams from SOURCE saving they as OUT.
    \n
    The default output format is png.
    \n
    Example:\n
    crc-diagram source_file.py output.png
    """
    if os.path.isdir(source):
        crc_cards = crc_diagram.folder_to_crc(source)
    else:
        crc_cards = crc_diagram.to_crc(source)

    if raw:
        out = path_to_stream(out or sys.stdout, 'w')
        json.dump([crc.to_dict() for crc in crc_cards], out, indent=4)
    else:
        if out is None:
            raise click.UsageError('Missing argument "out".')
        DotRender(crc_cards, format=format).render(out, view=view)
项目:textkit    作者:learntextvis    | 项目源码 | 文件源码
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))
项目:EasyEuler    作者:Encrylize    | 项目源码 | 文件源码
def cli(problem, path):
    """
    Generate the resource files for problems.

    These resources are either images - serving as helpful illustrations -
    or text files containing specific data - referenced in the problem.

    If the PROBLEM argument isn't specified, all resources will be
    generated.

    """

    if problem is None:
        resources = os.listdir('%s/resources' % paths.DATA)
    else:
        if 'resources' not in problem:
            sys.exit('Problem %s has no resource files' % problem['id'])
        resources = problem['resources']

    generate_resources(resources, path)
项目:configmanager    作者:jbasko    | 项目源码 | 文件源码
def argument(self, *args, **kwargs):
        """
        Registers a click.argument which falls back to a configmanager Item
        if user hasn't provided a value in the command line.

        Item must be the last of ``args``.
        """

        if kwargs.get('required', True):
            raise TypeError(
                'In click framework, arguments are mandatory, unless marked required=False. '
                'Attempt to use configmanager as a fallback provider suggests that this is an optional option, '
                'not a mandatory argument.'
            )

        args, kwargs = _config_parameter(args, kwargs)
        return self._click.argument(*args, **kwargs)
项目:munch-core    作者:crunchmail    | 项目源码 | 文件源码
def make_django_command(name, django_command=None, help=None):
    "A wrapper to convert a Django subcommand a Click command"
    if django_command is None:
        django_command = name

    @click.command(
        name=name,
        help=help,
        add_help_option=False,
        context_settings=dict(
            ignore_unknown_options=True,
        ))
    @click.argument('management_args', nargs=-1, type=click.UNPROCESSED)
    @click.pass_context
    def inner(ctx, management_args):
        from munch.runner.commands.django import django
        ctx.params['management_args'] = (django_command,) + management_args
        ctx.forward(django)

    return inner
项目:passpy    作者:bfrascher    | 项目源码 | 文件源码
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
项目:passpy    作者:bfrascher    | 项目源码 | 文件源码
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)))
项目:feeds    作者:nblock    | 项目源码 | 文件源码
def crawl(ctx, spiders, stats):
    """
    Crawl one or many or all pages.

    What spider(s) to run is determined in the following order:

      1. Spider(s) given as argument(s)

      2. Spider(s) specified in the configuration file

    Note that if a spider is given as an argument, the spiders in the
    configuration file are ignored. All available spiders will be used to
    crawl if no arguments are given and no spiders are configured.
    """
    settings = ctx.obj['settings']
    if stats:
        settings.set('STATS_CLASS',
                     'scrapy.statscollectors.MemoryStatsCollector')

    # Start a new crawler process.
    process = CrawlerProcess(settings)
    spiders = spiders_to_crawl(process, spiders)
    if not spiders:
        logger.error('Please specify what spiders you want to run!')
    else:
        for spider in spiders:
            logger.info('Starting crawl of {} ...'.format(spider))
            process.crawl(spider)

    process.start()

    if settings.getbool('HTTPCACHE_ENABLED'):
        run_cleanup_cache(settings)
项目:histonets-cv    作者:sul-cidr    | 项目源码 | 文件源码
def test_pair_options_to_argument_args(self):
        args = ['im', 't1', '-o', '1', 't2', 't3', '-o', '3']

        @click.command()
        @click.argument('img')
        @click.argument('arg', nargs=-1, required=True)
        @click.option('-o', '--option', multiple=True)
        @utils.pair_options_to_argument(
            'arg', {'option': 0}, args=args, args_slice=(1, None)
        )
        def command(img, arg, option):
            click.echo(json.dumps((arg, option)))

        runner = CliRunner()
        output = runner.invoke(command, args).output
        assert 'Error' not in output
        assert [["t1", "t2", "t3"], ["1", 0, "3"]] == json.loads(output)
项目:histonets-cv    作者:sul-cidr    | 项目源码 | 文件源码
def test_two_paired_options_to_argument_args(self):
        args = ['im', 't1', '-o', '1', 't2', '-a', '3', 't3']

        @click.command()
        @click.argument('img')
        @click.argument('arg', nargs=-1, required=True)
        @click.option('-o', '--option', multiple=True)
        @click.option('-a', '--another', multiple=True)
        @utils.pair_options_to_argument(
            'arg', {'option': 0, 'another': 1}, args=args, args_slice=(1, None)
        )
        def command(img, arg, option, another):
            click.echo(json.dumps((arg, option, another)))

        runner = CliRunner()
        output = runner.invoke(command, args).output
        assert 'Error' not in output
        assert ([["t1", "t2", "t3"], ["1", 0, 0], [1, "3", 1]]
                == json.loads(output))
项目:histonets-cv    作者:sul-cidr    | 项目源码 | 文件源码
def test_pair_options_to_argument_args_default(self):
        args = ['im', 't1', 't2', 't3']

        @click.command()
        @click.argument('img')
        @click.argument('arg', nargs=-1, required=True)
        @click.option('-o', '--option', multiple=True)
        @utils.pair_options_to_argument(
            'arg', {'option': 0}, args=args, args_slice=(1, None)
        )
        def command(img, arg, option):
            click.echo(json.dumps((arg, option)))

        runner = CliRunner()
        output = runner.invoke(command, args).output
        assert 'Error' not in output
        assert [["t1", "t2", "t3"], [0, 0, 0]] == json.loads(output)
项目:histonets-cv    作者:sul-cidr    | 项目源码 | 文件源码
def test_pair_options_to_argument(self):
        code = """
import json
import click
from histonets import utils
@click.group()
def main():
    pass
@main.command()
@click.argument('img')
@click.argument('arg', nargs=-1, required=True)
@click.option('-o', '--option', multiple=True)
@utils.pair_options_to_argument('arg', {'option': 0}, args_slice=(2, None))
def command(img, arg, option):
    click.echo(json.dumps((arg, option)))
main()
        """
        cmd = ("echo \"{}\" "
               "| python - command im t1 -o 1 t2 t3 -o 3".format(code))
        ps = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE,
                              stderr=subprocess.STDOUT)
        output = ps.communicate()[0].decode()
        assert 'Error' not in output
        assert [["t1", "t2", "t3"], ["1", 0, "3"]] == json.loads(output)
项目:serplint    作者:beaugunderson    | 项目源码 | 文件源码
def add_to_scope(self, method_name, token, variable_type):
        name = self.resolve_name(token, method_name)

        if self.get_scope(method_name, name):
            if self.get_scope(method_name, name)['type'] == 'argument':
                self.log_message(
                    token.metadata.ln,
                    token.metadata.ch,
                    ASSIGNED_TO_ARGUMENT,
                    'Assigned a value to an argument "{}"'.format(name))

        self.scope[method_name][name] = {
            'type': variable_type,
            'accessed': False,
            'token': token,
        }
项目:koi    作者:openpermissions    | 项目源码 | 文件源码
def __init__(self, main, conf_dir=None, commands_dir=None, **kwargs):
        self._commands_dir = commands_dir
        if conf_dir:
            configure.load_config_file(conf_dir)

        # This is a bit of a hack, but need to register all parameters from
        # the command line because want to allow tornado to handle them and
        # click doesn't contain an equivalent of the `allow_extra_args`
        # keyword argument that works for options.
        # TODO: don't use tornado command line parsing
        params = _options()

        super(Command, self).__init__(self,
                                      params=params,
                                      callback=run(main),
                                      invoke_without_command=True,
                                      **kwargs)
项目:treadmill    作者:Morgan-Stanley    | 项目源码 | 文件源码
def init():
    """Return top level command handler."""

    @click.command()
    @click.option('--api', required=False, help='API url to use.',
                  envvar='TREADMILL_RESTAPI')
    @click.option('-m', '--manifest', help='App manifest file (stream)',
                  type=click.Path(exists=True, readable=True))
    @click.option('--delete', help='Delete the app.',
                  is_flag=True, default=False)
    @click.argument('appname', required=False)
    @cli.handle_exceptions(restclient.CLI_REST_EXCEPTIONS)
    def configure(api, manifest, delete, appname):
        """Configure a Treadmill app"""
        restapi = context.GLOBAL.admin_api(api)
        if appname:
            if delete:
                return _delete(restapi, appname)
            return _configure(restapi, manifest, appname)
        else:
            return _list(restapi)

    return configure
项目:treadmill    作者:Morgan-Stanley    | 项目源码 | 文件源码
def init():
    """Return top level command handler."""

    @click.command()
    @click.argument('inputfile', type=click.Path(exists=True))
    @click.argument('params', nargs=-1,
                    type=click.Path(exists=True, readable=True))
    def interpolate(inputfile, params):
        """Interpolate input file template."""
        env = jinja2.Environment(
            loader=jinja2.FileSystemLoader(os.path.dirname(inputfile)),
            keep_trailing_newline=True
        )

        data = {}
        for param in params:
            with io.open(param, 'rb') as fd:
                data.update(yaml.load(stream=fd))

        cli.out(env.get_template(os.path.basename(inputfile)).render(data))

    return interpolate
项目:treadmill    作者:Morgan-Stanley    | 项目源码 | 文件源码
def init():
    """Top level command handler."""

    @click.command()
    @click.option('--approot', type=click.Path(exists=True),
                  envvar='TREADMILL_APPROOT', required=True)
    @click.option('--runtime', envvar='TREADMILL_RUNTIME', required=True)
    @click.argument('eventfile', type=click.Path(exists=True))
    def configure(approot, runtime, eventfile):
        """Configure local manifest and schedule app to run."""
        tm_env = appenv.AppEnvironment(root=approot)

        container_dir = app_cfg.configure(tm_env, eventfile, runtime)
        _LOGGER.info('Configured %r', container_dir)

    return configure
项目:SuperOcto    作者:mcecchi    | 项目源码 | 文件源码
def plugin_uninstall(self):
        @click.command("uninstall")
        @click.argument("name")
        def command(name):
            """Uninstalls the plugin with the given name."""
            import sys

            lower_name = name.lower()
            if not lower_name.startswith("octoprint_") and not lower_name.startswith("octoprint-"):
                click.echo("This doesn't look like an OctoPrint plugin name")
                sys.exit(1)

            call = [sys.executable, "-m", "pip", "uninstall", "--yes", name]
            self.command_caller.call(call)

        return command
项目:cookiecutter-django    作者:toxinu    | 项目源码 | 文件源码
def make_django_command(name, django_command=None, help=None):
    "A wrapper to convert a Django subcommand a Click command"
    if django_command is None:
        django_command = name

    @click.command(
        name=name,
        help=help,
        add_help_option=False,
        context_settings=dict(
            ignore_unknown_options=True,
        ))
    @click.argument('management_args', nargs=-1, type=click.UNPROCESSED)
    @click.pass_context
    def inner(ctx, management_args):
        from {{ cookiecutter.module_name }}.runner.commands.django import django
        ctx.params['management_args'] = (django_command,) + management_args
        ctx.forward(django)

    return inner
项目:ampy    作者:adafruit    | 项目源码 | 文件源码
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)
项目:ampy    作者:adafruit    | 项目源码 | 文件源码
def ls(directory):
    """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
    """
    # List each file/directory on a separate line.
    board_files = files.Files(_board)
    for f in board_files.ls(directory):
        print(f)
项目:datapackage-pipelines    作者:frictionlessdata    | 项目源码 | 文件源码
def execute_if_needed(argument, spec, use_cache):
    ps = status.get(spec.pipeline_id)
    if (match_pipeline_id(argument, spec.pipeline_id) or
            (argument == 'all') or
            (argument == 'dirty' and ps.dirty())):
        if len(spec.validation_errors) != 0:
            return (spec.pipeline_id, False, {}, ['init'] + list(map(str, spec.validation_errors))), \
                   spec.pipeline_id == argument
        eid = gen_execution_id()
        if ps.queue_execution(eid, 'manual'):
            success, stats, errors = \
                execute_pipeline(spec, eid,
                                 use_cache=use_cache)
            return (spec.pipeline_id, success, stats, errors), spec.pipeline_id == argument
        else:
            return (spec.pipeline_id, False, None, ['Already Running']), spec.pipeline_id == argument
    return None, False
项目:aiohttp-devtools    作者:aio-libs    | 项目源码 | 文件源码
def runserver(**config):
    """
    Run a development server for an aiohttp apps.

    Takes one argument "app-path" which should be a path to either a directory containing a recognized default file
    ("app.py" or "main.py") or to a specific file. Defaults to the environment variable "AIO_APP_PATH" or ".".

    The app path is run directly, see the "--app-factory" option for details on how an app is loaded from a python
    module.
    """
    active_config = {k: v for k, v in config.items() if v is not None}
    setup_logging(config['verbose'])
    try:
        run_app(*_runserver(**active_config))
    except AiohttpDevException as e:
        if config['verbose']:
            tb = click.style(traceback.format_exc().strip('\n'), fg='white', dim=True)
            main_logger.warning('AiohttpDevException traceback:\n%s', tb)
        main_logger.error('Error: %s', e)
        sys.exit(2)
项目:jenskipper    作者:Stupeflix    | 项目源码 | 文件源码
def handle_jinja_errors(func):
    '''
    Print nice error messages on jinja exceptions.

    Expect a *base_dir* argument, so normally used after ``@repos_command``.
    '''

    @functools.wraps(func)
    def wrapper(base_dir, **kwargs):
        try:
            return func(base_dir=base_dir, **kwargs)
        except jinja2.TemplateNotFound as exc:
            click.secho('Template not found: %s' % exc.name, fg='red',
                        bold=True)
        except jinja2.TemplateError:
            exc_info = sys.exc_info()
            stack, error = templates.extract_jinja_error(exc_info, base_dir)
            templates.print_jinja_error(stack, error)
        sys.exit(1)

    return wrapper
项目:qypi    作者:jwodder    | 项目源码 | 文件源码
def package_args(versioned=True):
    if versioned:
        def wrapper(f):
            return all_opt(sort_opt(pre_opt(click.argument(
                'packages',
                nargs=-1,
                callback=lambda ctx, param, value:
                            ctx.obj.lookup_package_version(value),
            )(f))))
        return wrapper
    else:
        return click.argument(
            'packages',
            nargs=-1,
            callback=lambda ctx, param, value: ctx.obj.lookup_package(value),
        )
项目:Sentry    作者:NetEaseGame    | 项目源码 | 文件源码
def make_django_command(name, django_command=None, help=None):
    "A wrapper to convert a Django subcommand a Click command"
    if django_command is None:
        django_command = name

    @click.command(
        name=name,
        help=help,
        add_help_option=False,
        context_settings=dict(
            ignore_unknown_options=True,
        ))
    @click.argument('management_args', nargs=-1, type=click.UNPROCESSED)
    @click.pass_context
    def inner(ctx, management_args):
        from sentry.runner.commands.django import django
        ctx.params['management_args'] = (django_command,) + management_args
        ctx.forward(django)

    return inner
项目:stream2segment    作者:rizac    | 项目源码 | 文件源码
def set_help_from_yaml(cls, ctx, param, value):
        """
        When attaching this function as `callback` argument to an Option (`click.Option`),
        it will set
        an automatic help for all Options of the same command, which do not have an `help`
        specified and are found in the default config file for downloading
        (currently `download.yaml`).
        The Option having as callback this function must also have `is_eager=True`.
        Example:
        Assuming opt1, opt2, opt3 are variables of the config yaml file, and opt4 not, this
        sets the default help for opt1 and opt2:
\@click.Option('--opt1', ..., callback=set_help_from_yaml, is_eager=True,...)
    \@click.Option('--opt2'...)
    \@click.Option('--opt3'..., help='my custom help do not set the config help')
    \@click.Option('--opt4'...)
    ...
    ```
    """
    cfg_doc = cls.DEFAULTDOC
    for option in (opt for opt in ctx.command.params if opt.param_type_name == 'option'):
        if option.help is None:
            option.help = cfg_doc.get(option.name, None)

    return value

```

项目:stream2segment    作者:rizac    | 项目源码 | 文件源码
def download(configfile, dburl, eventws, start, end, dataws, min_sample_rate, traveltimes_model,
             timespan, update_metadata, retry_url_err, retry_mseed_err, retry_seg_not_found,
             retry_client_err, retry_server_err, retry_timespan_err, inventory, eventws_query_args):
    """Download waveform data segments with quality metadata and relative events, stations and
    channels metadata into a specified database.
    The -c option (required) sets the defaults for all other options below, which are optional.
    The argument 'eventws_query_args' is an optional list of space separated key and values to be
    passed to the event web service query (example: minmag 5.5 minlon 34.5). All FDSN query
    arguments are valid except 'start', 'end' (set them via -t0 and -t1) and 'format'
    """
    try:
        cfg_dict = yaml_load(configfile, **{k: v for k, v in locals().items()
                                            if v not in ((), {}, None, configfile)})
        # start and end might be integers. If we attach the conversion function
        # `clickutils.valid_date` to the relative clikc Option 'type' argument, the
        # function does not affect integer values in the config. Thus we need to set it here:
        cfg_dict['start'] = clickutils.valid_date(cfg_dict['start'])
        cfg_dict['end'] = clickutils.valid_date(cfg_dict['end'])
        ret = main.download(isterminal=True, **cfg_dict)
        sys.exit(ret)
    except KeyboardInterrupt:  # this except avoids printing traceback
        sys.exit(1)  # exit with 1 as normal python exceptions
项目:ghutil    作者:jwodder    | 项目源码 | 文件源码
def argument_list(cls, name):
        """
        A `click.argument` decorator that accepts zero or more command-line
        arguments and converts them all to instances of the class.  If
        `default_params` is not `None`, an empty argument list will be
        defaulted to the resource type's default value.
        """
        if cls.default_params is not None:
            def callback(ctx, param, value):
                return value or [cls.default(ctx.obj)]
        else:
            callback = None
        return click.argument(
            name,
            type=ResourceParamType(cls),
            nargs=-1,
            callback=callback,
        )
项目:apimas    作者:grnet    | 项目源码 | 文件源码
def construct_action(self, instance, spec, loc, context, action):
        """
        Construct a command based on a specific actions, e.g. list,
        create, etc.
        """
        assert len(loc) == 4
        self.init_adapter_conf(instance)
        collection = loc[0] + '/' + loc[-3]
        command = self.COMMANDS[action](self.clients.get(collection))
        if action in self.RESOURCE_ACTIONS:
            command = click.argument('resource_id')(command)
        if action in self.CRITICAL_ACTIONS:
            option = click.option(
                '--yes', is_flag=True, callback=abort_if_false,
                expose_value=False,
                prompt='Are you sure you want to perform this action?')
            command = option(command)
        self._add_format_option(command, action)
        instance[self.ADAPTER_CONF][action] = command
        return instance
项目:rust_pypi_example    作者:mckaymatt    | 项目源码 | 文件源码
def main(number=None):
    """Console script for rust_pypi_example
       The console script takes a singe argument, "NUMBER",
       which must be an integer greater than 2. The script calls
       out to a library written in Rust to compute whether the
       intger is a prime number.
       Example:
           rust_pypi_example 13
    """
    if number and number > 2:
        click.echo(True if rust_lib.is_prime(number) else False)
    else:
        click.echo("Please supply an integer argument greater than 2. The "
                   "console script will tell you if it is a prime number")
项目:polyaxon-cli    作者:polyaxon    | 项目源码 | 文件源码
def update(project, name, description):
    """Update project.

    Example:
polyaxon update foobar --description=Image Classification with Deep Learning using TensorFlow
```

```
polyaxon update mike1/foobar --description=Image Classification with Deep Learning using TensorFlow
```
"""
user, project_name = get_project_or_local(project)

update_dict = {}
if name:
    update_dict['name'] = name

if description:
    update_dict['description'] = description

if not update_dict:
    Printer.print_warning('No argument was provided to update the project.')
    sys.exit(1)

try:
    response = PolyaxonClients().project.update_project(user, project_name, update_dict)
except (PolyaxonHTTPError, PolyaxonShouldExitError) as e:
    Printer.print_error('Could not update project `{}`.'.format(project))
    Printer.print_error('Error message `{}`.'.format(e))
    sys.exit(1)

Printer.print_success("Project updated.")
response = response.to_light_dict()
Printer.print_header("Project info:")
dict_tabulate(response)

```

项目:polyaxon-cli    作者:polyaxon    | 项目源码 | 文件源码
def update(group, project, description):
    """Update experiement group.

    Example:
polyaxon group update 2 --description="new description for my experiments"
```
"""
user, project_name = get_project_or_local(project)
update_dict = {}

if description:
    update_dict['description'] = description

if not update_dict:
    Printer.print_warning('No argument was provided to update the experiment group.')
    sys.exit(0)

try:
    response = PolyaxonClients().experiment_group.update_experiment_group(
        user, project_name, group, update_dict)
except (PolyaxonHTTPError, PolyaxonShouldExitError) as e:
    Printer.print_error('Could not update experiment group `{}`.'.format(group))
    Printer.print_error('Error message `{}`.'.format(e))
    sys.exit(1)

Printer.print_success("Experiment group updated.")
response = response.to_light_dict()
Printer.print_header("Experiment group info:")
dict_tabulate(response)

```

项目:Travis-Encrypt    作者:mandeep    | 项目源码 | 文件源码
def cli(username, repository, path, password, deploy, env):
    """Encrypt passwords and environment variables for use with Travis CI.

    Travis Encrypt requires as arguments the user's GitHub username and repository name.
    Once the arguments are passed, a password prompt will ask for the password that needs
    to be encrypted. The given password will then be encrypted via the PKCS1v15 padding
    scheme and printed to standard output. If the path to a .travis.yml file
    is given as an argument, the encrypted password is added to the .travis.yml file.
    """
    key = retrieve_public_key('{}/{}' .format(username, repository))
    encrypted_password = encrypt_key(key, password.encode())

    if path:
        config = load_travis_configuration(path)

        if deploy:
            config.setdefault('deploy', {}).setdefault('password', {})['secure'] = encrypted_password

        elif env:
            config.setdefault('env', {}).setdefault('global', {})['secure'] = encrypted_password

        else:
            config.setdefault('password', {})['secure'] = encrypted_password

        dump_travis_configuration(config, path)

        print('Encrypted password added to {}' .format(path))

    else:
        print('\nPlease add the following to your .travis.yml:\nsecure: {}' .format(encrypted_password))
项目:lecli    作者:rapid7    | 项目源码 | 文件源码
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".')
项目:DataFS    作者:ClimateImpactLab    | 项目源码 | 文件源码
def _parse_args_and_kwargs(passed_args):

    args = []
    kwargs = {}

    has_kwargs = False

    while len(passed_args) > 0:

        arg = passed_args.pop(0)

        if arg[:2] == '--':
            has_kwargs = True

            if not len(passed_args) > 0:
                raise ValueError('Argument "{}" not recognized'.format(arg))

            kwargs[arg[2:]] = passed_args.pop(0)

        else:
            if has_kwargs:
                raise ValueError(
                    'Positional argument "{}" after keyword arguments'.format(
                        arg))

            args.append(arg)

    return args, kwargs
项目:pyUBoot    作者:molejar    | 项目源码 | 文件源码
def convert(self, value, param, ctx):
        try:
            if isinstance(value, (int,)):
                return value
            else:
                return int(value, 0)
        except:
            self.fail('%s is not a valid value' % value, param, ctx)


# Create instances of custom argument types
项目:pyUBoot    作者:molejar    | 项目源码 | 文件源码
def convert(self, value, param, ctx):
        try:
            if isinstance(value, (int,)):
                return value
            else:
                return int(value, 0)
        except:
            self.fail('%s is not a valid value' % value, param, ctx)


# Create instances of custom argument types
项目:no-YOU-talk-to-the-hand    作者:flashashen    | 项目源码 | 文件源码
def list():
    for name, config in get_config()['tunnels'].items():
        print name
        # print {'name':name,
        #     'proxy': config['proxy']['host'] if 'proxy' in config and 'host' in config['proxy'] else '',
        #     'check': config['check'] if 'check' in config else '',
        #     'depends':config['depends'] if 'depends' in config else ''}


# @cli.command()
# @click.argument('tunnel')
# def up(tunnel):
#     try:
#         if not supervisor_is_running():
#             start()
#
#         get_supervisor().startProcess(tunnel)
#     except:
#         traceback.print_exc()


# @cli.command('down')
# @click.argument('tunnel')
# def down(tunnel):
#     if not supervisor_is_running():
#         print('supervisor is not running')
#
#     get_config(None)
#     write_supervisor_conf()
#
#     get_supervisor().stopProcess(tunnel)
#     # continue stopping recursively
#     stop_dependent_tunnels(tunnel)
#
#     # get_supervisor().stopProcess(tunnel)