def global_options(f): def color_callback(ctx, option, value): ctx.color = value def logfile_callback(ctx, option, path): ctx.logfilepath = path config = click.option( '--config', '-c', help='The config file to use.', default=None, metavar='PATH' ) color = click.option( '--color/--no-color', help=('Use colored/uncolored output. Default is to only enable colors ' 'when not part of a pipe.'), expose_value=False, default=None, callback=color_callback ) logfile = click.option( '--logfile', '-l', help='The logfile to use [defaults to stdout]', type=click.Path(), callback=logfile_callback, default=None, expose_value=False, metavar='LOGFILE', ) version = click.version_option(version=__version__) return logfile(config(color(version(f))))
def global_options(f): def config_callback(ctx, option, config): prepare_context(ctx, config) def verbosity_callback(ctx, option, verbose): if verbose: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) config = click.option( '--config', '-c', is_eager=True, # make sure other options can access config help='The config file to use.', default=None, metavar='PATH', expose_value=False, callback=config_callback ) verbose = click.option( '--verbose', '-v', is_eager=True, # make sure to log config when debugging help='Output debugging information.', is_flag=True, expose_value=False, callback=verbosity_callback ) version = click.version_option(version=__version__) return config(verbose(version(f)))
def global_options(f): config = click.option('--config', '-c', default=None, metavar='PATH', help='The config file to use.') verbose = click.option('--verbose', '-v', is_flag=True, help='Output debugging information.') version = click.version_option(version=__version__) return config(verbose(version(f)))
def get_params(self, name): def show_help(ctx, param, value): if value and not ctx.resilient_parsing: ctx.info_name += " " + name click.echo(ctx.get_help(), color=ctx.color) ctx.exit() return [ click.version_option(version=self.version, message="%(version)s"), click.option( "-h", "--help", is_flag=True, is_eager=True, expose_value=False, callback=show_help, help="Show this message and exit.", ), ] + self.common_options
def global_options(f): def config_callback(ctx, option, config): prepare_context(ctx, config) def verbosity_callback(ctx, option, verbose): if verbose: logger.setLevel(logging.DEBUG) else: logger.setLevel(logging.INFO) def color_callback(ctx, option, value): ctx.color = value config = click.option( '--config', '-c', is_eager=True, # make sure other options can access config help='The config file to use.', default=None, metavar='PATH', expose_value=False, callback=config_callback ) verbose = click.option( '--verbose', '-v', is_eager=True, # make sure to log config when debugging help='Output debugging information.', is_flag=True, expose_value=False, callback=verbosity_callback ) color = click.option( '--color/--no-color', help=('Use colored/uncolored output. Default is to only enable colors ' 'when not part of a pipe.'), expose_value=False, default=None, callback=color_callback ) version = click.version_option(version=__version__) return config(verbose(color(version(f))))
import click from classifier.train import train_group from classifier.test import test_group CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) SOURCES = [train_group, test_group] cli = click.version_option()( click.CommandCollection(sources=SOURCES, context_settings=CONTEXT_SETTINGS) ) if __name__ == '__main__': cli()
"spec", type=click.File('rb'), default=None, envvar="SLACKTIVATE_CONFIG", metavar="SPEC", required=False, ) cli_opt_dry_run = click.option("-y", "--dry-run", is_flag=True, envvar="SLACKTIVATE_DRY_RUN", default=False, help="Do not actually perform the action.") cli_opt_version = click.version_option(version=slacktivate.__version__) OutputFormatType = typing.Union[typing.Literal["term"], typing.Literal["json"], typing.Literal["csv"], ] cli_opt_output_format = click.option( "--format", "-f", type=click.Choice(["term", "json", "csv"], case_sensitive=False), default="term", metavar="FORMAT", help="Output format (e.g.: term, json, csv, ...)") cli_root = chain_functions(*[ cli_root_group_green, cli_opt_token,
# https://github.com/tox-dev/tox/issues/1434 exc.stderr.strip() or exc.stdout.strip(), ) from exc ############################################################################### # https://github.com/python/typeshed/pull/3385 DEST_OPTION = click.option( # type: ignore "--dest", help="Specify the path to build in.", nargs=1, type=click.Path(), default=os.getcwd(), show_default="current working directory", ) VERSION_OPTION = click.version_option(__version__) @click.command() @click.option( "--build-opt", help="Pass keyword arguments to the builder (e.g. foo=bar).", nargs=1, multiple=True, ) @DEST_OPTION @click.option( "--log-level", help="Specify how verbose output should be.", nargs=1, type=click.Choice(
state_key='blocking_timeout', default=BLOCKING_TIMEOUT, type=float, help='when --debug: Blocking detector timeout.', ), compat_option( '--console-port', state_key='console_port', default=CONSOLE_PORT, type=params.TCPPort(), help='when --debug: Port to run debugger console on.', ), ] core_options: OptionSequence = [ click.version_option(version=f'Faust {faust_version}'), option('--app', '-A', help='Path of Faust application to use, or the name of a module.'), option('--quiet/--no-quiet', '-q', default=False, help='Silence output to <stdout>/<stderr>.'), option('--debug/--no-debug', default=DEBUG, help='Enable debugging output, and the blocking detector.'), option('--no-color/--color', '--no_color/--color', default=False, help='Enable colors in output.'), option('--workdir',
state_key="blocking_timeout", default=None, type=float, help="when --debug: Blocking detector timeout.", ), compat_option( "--console-port", state_key="console_port", default=CONSOLE_PORT, type=params.TCPPort(), help="when --debug: Port to run debugger console on.", ), ] core_options: OptionSequence = [ click.version_option(version=f"Faust {faust_version}"), option("--app", "-A", help="Path of Faust application to use, or the name of a module."), option( "--quiet/--no-quiet", "-q", default=False, help="Silence output to <stdout>/<stderr>.", ), option( "--debug/--no-debug", default=DEBUG, help="Enable debugging output, and the blocking detector.", ), option(
def create_cli(package_name, package_path, type_=None, exclude=None, config=None): base_path = os.path.abspath(os.path.join(package_path, '..')) if exclude is None: exclude = EXCLUDE_BY_TYPE.get(type_, []) mode_file = os.path.join(base_path, '.dev') if type_ == 'tool' and not os.path.exists(mode_file): exclude = exclude + PROD_EXCLUDE if config is None: # Find the ini directory inifilename = 'marvin.ini' inidir = base_path # Load the ini file inipath = os.path.join(inidir, inifilename) config_defaults = { 'inidir': inidir, 'marvin_packagedir': '{inidir}/{marvin_package}', } if os.path.exists(inipath): config = parse_ini(inipath, config_defaults) else: config = {} exclude = config.get('marvin_exclude', ','.join(exclude)) if isinstance(exclude, str): exclude = exclude.split(',') @click.group('custom') @click.option('--debug', is_flag=True, help='Enable debug mode.') @click.pass_context def cli(ctx, debug): ctx.obj = { 'debug': debug, 'package_name': package_name, 'package_path': package_path, 'base_path': base_path, 'type': type_, 'config': config, } # Load internal commands commands = {} commands.update(cli_bigquery.commands) commands.update(cli_pkg.commands) commands.update(cli_test.commands) commands.update(cli_notebook.commands) commands.update(cli_engine.commands) commands.update(cli_hive.commands) for name, command in commands.items(): if name not in exclude: cli.add_command(command, name=name) # Load custom commands from project been managed commands_file_paths = [ config.get('marvin_commandsfile'), os.path.join(base_path, 'marvin_commands.py'), os.path.join(base_path, 'commands.py') ] for commands_file_path in commands_file_paths: if commands_file_path and os.path.exists(commands_file_path): commands = load_commands_from_file(commands_file_path) for command in commands: cli.add_command(command) break # Add version and help messages from .. import __version__ cli = click.version_option(version=__version__, message=VERSION_MSG.replace('\n', '\n '))(cli) cli.help = '\b{}\n'.format(VERSION_MSG % {'version': __version__}) return cli
def _sort_by(thing): return not getattr(thing, "_always_sorts_first", False), sort_by(thing) contents = [ path_and_children for path in paths or (project.from_path(FilePath(".")),) for path_and_children in recurse(path=path, ls=ls) ] for line in output(contents, sort_by=_sort_by): stdout.write(line) stdout.write("\n") I_hate_everything = [ click.command(context_settings=dict(help_option_names=["-h", "--help"])), click.version_option(version=__version__, prog_name="l"), click.option( "-1", "--one-per-line", "output", flag_value=core.one_per_line, help="Force output to be one entry per line. " "Note that unlike ls, when recursively listing directories, " "also forces output to not be grouped by subdirectory.", ), click.option( "--many-per-line", "output", flag_value=core.columnized, help="Show human-readable, labelled output.", ), click.option( "--tree", "output", flag_value=core.as_tree,
show_default=True ) verbose = click.option('-v', '--verbose', count=True, default=2 ) variant_type = click.option('--variant-type', type=click.Choice(['snv', 'sv']), default='snv', show_default=True, help="If Structural Variantion or Single Nucleotide variant"\ " mode should be used" ) family_file = click.option('-f', '--family_file', type=click.File('r') ) family_type = click.option('--family_type', type=click.Choice(['ped', 'alt']), default='ped', show_default=True, help='If the analysis use one of the known setups, please specify which one.' ) version = click.version_option(puzzle.__version__) phenomizer = click.option('--phenomizer', nargs=2, help='Phenomizer username/password', envvar='PHENOMIZER_AUTH' )
count=True, type=int, default=1, help='Verbose output'), click.option('-d', '--debug', 'debug', is_flag=True, default=False, help='enable debug'), click.option('--quiet', '-q', 'verbosity', flag_value=0, help='Minimal output'), click.version_option(version=version)) class global_options(object): def __init__(self, invoke_without_command=False): assert isinstance(invoke_without_command, bool) self.invoke_without_command = invoke_without_command def __call__(self, f): def wrapped_f(*args): fn = f for option in reversed(global_options_list): fn = option(f) fn = click.group(
import click from . import __version__ from .count import count from .gc_correct import gc_correct from .newref import newref from .ztest import ztest shared_options = [ click.option("--binsize", "-B", type=click.IntRange(0, None), default=50000, help="Bin size to use. Default = 50000"), click.option("--reference", "-R", type=click.Path(exists=True), required=True, help="Path to reference fasta"), click.option('--bin-file', '-L', type=click.Path(exists=True), required=False, help="Optional path to region BED file"), click.version_option(version=__version__) ] def generic_option(options): """ Decorator to add generic options to Click CLI's The group parent should NOT be decorated with this decorator :param options: list of click.option :return: decorated function """ def __generic_option(func): for option in reversed(options): func = option(func) return func return __generic_option
'verbosity', count=True, type=int, default=1, help='Verbose output'), click.option('-d', 'debug', is_flag=True, default=False, help='enable debug'), click.option('--quiet', '-q', 'verbosity', flag_value=0, help='Minimal output'), click.version_option(version="0.1.0")) class global_options(object): def __init__(self, invoke_without_command=False): assert isinstance(invoke_without_command, bool) self.invoke_without_command = invoke_without_command def __call__(self, f): def wrapped_f(*args): fn = f for option in reversed(global_options_list): fn = option(f) fn = click.group(
#!/usr/bin/env python import logging import pkg_resources import sys import click from click_plugins import with_plugins version_opt = click.version_option( version=pkg_resources.require("lds-bde-loader")[0].version, message=( "LINZ LDS BDE Loader v%(version)s\n" "Copyright (c) 2015 Koordinates Limited.\n" "Open Source Software available under the BSD License." ) ) @with_plugins(ep for ep in list(pkg_resources.iter_entry_points('ldsbde.commands'))) @click.group() @click.option('-v', '--verbose', count=True, help="Increase verbosity (repeat for more)") @click.option('-q', '--quiet', is_flag=True, help="Only produce error output") @version_opt @click.pass_context def main(ctx, verbose, quiet): """ Tool for managing the regular updates of the LINZ BDE data into the LINZ Data Service. """ if quiet: verbose = -1
from .detect.opencv import HaarCascadeDetector from .meme.basic import Meme from .meme.thug import ThugMeme MEME_RESULT_DIR = getcwd() CONTEXT = dict(help_option_names=['-h', '--help']) class Detector(Enum): OPEN_CV = 'opencv' DLIB = 'dlib' _common_decorators = [ click.version_option(None, '-v', '--version'), click.argument('fpath', type=click.Path(exists=True)), click.argument('txt1'), click.argument('txt2'), click.option( '--override', '-o', type=(str, str), multiple=True, help='Override any configuration option: <option_name> <new_value>.'), click.option( '--show-config', is_flag=True, help='Show the configuration and exit. Takes into account -o options.') ]
def get_config(self, config, requested_config_options, requested_command_config_options): application_context = config.get(APPLICATION_CONTEXT) ignore_hidden = any_option_in_sys_argv( FULL_HELP_OPTIONS) or IS_BASH_COMPLETION main_options = prepare_config_options( config, None, get_applicable_options(requested_config_options, application_context), ignore_hidden, disable_required=self.try_to_parse) main_defaults = { translate_param_to_config(option.name): option.default for option in main_options } prog_name = config.get(ENTRYPOINT_NAME, 'zaf') version = config.get(APPLICATION_VERSION) try: main_command = ClickCommandWithConfigOptions( config, command=None, all_commands=requested_command_config_options.keys(), command_config_options=requested_command_config_options, application_context=application_context, ignore_hidden=ignore_hidden, disable_required=self.try_to_parse, name=prog_name, params=main_options, context_settings={'help_option_names': HELP_OPTIONS}) click.version_option(version)(main_command) is_help_or_version = (any_option_in_sys_argv(HELP_OPTIONS) or any_option_in_sys_argv(VERSION_OPTIONS)) if self.try_to_parse: args = [ arg for arg in sys.argv if arg not in HELP_OPTIONS and arg not in VERSION_OPTIONS ][1:] try: # Special call to main that tries to parse the command line main_command.main(args=args, prog_name=prog_name, standalone_mode=False, allow_extra_args=True, ignore_unknown_options=True) except click.exceptions.UsageError: # Continuing and letting load order 100 parsing give a correct error message # This can happen for example for zaf --help because there is no subcommand return [] else: main_command.main(standalone_mode=False, prog_name=prog_name, max_content_width=120) if is_help_or_version: if (any_option_in_sys_argv(HELP_OPTIONS) and not any_option_in_sys_argv(FULL_HELP_OPTIONS)): print() print( 'To see hidden commands and options use --full-help.' ) sys.exit(0) click_config = main_command.created_config defaults = main_defaults.copy() command = main_command while type(command) == ClickCommandWithConfigOptions: defaults.update(command.command_defaults) click_config.update(command.created_config) command = command.executed_command click_config[COMMAND.name] = command.name filtered_config = filter_out_same_as_defaults( click_config, defaults) return ExtensionConfig(filtered_config, priority=CLICK_CONFIG_PRIORITY) except click.exceptions.ClickException as e: logger.debug(e.format_message(), exc_info=True) e.show(file=sys.stdout) exit(2)
# ------------------------------------------------------------------------- global_options_list = ( # General click.option('-v', 'verbosity', count=True, type=int, default=1, help='Verbose output'), click.option('-d', '--debug', 'debug', is_flag=True, default=False, help='enable debug'), click.option('--quiet', '-q', 'verbosity', flag_value=0, help='Minimal output'), click.version_option(version=version) ) class global_options(object): def __init__(self, invoke_without_command=False): assert isinstance(invoke_without_command, bool) self.invoke_without_command = invoke_without_command def __call__(self, f): def wrapped_f(*args): fn = f for option in reversed(global_options_list): fn = option(f)
def addVersionFlag(app): """ Add version flag to given clickObj """ click.version_option(version=app.version, prog_name=settings.NAME)(app.baseGroup.clickObj)
import click from .convert import convert from .dump import dump from .find import find cmd = click.Group() cmd = click.version_option()(cmd) cmd.add_command(dump) cmd.add_command(find) cmd.add_command(convert) def main(): cmd()
'--output_dir', help="output directory", default="./", show_default=True), click.option('-f', '--force', is_flag=True, default=False, help="force to overwrite the output file"), click.option('-l', '--loglevel', default='info', type=click.Choice( ['critical', 'error', 'warning', 'info', 'debug'])), click.version_option(version="0.1.0", prog_name="readcounter", message="%(prog)s, version %(version)s") ] def emit_subcommand_info(subcommand, loglevel): setup_logging(loglevel) _logger.info('invoking {0} subcommand'.format(subcommand)) @click.command() @add_options(shared_options) def fasta(input_file, prefix, output_dir, force, loglevel): emit_subcommand_info("fasta", loglevel) output_file = make_output_file(input_file, prefix,