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

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

项目:okta-awscli    作者:jmhale    | 项目源码 | 文件源码
def main(okta_profile, profile, verbose, force, awscli_args):
    """ Authenticate to awscli using Okta """
    if not okta_profile:
        okta_profile = "default"
    aws_auth = AwsAuth(profile, verbose)
    if not aws_auth.check_sts_token(profile) or force:
        if verbose and force and profile:
            click.echo("Force option selected, getting new credentials anyway.")
        elif verbose and force:
            click.echo("Force option selected, but no profile provided. Option has no effect.")
        get_credentials(aws_auth, okta_profile, profile, verbose)

    if awscli_args:
        cmdline = ['aws', '--profile', profile] + list(awscli_args)
        if verbose:
            click.echo('Invoking: %s' % ' '.join(cmdline))
        call(cmdline)
项目:findcve    作者:garethr    | 项目源码 | 文件源码
def load_vulnerability_database():
    # Currently manually downloaded from
    # https://security-tracker.debian.org/tracker/data/json
    # Should instead download if not found in option localtion
    # or redownload if found but out of date
    # progress bar for download

    url = "https://security-tracker.debian.org/tracker/data/json"
    db = Path('debian.json')
    r = requests.get(url, stream=True)
    if not db.exists():
        with open(db.name, 'wb') as data_file:
            total_length = 1024*20722
            for chunk in progress.bar(r.iter_content(chunk_size=1024), label="Downloading Debian data", expected_size=(total_length/1024) + 1): 
                if chunk:
                    data_file.write(chunk)
                    data_file.flush()
    with open(db.name, 'r') as data_file:
        return json.load(data_file)
项目: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
项目:linchpin    作者:CentOS-PaaS-SIG    | 项目源码 | 文件源码
def init(ctx):
    """
    Initializes a linchpin project, which generates an example PinFile, and
    creates the necessary directory structure for topologies and layouts.

    ctx: Context object defined by the click.make_pass_decorator method
    """

    pf_w_path = _get_pinfile_path(exists=False)

    try:
        # lpcli.lp_init(pf_w_path, targets) # TODO implement targets option
        lpcli.lp_init(pf_w_path)
    except LinchpinError as e:
        ctx.log_state(e)
        sys.exit(1)
项目:saffron    作者:Lamden    | 项目源码 | 文件源码
def new(option, name):
    assert option != None and option in ['account', 'contract'], 'Provide either "account" or "contract" after "new"'
    if option == 'account':
        print('Generating new account.')

        project_dir = ''
        run_location, filename = os.path.split(os.path.abspath(__file__))
        config = configparser.ConfigParser()
        config.read(os.path.join(run_location, 'config/default.conf'))
        settings.lamden_home = os.getcwd()
        settings.lamden_folder_path = join(settings.lamden_home, project_dir)
        settings.lamden_db_file = join(settings.lamden_folder_path, config.defaults()['lamden_db_file'])

        user_input = input('Enter password for new account: ')
        print(utils.create_account(user_input))
    else:
        print('Generating new contract.')
    pass

# add list for contracts and addresses
项目:openshift-under-kubernetes    作者:paralin    | 项目源码 | 文件源码
def undeploy(ctx):
    """Removes OpenShift from the cluster."""
    print("Preparing to remove OpenShift...")
    if not ctx.init_with_checks():
        print("Failed cursory checks, exiting.")
        exit(1)

    if ctx.auto_confirm:
        print("Auto confirm (-y) option set, clearing existing installation.")
    else:
        print("Really consider the decision you're about to make.")
        if not click.confirm("Do you want to clear the existing installation?"):
            print("Okay, cancelling.")
            exit(1)
    ctx.delete_namespace_byname("openshift-origin")
    print("Note: namespaces with openshift finalizer will need to be manually deleted if desired.")
    print("See: https://github.com/paralin/openshift-under-kubernetes/blob/master/REMOVING_OPENSHIFT.md")
项目:clickutil    作者:stroxler    | 项目源码 | 文件源码
def default_option(flag, short_flag, type, default, help):
    """
    Consistent interface for creating click options with defaults.

    PARAMETERS
    ----------
    flag: str
    short_flag: {str, None}
    type: any click arg type
    default: object
    help: str
    """
    type_info, help = _parse_type(type, help)
    if short_flag is None:
        click_decorator = click.option(flag, default=default,
                                       help=help, show_default=True,
                                       **type_info)
    else:
        click_decorator = click.option(flag, short_flag, default=default,
                                       help=help, show_default=True,
                                       **type_info)

    return mk_decorator(click_decorator)
项目:clickutil    作者:stroxler    | 项目源码 | 文件源码
def required_option(flag, short_flag, type, help):
    """
    Consistent interface for creating click options without defaults.

    PARAMETERS
    ----------
    flag: str
    short_flag: {str, None}
    type: any click arg type
    help: str
    """
    type_info, help = _parse_type(type, help)
    if short_flag is None:
        click_decorator = click.option(flag, required=True,
                                       help=help, show_default=True,
                                       **type_info)
    else:
        click_decorator = click.option(flag, short_flag, required=True,
                                       help=help, show_default=True,
                                       **type_info)

    return mk_decorator(click_decorator)
项目:clickutil    作者:stroxler    | 项目源码 | 文件源码
def boolean_flag(flag, default, help):
    """
    Consistent interface for creating boolean flags using click.


    PARAMETERS
    ----------
    flag: str
    default: boolean
    help: str
    """
    if not flag.startswith('--'):
        raise ValueError('flag {} does not start with "--"'.format(flag))
    stripped_flag = flag[2:]
    click_flag = '--{0}/--no-{0}'.format(stripped_flag)
    click_decorator = click.option(click_flag, default=default, help=help,
                                   show_default=True)
    return mk_decorator(click_decorator)
项目:smartcontainers    作者:crcresearch    | 项目源码 | 文件源码
def orcid(i, e):
    """Create a config file, based on an Orcid ID.

    :param i: string
        (Optional) Option to enter Orcid ID if known
    :param e: string
        (Optional) Option to enter Orcid email if known
    """
    # Make sure sandbox variable is set correctly in cli.py before testing
    if i:
        config_by_id(i)
    elif e:
        config_by_email(e)
    elif i is None and e is None:
        config_by_search()
    else:
        print('You have not selected a viable option.')
项目:LambdaMLM    作者:ilg    | 项目源码 | 文件源码
def set_config(ctx, option=None, value=None, boolean=None, integer=None):
    if option is None:
        try:
            click.echo('Configuration for {}:'.format(ctx.obj.list_address))
            for option, value in ctx.obj.listobj.user_config_values(ctx.obj.user):
                click.echo('{}: {}'.format(option, value))
        except listobj.InsufficientPermissions:
            handle_insufficient_permissions('view options on {}.'.format(ctx.obj.list_address))
        return
    if boolean is not None:
        value = boolean
    elif integer is not None:
        value = integer
    try:
        ctx.obj.listobj.user_set_config_value(ctx.obj.user, option, value)
        click.echo('Set {} to {} on {}.'.format(option, value, ctx.obj.list_address))
    except listobj.InsufficientPermissions:
        handle_insufficient_permissions('change {} on {}.'.format(option, ctx.obj.list_address))
    except listobj.UnknownOption:
        click.echo('{} is not a valid configuration option.'.format(option), err=True)
项目:catalyst    作者:enigmampc    | 项目源码 | 文件源码
def extract_option_object(option):
    """Convert a click.option call into a click.Option object.

    Parameters
    ----------
    option : decorator
        A click.option decorator.

    Returns
    -------
    option_object : click.Option
        The option object that this decorator will create.
    """

    @option
    def opt():
        pass

    return opt.__click_params__[0]
项目:cfdilib    作者:Vauxoo    | 项目源码 | 文件源码
def cfdv32mx(config):
    """Format cfdi v3.2 for Mexico.

    \b
    File where the files will be written document.xml.
        cfdicli --in_file /path/to/yout/json/documnt.json cfdv32mx

    \b
    File where the files will be written from document.json.
        cfdicli --out_file ./document.xml cfdv32mx
    """
    # TODO: look for a secure option for eval.
    #       Or simply the CLI only should manage json?
    # TODO: Implement json option also.
    dict_input = eval(config.in_file.read())
    invoice = cfdv32.get_invoice(dict_input)
    if invoice.valid:
        config.out_file.write(invoice.document)
        config.out_file.flush()
        click.echo('Document %s has been created.' % config.out_file.name)
    else:
        click.echo(invoice.ups.message)
项目:globus-cli    作者:globus    | 项目源码 | 文件源码
def task_submission_options(f):
    """
    Options shared by both transfer and delete task submission
    """
    f = click.option(
        "--dry-run", is_flag=True,
        help=("Don't actually submit the task, print submission "
              "data instead"))(f)
    f = click.option(
        "--submission-id", help=(
            "Task submission ID, as generated by `globus task "
            "generate-submission-id`. Used for safe resubmission in the "
            "presence of network failures."))(f)
    f = click.option(
        "--label", default=None, help="Set a label for this task.")(f)
    f = click.option(
        "--deadline", default=None, type=ISOTimeType(),
        help="Set a deadline for this to be canceled if not completed by.")(f)
    f = click.option('--skip-activation-check', is_flag=True, help=(
            "Submit the task even if the endpoint(s) "
            "aren't currently activated."))(f)

    return f
项目:globus-cli    作者:globus    | 项目源码 | 文件源码
def shell_complete_option(f):
    def callback(ctx, param, value):
        if not value or ctx.resilient_parsing:
            return

        if value == 'BASH':
            do_bash_complete()
        elif value == 'ZSH':
            do_zsh_complete()
        else:
            raise ValueError('Unsupported shell completion')

        click.get_current_context().exit(0)

    f = click.option('--shell-complete', cls=HiddenOption,
                     is_eager=True, expose_value=False,
                     type=click.Choice(SUPPORTED_SHELLS),
                     callback=callback)(f)
    return f
项目:globus-cli    作者:globus    | 项目源码 | 文件源码
def version_option(f):
    """
    Largely a custom clone of click.version_option -- almost identical, but
    prints our special output.
    """
    def callback(ctx, param, value):
        # copied from click.decorators.version_option
        # no idea what resilient_parsing means, but...
        if not value or ctx.resilient_parsing:
            return

        print_version()
        ctx.exit(0)

    return click.option('--version', is_flag=True, expose_value=False,
                        is_eager=True, callback=callback, cls=HiddenOption)(f)
项目:temci    作者:parttimenerd    | 项目源码 | 文件源码
def validate(type_scheme: Type) -> t.Callable[[click.Context, str, t.Any], t.Any]:
    """
    Creates a valid click option validator function that can be passed to click via the callback
    parameter.
    The validator function expects the type of the value to be the raw type of the type scheme.

    :param type_scheme: type scheme the validator validates against
    :return: the validator function
    """
    def func(ctx, param, value):
        param = param.human_readable_name
        param = param.replace("-", "")
        res = verbose_isinstance(value, type_scheme, value_name=param)
        if not res:
            raise click.BadParameter(str(res))
        return value
    return func
项目: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
项目:assistant-sdk-python    作者:googlesamples    | 项目源码 | 文件源码
def resolve_project_id(client_secrets, credentials):
    """Resolve project ID from client secrets."""
    if client_secrets is None:
        client_secrets = 'client_secret_%s.json' % credentials.client_id
    try:
        with open(client_secrets, 'r') as f:
            secret = json.load(f)
            return secret['installed']['project_id']
    except Exception as e:
        raise click.ClickException('Error loading client secret: %s.\n'
                                   'Run the device tool '
                                   'with --client-secrets '
                                   'or --project-id option.\n'
                                   'Or copy the %s file '
                                   'in the current directory.'
                                   % (e, client_secrets))
项目:click-configfile    作者:click-contrib    | 项目源码 | 文件源码
def test_param_with_default__uses_param_default_when_missing(self, cli_runner_isolated):
        assert ConfigFileProcessor1.config_files[0] == "hello.ini"
        CONFIG_FILE_CONTENTS = """
            [hello]
            name = Alice
            """
        write_configfile_with_contents("hello.ini", CONFIG_FILE_CONTENTS)
        assert os.path.exists("hello.ini")

        CONTEXT_SETTINGS = dict(default_map=ConfigFileProcessor1.read_config())
        @click.command(context_settings=CONTEXT_SETTINGS)
        @click.option("-n", "--name", type=str, default="__CMDLINE__")
        @click.option("--number", default=123)
        def hello_with_param_default(name, number):
            click.echo("param: number= %s" % number)

        result = cli_runner_isolated.invoke(hello_with_param_default)
        assert result.output == "param: number= 42\n"
        assert result.exit_code == 0
项目:click-configfile    作者:click-contrib    | 项目源码 | 文件源码
def test_param_with_default__uses_cmdline_when_provided(self, cli_runner_isolated):
        assert ConfigFileProcessor1.config_files[0] == "hello.ini"
        CONFIG_FILE_CONTENTS = """
            [hello]
            name = Alice
            number = 43
            """
        write_configfile_with_contents("hello.ini", CONFIG_FILE_CONTENTS)
        assert os.path.exists("hello.ini")

        CONTEXT_SETTINGS = dict(default_map=ConfigFileProcessor1.read_config())
        @click.command(context_settings=CONTEXT_SETTINGS)
        @click.option("-n", "--name", type=str, default="__CMDLINE__")
        @click.option("--number", default=123)
        def hello_with_param_default2(name, number):
            click.echo("param: number= %s" % number)

        result = cli_runner_isolated.invoke(hello_with_param_default2,
                                            ["--number", "234"])
        assert result.output == "param: number= 234\n"
        assert result.exit_code == 0
项目:click-configfile    作者:click-contrib    | 项目源码 | 文件源码
def test_param_without_default__uses_cmdline_default_when_missing(self, cli_runner_isolated):
        assert ConfigFileProcessor1.config_files[0] == "hello.ini"
        CONFIG_FILE_CONTENTS = """
            [hello]
            number = 1234
            """
        write_configfile_with_contents("hello.ini", CONFIG_FILE_CONTENTS)
        assert os.path.exists("hello.ini")

        CONTEXT_SETTINGS = dict(default_map=ConfigFileProcessor1.read_config())
        @click.command(context_settings=CONTEXT_SETTINGS)
        @click.option("-n", "--name", type=str, default="__CMDLINE__")
        def hello_with_config(name):
            click.echo("param: name= %s" % name)

        result = cli_runner_isolated.invoke(hello_with_config)
        assert result.output == "param: name= __CMDLINE__\n"
        assert result.exit_code == 0
项目:click-configfile    作者:click-contrib    | 项目源码 | 文件源码
def test_with_cmdline_and_configfile__prefers_cmdline(self, cli_runner_isolated):
        assert ConfigFileProcessor1.config_files[0] == "hello.ini"
        CONFIG_FILE_CONTENTS1 = """
            [hello]
            name = Alice
            """
        write_configfile_with_contents("hello.ini", CONFIG_FILE_CONTENTS1)
        assert os.path.exists("hello.ini")
        assert not os.path.exists("hello.cfg")

        CONTEXT_SETTINGS = dict(default_map=ConfigFileProcessor1.read_config())
        @click.command(context_settings=CONTEXT_SETTINGS)
        @click.option("-n", "--name", default="__CMDLINE__")
        def hello(name):
            click.echo("Hello %s" % name)

        result = cli_runner_isolated.invoke(hello, ["--name", "CMDLINE_VALUE"])
        assert result.output == "Hello CMDLINE_VALUE\n"
        assert result.exit_code == 0
项目:click-configfile    作者:click-contrib    | 项目源码 | 文件源码
def test_with_configfile2__usable_as_alternative(self, cli_runner_isolated):
        assert ConfigFileProcessor1.config_files[1] == "hello.cfg"
        CONFIG_FILE_CONTENTS2 = """
            [hello]
            name = Bob
            """
        write_configfile_with_contents("hello.cfg", CONFIG_FILE_CONTENTS2)
        assert not os.path.exists("hello.ini")
        assert os.path.exists("hello.cfg")

        CONTEXT_SETTINGS = dict(default_map=ConfigFileProcessor1.read_config())
        @click.command(context_settings=CONTEXT_SETTINGS)
        @click.option("-n", "--name", default="__CMDLINE__")
        def hello(name):
            click.echo("Hello %s" % name)

        result = cli_runner_isolated.invoke(hello)
        assert result.output == "Hello Bob\n"
        assert result.exit_code == 0
项目:click-configfile    作者:click-contrib    | 项目源码 | 文件源码
def test_with_configfile12__prefers_configfile1(self, cli_runner_isolated):
        assert ConfigFileProcessor1.config_files == ["hello.ini", "hello.cfg"]
        CONFIG_FILE_CONTENTS1 = """
            [hello]
            name = alice
            """
        CONFIG_FILE_CONTENTS2 = """
            [hello]
            name = bob
            """
        write_configfile_with_contents("hello.ini", CONFIG_FILE_CONTENTS1)
        write_configfile_with_contents("hello.cfg", CONFIG_FILE_CONTENTS2)
        assert os.path.exists("hello.ini")
        assert os.path.exists("hello.cfg")

        CONTEXT_SETTINGS = dict(default_map=ConfigFileProcessor1.read_config())
        @click.command(context_settings=CONTEXT_SETTINGS)
        @click.option("-n", "--name", default="__CMDLINE__")
        def hello(name):
            click.echo("Hello %s" % name)

        result = cli_runner_isolated.invoke(hello)
        assert result.output == "Hello alice\n"
        assert result.exit_code == 0
项目:EasyEuler    作者:Encrylize    | 项目源码 | 文件源码
def cli(paths, language, time, errors, recursive):
    """
    Verify the solution to a problem.

    Runs the appropriate command for a language (specified in the
    configuration file) with the file path(s) as arguments.

    If the LANGUAGE option isn't specified, it will be identified based
    on the file extension. Similarly, the problem ID will be identified
    based on the file name.

    """

    for path in paths:
        if os.path.isdir(path):
            if recursive:
                validate_directory(path, language, time, errors)
            else:
                click.echo('Skipping %s because it is a directory '
                           'and --recursive was not specified' %
                           click.format_filename(path))
        else:
            validate_file(path, language, time, errors)
项目:configmanager    作者:jbasko    | 项目源码 | 文件源码
def option(self, *args, **kwargs):
        """
        Registers a click.option 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``.

        Examples::

            config = Config({'greeting': 'Hello'})

            @click.command()
            @config.click.option('--greeting', config.greeting)
            def say_hello(greeting):
                click.echo(greeting)

        """
        args, kwargs = _config_parameter(args, kwargs)
        return self._click.option(*args, **kwargs)
项目: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)
项目:MIGPU    作者:scuAILab    | 项目源码 | 文件源码
def script_info_option(*args, **kwargs):
    """This decorator works exactly like :func:`click.option` but is eager
    by default and stores the value in the :attr:`ScriptInfo.data`.  This
    is useful to further customize an application factory in very complex
    situations.

    :param script_info_key: this is a mandatory keyword argument which
                            defines under which data key the value should
                            be stored.
    """
    try:
        key = kwargs.pop('script_info_key')
    except LookupError:
        raise TypeError('script_info_key not provided.')

    real_callback = kwargs.get('callback')
    def callback(ctx, param, value):
        if real_callback is not None:
            value = real_callback(ctx, value)
        ctx.ensure_object(ScriptInfo).data[key] = value
        return value

    kwargs['callback'] = callback
    kwargs.setdefault('is_eager', True)
    return click.option(*args, **kwargs)
项目:peerme    作者:cooperlees    | 项目源码 | 文件源码
def main(ctx, config, debug, data_source, refresh_data):
    '''
        Discover and generate potential peering endpoints @ IXs
    '''

    loop = asyncio.get_event_loop()
    config_obj = peerme_config.PeermeConfig(config)
    if data_source == 'pdbsql':
        peering_api = peeringdb_mysql.PeermeDb(config_obj, loop)
    elif data_source == 'pdbapi':
        peering_api = peeringdb_api.PeermeDb(config_obj, loop)
    elif data_source == 'euroix':
        peering_api = euroix_json.PeermeDb(
            config_obj, refresh_data, loop
        )
    else:
        raise Exception('Invalid option "{}" for data source.'.format(
            data_source))

    # Class to hold all shared options
    ctx.obj = Options(debug, time.time(), peering_api, loop, config_obj)
项目:BioDownloader    作者:biomadeira    | 项目源码 | 文件源码
def add_common(options):
    def _add_options(func):
        for option in reversed(options):
            func = option(func)
        return func
    return _add_options
项目:zellij    作者:nedbat    | 项目源码 | 文件源码
def common_options(category):
    """Provide a set of common options to a click command."""
    def _wrapped(func):
        # from: https://github.com/pallets/click/issues/108#issuecomment-194465429
        for option in reversed(_common_options[category]):
            func = option(func)
        return func
    return _wrapped
项目:kubernaut    作者:datawire    | 项目源码 | 文件源码
def common_options(func):
    @click.option("-s", "--server", help="Set the kubernaut server", default=KUBERNAUT_ADDR)
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs)

    return wrapper
项目:casebot    作者:anseljh    | 项目源码 | 文件源码
def set_setting(config, ini, section, option, passed_option=None):
    if section not in config:
        config[section] = {}
    if passed_option is not None:
        config[section][option] = passed_option
    else:
        config[section][option] = ini[section][option]
    return config
项目:hlsclt    作者:benjmarshall    | 项目源码 | 文件源码
def syn_lookahead_check(ctx):
    config = ctx.obj.config
    solution_num = ctx.obj.solution_num
    file = ctx.obj.file
    if (not ctx.obj.syn_command_present) and (not check_for_syn_results(config["project_name"], solution_num, config["top_level_function_name"])):
        if click.confirm("C Synthesis has not yet been run but is required for the process(es) you have selected.\nWould you like to add it to this run?", default=True):
            click.echo("Adding csynth option.")
            file.write("csynth_design" + "\n")
        else:
            click.echo("Ok, watch out for missing synthesis errors!")

# Function which defines the main actions of the 'cosim' command.
项目:sphinxcontrib-versioning    作者:Robpol86    | 项目源码 | 文件源码
def custom_sort(param):
        """Custom Click(Command|Group).params sorter.

        Case insensitive sort with capitals after lowercase. --version at the end since I can't sort --help.

        :param click.core.Option param: Parameter to evaluate.

        :return: Sort weight.
        :rtype: int
        """
        option = param.opts[0].lstrip('-')
        if param.param_type_name != 'option':
            return False,
        return True, option == 'version', option.lower(), option.swapcase()
项目:sphinxcontrib-versioning    作者:Robpol86    | 项目源码 | 文件源码
def build_options(func):
    """Add "build" Click options to function.

    :param function func: The function to wrap.

    :return: The wrapped function.
    :rtype: function
    """
    func = click.option('-a', '--banner-greatest-tag', is_flag=True,
                        help='Override banner-main-ref to be the tag with the highest version number.')(func)
    func = click.option('-A', '--banner-recent-tag', is_flag=True,
                        help='Override banner-main-ref to be the most recent committed tag.')(func)
    func = click.option('-b', '--show-banner', help='Show a warning banner.', is_flag=True)(func)
    func = click.option('-B', '--banner-main-ref',
                        help="Don't show banner on this ref and point banner URLs to this ref. Default master.")(func)
    func = click.option('-i', '--invert', help='Invert/reverse order of versions.', is_flag=True)(func)
    func = click.option('-p', '--priority', type=click.Choice(('branches', 'tags')),
                        help="Group these kinds of versions at the top (for themes that don't separate them).")(func)
    func = click.option('-r', '--root-ref',
                        help='The branch/tag at the root of DESTINATION. Will also be in subdir. Default master.')(func)
    func = click.option('-s', '--sort', multiple=True, type=click.Choice(('semver', 'alpha', 'time')),
                        help='Sort versions. Specify multiple times to sort equal values of one kind.')(func)
    func = click.option('-t', '--greatest-tag', is_flag=True,
                        help='Override root-ref to be the tag with the highest version number.')(func)
    func = click.option('-T', '--recent-tag', is_flag=True,
                        help='Override root-ref to be the most recent committed tag.')(func)
    func = click.option('-w', '--whitelist-branches', multiple=True,
                        help='Whitelist branches that match the pattern. Can be specified more than once.')(func)
    func = click.option('-W', '--whitelist-tags', multiple=True,
                        help='Whitelist tags that match the pattern. Can be specified more than once.')(func)

    return func
项目:skymod    作者:DelusionalLogic    | 项目源码 | 文件源码
def set_(name, value):
    section, option = name.split(".")
    try:
        cfg[section][option] = value
    except KeyError:
        print(
            "Unknown config option {Style.BRIGHT}{}{Style.RESET_ALL}"
            .format(
                name,
                Style=Style
            )
        )
项目:skymod    作者:DelusionalLogic    | 项目源码 | 文件源码
def get(name):
    section, option = name.split(".")
    try:
        print(cfg[section][option])
    except KeyError:
        print(
            "Unknown config option {Style.BRIGHT}{}{Style.RESET_ALL}"
            .format(
                name,
                Style=Style
            )
        )
项目:holcrawl    作者:shaypal5    | 项目源码 | 文件源码
def _shared_options(func):
    for option in reversed(_SHARED_OPTIONS):
        func = option(func)
    return func
项目:swjtu-pyscraper    作者:Desgard    | 项目源码 | 文件源码
def run_command(info, host, port, reload, debugger, eager_loading,
                with_threads):
    """Runs a local development server for the Flask application.

    This local server is recommended for development purposes only but it
    can also be used for simple intranet deployments.  By default it will
    not support any sort of concurrency at all to simplify debugging.  This
    can be changed with the --with-threads option which will enable basic
    multithreading.

    The reloader and debugger are by default enabled if the debug flag of
    Flask is enabled and disabled otherwise.
    """
    from werkzeug.serving import run_simple

    debug = get_debug_flag()
    if reload is None:
        reload = bool(debug)
    if debugger is None:
        debugger = bool(debug)
    if eager_loading is None:
        eager_loading = not reload

    app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)

    # Extra startup messages.  This depends a but on Werkzeug internals to
    # not double execute when the reloader kicks in.
    if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
        # If we have an import path we can print it out now which can help
        # people understand what's being served.  If we do not have an
        # import path because the app was loaded through a callback then
        # we won't print anything.
        if info.app_import_path is not None:
            print(' * Serving Flask app "%s"' % info.app_import_path)
        if debug is not None:
            print(' * Forcing debug mode %s' % (debug and 'on' or 'off'))

    run_simple(host, port, app, use_reloader=reload,
               use_debugger=debugger, threaded=with_threads)
项目:aiotasks    作者:cr0hn    | 项目源码 | 文件源码
def __call__(self, f):
        def wrapped_f(*args):
            fn = f
            for option in reversed(global_options_list):
                fn = option(f)

            fn = click.group(
                context_settings={'help_option_names': ['-h', '--help']},
                invoke_without_command=self.invoke_without_command)(fn)

            return fn

        return wrapped_f()


#
# HERE MORE EXAMPLES OF CMD OPTIONS
#
# -------------------------------------------------------------------------
# Options for "auto" command
# -------------------------------------------------------------------------
#
# auto_options_list = (
#     click.option('-T', '--timeout', 'timeout', type=int, default=60,
#                  help="max time to wait until actions are available"),
# )
#
#
# class auto_options(object):
#     def __call__(self, f):
#         def wrapped_f(*args):
#             fn = f
#             for option in reversed(auto_options_list):
#                 fn = option(f)
#
#             return fn
#
#         return wrapped_f()
项目:rsync-by-config    作者:AndiH    | 项目源码 | 文件源码
def parseGlobalRsyncOptions(self):
        """Parse global Rsync options specified at the very top of a TOML file."""
        globalOptions = []
        if "rsync_options" in self.config:
            if self.verbose:
                print("# A global rsync_options key is given in the config file.")
            rawOptions = self.config["rsync_options"]
            if type(rawOptions) is list:
                for option in self.config["rsync_options"]:
                    globalOptions.append(str(option))
            else:
                globalOptions.append(str(rawOptions))
            if self.verbose:
                print("# List of rsync options due to command line and global key in config file: {}".format(globalOptions))
        self.rsync_options = self.rsync_options + globalOptions
项目:rsync-by-config    作者:AndiH    | 项目源码 | 文件源码
def sync(synObj):
    """Setup rsync with options from different sources and run rsync"""
    rsync_opts = []
    rsync_opts.append("--archive")  # archive
    # rsync_opts.append("--update")  # skip files that are newer on the receiver
    rsync_opts.append("--human-readable")  # output numbers in a human-readable format
    rsync_opts.append("--verbose")  # increase verbosity
    rsync_opts.append("--recursive")  # recurse into directories
    rsync_opts.append("--compress")  # compress file data during the transfer
    rsync_opts.append("--cvs-exclude")  # auto-ignore files in the same way CVS does
    # rsync_opts.append("--delete")  # delete extraneous files from dest dirs
    # rsync_opts.append('--filter=\"dir-merge,- .gitignore\"')
    rsync_opts.append('--exclude=*.bin')
    rsync_opts.append('--exclude=' + synObj.config_file)
    if synObj.dryrun:
        if synObj.verbose:
            print("# --dryrun is turned ON!")
        rsync_opts.append("--dry-run")  # no transfer, just report
    if 'rsync_options' in synObj.host_toml:
        for option in synObj.host_toml['rsync_options']:
            rsync_opts.append(option)
    for option in synObj.rsync_options:
        rsync_opts.append(str(option))

    if synObj.verbose:
        print("# All rsync options: {}".format(rsync_opts))

    sourceDir = synObj.localDir + "/"  # make sure it has a trailing slash, for rsync
    destDir = synObj.destDir
    if 'hostname' in synObj.host_toml:
        destDir = str(synObj.host_toml['hostname']) + ":" + synObj.destDir

    if synObj.gather:
        sourceDir, destDir = destDir, sourceDir

    if synObj.multihost:
        print("Syncing with {}".format(synObj.entry))
    print(rsync(rsync_opts, sourceDir, destDir))
项目:linchpin    作者:CentOS-PaaS-SIG    | 项目源码 | 文件源码
def drop(ctx, targets):
    """
    DEPRECATED. Use 'destroy'.

    There are now two functions, `destroy` and `down` which perform node
    teardown. The `destroy` functionality is the default, and if drop is
    used, will be called.

    The `down` functionality is currently unimplemented, but will shutdown
    and preserve instances. This feature will only work on providers that
    support this option.

    """

    pass
项目:Sci-Finder    作者:snverse    | 项目源码 | 文件源码
def run_command(info, host, port, reload, debugger, eager_loading,
                with_threads):
    """Runs a local development server for the Flask application.

    This local server is recommended for development purposes only but it
    can also be used for simple intranet deployments.  By default it will
    not support any sort of concurrency at all to simplify debugging.  This
    can be changed with the --with-threads option which will enable basic
    multithreading.

    The reloader and debugger are by default enabled if the debug flag of
    Flask is enabled and disabled otherwise.
    """
    from werkzeug.serving import run_simple

    debug = get_debug_flag()
    if reload is None:
        reload = bool(debug)
    if debugger is None:
        debugger = bool(debug)
    if eager_loading is None:
        eager_loading = not reload

    app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)

    # Extra startup messages.  This depends a bit on Werkzeug internals to
    # not double execute when the reloader kicks in.
    if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
        # If we have an import path we can print it out now which can help
        # people understand what's being served.  If we do not have an
        # import path because the app was loaded through a callback then
        # we won't print anything.
        if info.app_import_path is not None:
            print(' * Serving Flask app "%s"' % info.app_import_path)
        if debug is not None:
            print(' * Forcing debug mode %s' % (debug and 'on' or 'off'))

    run_simple(host, port, app, use_reloader=reload,
               use_debugger=debugger, threaded=with_threads)
项目:Sci-Finder    作者:snverse    | 项目源码 | 文件源码
def run_command(info, host, port, reload, debugger, eager_loading,
                with_threads):
    """Runs a local development server for the Flask application.

    This local server is recommended for development purposes only but it
    can also be used for simple intranet deployments.  By default it will
    not support any sort of concurrency at all to simplify debugging.  This
    can be changed with the --with-threads option which will enable basic
    multithreading.

    The reloader and debugger are by default enabled if the debug flag of
    Flask is enabled and disabled otherwise.
    """
    from werkzeug.serving import run_simple

    debug = get_debug_flag()
    if reload is None:
        reload = bool(debug)
    if debugger is None:
        debugger = bool(debug)
    if eager_loading is None:
        eager_loading = not reload

    app = DispatchingApp(info.load_app, use_eager_loading=eager_loading)

    # Extra startup messages.  This depends a bit on Werkzeug internals to
    # not double execute when the reloader kicks in.
    if os.environ.get('WERKZEUG_RUN_MAIN') != 'true':
        # If we have an import path we can print it out now which can help
        # people understand what's being served.  If we do not have an
        # import path because the app was loaded through a callback then
        # we won't print anything.
        if info.app_import_path is not None:
            print(' * Serving Flask app "%s"' % info.app_import_path)
        if debug is not None:
            print(' * Forcing debug mode %s' % (debug and 'on' or 'off'))

    run_simple(host, port, app, use_reloader=reload,
               use_debugger=debugger, threaded=with_threads)
项目:saffron    作者:Lamden    | 项目源码 | 文件源码
def list(option):
    assert option != None and option in ['account', 'contract'], 'Provide either "account" or "contract" after "list"'
    pass
项目:core-workflow    作者:python    | 项目源码 | 文件源码
def backport(self):
        if not self.branches:
            raise click.UsageError("At least one branch must be specified.")
        self.fetch_upstream()

        for maint_branch in self.sorted_branches:
            click.echo(f"Now backporting '{self.commit_sha1}' into '{maint_branch}'")

            cherry_pick_branch = self.get_cherry_pick_branch(maint_branch)
            self.checkout_branch(maint_branch)
            commit_message = ""
            try:
                self.cherry_pick()
                commit_message = self.amend_commit_message(cherry_pick_branch)
            except subprocess.CalledProcessError as cpe:
                click.echo(cpe.output)
                click.echo(self.get_exit_message(maint_branch))
            except CherryPickException:
                click.echo(self.get_exit_message(maint_branch))
                raise
            else:
                if self.push:
                    self.push_to_remote(maint_branch,
                                        cherry_pick_branch,
                                        commit_message)
                    self.cleanup_branch(cherry_pick_branch)
                else:
                    click.echo(\
f"""
Finished cherry-pick {self.commit_sha1} into {cherry_pick_branch} \U0001F600
--no-push option used.
... Stopping here.
To continue and push the changes:
    $ cherry_picker --continue

To abort the cherry-pick and cleanup:
    $ cherry_picker --abort
""")
项目:pydisp    作者:dimatura    | 项目源码 | 文件源码
def main(images, title, win, width, pause, port, hostname):

    # TODO tiling option

    if port is not None:
        pydisp.CONFIG.PORT = port

    if hostname is not None:
        pydisp.CONFIG.HOSTNAME = hostname

    for img_fname in images:
        click.echo('loading {}'.format(img_fname))
        base, ext = os.path.splitext(img_fname)
        ext = ext.lower().replace('.', '').replace('jpg', 'jpeg')
        if not pydisp.is_valid_image_mime_type(ext):
            raise click.BadParameter('unrecognized image format: {}'.format(ext))
        with open(img_fname, 'rb') as f:
            encoded = pydisp.b64_encode(f.read(), ext)
        if title == '':
            title = img_fname
        if win=='%f':
            win = img_fname
        elif win=='%p':
            win = os.path.basename(img_fname)
        pydisp.pane('image',
                    win=win,
                    title=title,
                    content={'src': encoded,
                             'width': width,
                            })
        if (len(img_fname) > 1) and (pause > 0.0):
            time.sleep(pause)