class DeviceGroup(click.MultiCommand): class Command: def __init__(self, name, decorators, *, default_output=None, **kwargs): self.name = name self.decorators = list(decorators) self.decorators.reverse() self.default_output = default_output self.kwargs = kwargs def __call__(self, func): self.func = func func._device_group_command = self self.kwargs.setdefault("help", self.func.__doc__) def _autodetect_model_if_needed(func): def _wrap(self, *args, **kwargs): skip_autodetect = func._device_group_command.kwargs.pop( "skip_autodetect", False) if (not skip_autodetect and self._model is None and self._info is None): _LOGGER.debug( "Unknown model, trying autodetection. %s %s" % (self._model, self._info)) self._fetch_info() return func(self, *args, **kwargs) # TODO HACK to make the command visible to cli _wrap._device_group_command = func._device_group_command return _wrap func = _autodetect_model_if_needed(func) return func @property def command_name(self): return self.name or self.func.__name__.lower() def wrap(self, ctx, func): gco = ctx.find_object(GlobalContextObject) if gco is not None and gco.output is not None: output = gco.output elif self.default_output: output = self.default_output else: output = format_output("Running command {0}".format( self.command_name)) # Remove skip_autodetect before constructing the click.command self.kwargs.pop("skip_autodetect", None) func = output(func) for decorator in self.decorators: func = decorator(func) return click.command(self.command_name, **self.kwargs)(func) def call(self, owner, *args, **kwargs): method = getattr(owner, self.func.__name__) return method(*args, **kwargs) DEFAULT_PARAMS = [ click.Option(["--ip"], required=True, callback=validate_ip), click.Option(["--token"], required=True, callback=validate_token), click.Option(["--model"], required=False), ] def __init__(self, device_class, name=None, invoke_without_command=False, no_args_is_help=None, subcommand_metavar=None, chain=False, result_callback=None, result_callback_pass_device=True, **attrs): self.commands = getattr(device_class, "_device_group_commands", None) if self.commands is None: raise RuntimeError( "Class {} doesn't use DeviceGroupMeta meta class." " It can't be used with DeviceGroup.") self.device_class = device_class self.device_pass = click.make_pass_decorator(device_class) attrs.setdefault("params", self.DEFAULT_PARAMS) attrs.setdefault("callback", click.pass_context(self.group_callback)) if result_callback_pass_device and callable(result_callback): result_callback = self.device_pass(result_callback) super().__init__(name or device_class.__name__.lower(), invoke_without_command, no_args_is_help, subcommand_metavar, chain, result_callback, **attrs) def group_callback(self, ctx, *args, **kwargs): gco = ctx.find_object(GlobalContextObject) if gco: kwargs["debug"] = gco.debug ctx.obj = self.device_class(*args, **kwargs) def command_callback(self, miio_command, miio_device, *args, **kwargs): return miio_command.call(miio_device, *args, **kwargs) def get_command(self, ctx, cmd_name): if cmd_name not in self.commands: ctx.fail("Unknown command (%s)" % cmd_name) cmd = self.commands[cmd_name] return self.commands[cmd_name].wrap( ctx, self.device_pass(partial(self.command_callback, cmd))) def list_commands(self, ctx): return sorted(self.commands.keys())
"name": sub_command.name.replace("-", "_"), "howcall": howcall, "code": code, "parameters": parameters, }] return callback option_exec_before = click.option( "--exec-before", help="Execute code in the function's global namespace.") for subcommand in subcommands: subcommand.params = [ click.Option(["--autocall/--no-autocall"], is_flag=True, default=True), click.Argument(["code"]), ] subcommand.callback = build_callback(subcommand) subcommand = option_exec_before(subcommand) # TODO: add_cli and add_traversal should be the non-decorator form registry.add_cli(name=subcommand.name)(subcommand) @registry.add_cli(name="reduce") @click.command( "reduce", short_help="Reduce a sequence with a <function>. e.g. `operator.mul`.") @option_exec_before @click.argument("function_name") def _reduce(function_name, **parameters):
def get_click_param( param: inspect.Parameter, ) -> Tuple[Union[click.Argument, click.Option], Any]: # First, find out what will be: # * ParamInfo (ArgumentInfo or OptionInfo) # * default_value # * required default_value = None required = False if isinstance(param.default, ParameterInfo): parameter_info = param.default if parameter_info.default == Required: required = True else: default_value = parameter_info.default elif param.default == Required or param.default == param.empty: required = True parameter_info = ArgumentInfo() else: default_value = param.default parameter_info = OptionInfo() annotation: Any = Any if not param.annotation == param.empty: annotation = param.annotation else: annotation = str main_type = annotation is_list = False parameter_type: Any = None is_flag = None origin = getattr(main_type, "__origin__", None) if origin is not None: # Handle Optional[SomeType] if origin is Union: types = [] for type_ in main_type.__args__: if type_ is NoneType: # type: ignore continue types.append(type_) assert len( types) == 1, "Typer Currently doesn't support Union types" main_type = types[0] origin = getattr(main_type, "__origin__", None) # Handle Tuples and Lists if lenient_issubclass(origin, List): main_type = main_type.__args__[0] assert not getattr( main_type, "__origin__", None ), "List types with complex sub-types are not currently supported" is_list = True elif lenient_issubclass(origin, Tuple): # type: ignore types = [] for type_ in main_type.__args__: assert not getattr( type_, "__origin__", None ), "Tuple types with complex sub-types are not currently supported" types.append( get_click_type(annotation=type_, parameter_info=parameter_info)) parameter_type = tuple(types) if parameter_type is None: parameter_type = get_click_type(annotation=main_type, parameter_info=parameter_info) convertor = None if lenient_issubclass(main_type, Path): convertor = param_path_convertor if lenient_issubclass(main_type, Enum): convertor = generate_enum_convertor(main_type) if convertor and is_list: convertor = generate_iter_convertor(convertor) # TODO: handle recursive conversion for tuples if isinstance(parameter_info, OptionInfo): if main_type is bool and not (parameter_info.is_flag is False): is_flag = True # Click doesn't accept a flag of type bool, only None, and then it sets it # to bool internally parameter_type = None default_option_name = get_command_name(param.name) if is_flag: default_option_declaration = ( f"--{default_option_name}/--no-{default_option_name}") else: default_option_declaration = f"--{default_option_name}" param_decls = [param.name] if parameter_info.param_decls: param_decls.extend(parameter_info.param_decls) else: param_decls.append(default_option_declaration) return ( click.Option( # Option param_decls=param_decls, show_default=parameter_info.show_default, prompt=parameter_info.prompt, confirmation_prompt=parameter_info.confirmation_prompt, hide_input=parameter_info.hide_input, is_flag=is_flag, flag_value=parameter_info.flag_value, multiple=is_list, count=parameter_info.count, allow_from_autoenv=parameter_info.allow_from_autoenv, type=parameter_type, help=parameter_info.help, hidden=parameter_info.hidden, show_choices=parameter_info.show_choices, show_envvar=parameter_info.show_envvar, # Parameter required=required, default=default_value, callback=parameter_info.callback, metavar=parameter_info.metavar, expose_value=parameter_info.expose_value, is_eager=parameter_info.is_eager, envvar=parameter_info.envvar, autocompletion=parameter_info.autocompletion, ), convertor, ) elif isinstance(parameter_info, ArgumentInfo): param_decls = [param.name] nargs = None if is_list: nargs = -1 return ( click.Argument( # Argument param_decls=param_decls, type=parameter_type, required=required, nargs=nargs, # Parameter default=default_value, callback=parameter_info.callback, metavar=parameter_info.metavar, expose_value=parameter_info.expose_value, is_eager=parameter_info.is_eager, envvar=parameter_info.envvar, autocompletion=parameter_info.autocompletion, ), convertor, ) assert False, "A click.Parameter should be returned" # pragma no cover
def test_show_default_string(runner): """When show_default is a string show that value as default.""" opt = click.Option(["--limit"], show_default="unlimited") ctx = click.Context(click.Command("cli")) message = opt.get_help_record(ctx)[1] assert "[default: (unlimited)]" in message
from .mod import SimulationMod return SimulationMod() """ 注入 --signal option: 实现信号模式回测 注入 --slippage option: 实现设置滑点 注入 --commission-multiplier options: 实现设置手续费乘数 注入 --matching-type: 实现选择回测引擎 """ cli_prefix = "mod__sys_simulation__" cli.commands['run'].params.append( click.Option( ('--signal', cli_prefix + "signal"), is_flag=True, default=None, help="[sys_simulation] exclude match engine", )) cli.commands['run'].params.append( click.Option(('-sp', '--slippage', cli_prefix + "slippage"), type=click.FLOAT, help="[sys_simulation] set slippage")) cli.commands['run'].params.append( click.Option(('-cm', '--commission-multiplier', cli_prefix + "commission_multiplier"), type=click.FLOAT, help="[sys_simulation] set commission multiplier")) cli.commands['run'].params.append(
return "" def validate_module(ctx, param, value): if value: try: importlib.import_module(value) except ImportError: raise click.BadParameter( "{param} must be a valid python module import path") return value debug_option = click.Option( param_decls=["--debug"], default=False, is_flag=True, help="Output debug messages (for development)", ) settings_option = click.Option( param_decls=["--settings"], callback=validate_module, help="Django settings module path", ) pythonpath_option = click.Option( param_decls=["--pythonpath"], type=click.Path(exists=True, file_okay=False), help="Add a path to the Python path", )
def test_intrange_default_help_text(runner, type, expect): option = click.Option(["--count"], type=type, show_default=True, default=2) context = click.Context(click.Command("test")) result = option.get_help_record(context)[1] assert expect in result
def _build_param(self, attribute, details): req = details['required'] return click.Option(('--{0}'.format(attribute), ), prompt=req, required=req)
cli_prefix = "mod__stock_realtime__" __config__ = { "priority": 200, "persist_path": "./persist/strategy/", "fps": 3, "redis_uri": None, } cli.commands['run'].params.append( click.Option( ('--redis-uri', cli_prefix + 'redis_uri'), type=click.STRING, help="[stock_realtime] market data redis uri", ) ) @cli.command() @click.argument('redis_url', required=True) def quotation_server(redis_url): """ [stock_realtime] quotation service, download market data into redis Multiple RQAlpha instance can use single market data service. """ import redis import time
# 遵守 Apache License 2.0(下称“Apache 2.0 许可”),您可以在以下位置获得 Apache 2.0 许可的副本:http://www.apache.org/licenses/LICENSE-2.0。 # 除非法律有要求或以书面形式达成协议,否则本软件分发时需保持当前许可“原样”不变,且不得附加任何条件。 # # * 商业用途(商业用途指个人出于任何商业目的使用本软件,或者法人或其他组织出于任何目的使用本软件): # 未经米筐科技授权,任何个人不得出于任何商业目的使用本软件(包括但不限于向第三方提供、销售、出租、出借、转让本软件、本软件的衍生产品、引用或借鉴了本软件功能或源代码的产品或服务),任何法人或其他组织不得出于任何目的使用本软件,否则米筐科技有权追究相应的知识产权侵权责任。 # 在此前提下,对本软件的使用同样需要遵守 Apache 2.0 许可,Apache 2.0 许可与本许可冲突之处,以本许可为准。 # 详细的授权流程,请联系 [email protected] 获取。 import click from rqalpha import cli __config__ = { "order_book_id": None } def load_mod(): from .mod import BenchmarkMod return BenchmarkMod() cli_prefix = "mod__sys_benchmark__" cli.commands["run"].params.append( click.Option( ("-bm", "--benchmark", cli_prefix + "order_book_id"), type=click.STRING, help="[sys_benchmark] order_book_id of benchmark" ) )
def load_mod(): from .mod import AnalyserMod return AnalyserMod() """ --report --output-file """ cli_prefix = "mod__sys_analyser__" cli.commands['run'].params.append( click.Option( ('--report', 'mod__sys_analyser__report_save_path'), type=click.Path(writable=True), help="[sys_analyser] save report" ) ) cli.commands['run'].params.append( click.Option( ('-o', '--output-file', 'mod__sys_analyser__output_file'), type=click.Path(writable=True), help="[sys_analyser] output result pickle file" ) ) cli.commands['run'].params.append( click.Option( ('-p', '--plot/--no-plot', 'mod__sys_analyser__plot'), default=None, help="[sys_analyser] plot result"
def set_debug_value(ctx, value): ctx.ensure_object(ScriptInfo).debug = value def set_app_value(ctx, value): if value is not None: if os.path.isfile(value): value = prepare_exec_for_file(value) elif '.' not in sys.path: sys.path.insert(0, '.') ctx.ensure_object(ScriptInfo).app_import_path = value debug_option = click.Option(['--debug/--no-debug'], help='Enable or disable debug mode.', default=None, callback=set_debug_value) app_option = click.Option(['-a', '--app'], help='The application to run', callback=set_app_value, is_eager=True) class FlaskGroup(click.Group): """Special subclass of the a regular click group that supports loading more commands from the configured Flask app. Normally a developer does not have to interface with this class but there are some very advanced usecases for which it makes sense to create an instance of this.
} def load_mod(): from .mod import AnalyserMod return AnalyserMod() """ --report --output-file """ cli.commands['run'].params.append( click.Option(('--report', 'mod__sys_analyser__report_save_path'), type=click.Path(writable=True), help="[sys_analyser] save report")) cli.commands['run'].params.append( click.Option(('-o', '--output-file', 'mod__sys_analyser__output_file'), type=click.Path(writable=True), help="[sys_analyser] output result pickle file")) cli.commands['run'].params.append( click.Option(('-p', '--plot/--no-plot', 'mod__sys_analyser__plot'), default=None, help="[sys_analyser] plot result")) cli.commands['run'].params.append( click.Option(('--plot-save', 'mod__sys_analyser__plot_save_file'), default=None, help="[sys_analyser] save plot to file"))
def run_params(fn): click_util.append_params( fn, [ click.Argument(("flags", ), metavar="[FLAG=VAL...]", nargs=-1), click.Option(("-l", "--label"), metavar="LABEL", help="Set a label for the run."), click.Option( ("-t", "--tag"), metavar="TAG", help= "Prepend TAG to the default label. Cannot be used with --label.", ), click.Option( ("-e", "--edit-flags"), help="Use an editor to review and modify flags.", is_flag=True, ), click.Option( ( "-d", "--run-dir", ), metavar="DIR", help= ("Use alternative run directory DIR. Cannot be used with --stage." ), ), click.Option( ("--stage", ), help="Stage an operation.", is_flag=True), click.Option( ("--start", "--restart", "restart"), metavar="RUN", help=( "Start a staged run or restart an existing run. Cannot be " "used with --proto or --run-dir."), ), click.Option( ("--proto", ), metavar="RUN", help= ("Use the operation, flags and source code from RUN. Flags may " "be added or redefined in this operation. Cannot " "be used with --restart."), ), click.Option( ("--force-sourcecode", ), is_flag=True, help= ("Use working source code when --restart or --proto is specified. " "Ignored otherwise."), ), click.Option( ("--gpus", ), metavar="DEVICES", help=( "Limit availabe GPUs to DEVICES, a comma separated list of " "device IDs. By default all GPUs are available. Cannot be" "used with --no-gpus."), ), click.Option( ("--no-gpus", ), is_flag=True, help="Disable GPUs for run. Cannot be used with --gpu.", ), click.Option( ( "-bl", "--batch-label", ), metavar="LABEL", help="Label to use for batch runs. Ignored for non-batch runs.", ), click.Option( ( "-bt", "--batch-tag", ), metavar="TAG", help="Tag to use for batch runs. Ignored for non-batch runs.", ), click.Option( ( "-o", "--optimizer", ), metavar="ALGORITHM", help=("Optimize the run using the specified algorithm. See " "Optimizing Runs for more information."), ), click.Option( ( "-O", "--optimize", ), is_flag=True, help="Optimize the run using the default optimizer.", ), click.Option( ( "-N", "--minimize", ), metavar="COLUMN", help=( "Column to minimize when running with an optimizer. See " "help for compare command for details specifying a column. " "May not be used with --maximize."), ), click.Option( ( "-X", "--maximize", ), metavar="COLUMN", help=( "Column to maximize when running with an optimizer. See " "help for compare command for details specifying a column. " "May not be used with --minimize."), ), click.Option( ("-Fo", "--opt-flag", "opt_flags"), metavar="FLAG=VAL", multiple=True, help="Flag for OPTIMIZER. May be used multiple times.", ), click.Option( ( "-m", "--max-trials", ), metavar="N", type=click.IntRange(1, None), help=("Maximum number of trials to run in batch operations. " "Default is optimizer specific. If optimizer is not " "specified, default is 20."), ), click.Option( ("--random-seed", ), metavar="N", type=int, help="Random seed used when sampling trials or flag values.", ), click.Option( ("--debug-sourcecode", ), metavar="PATH", help=("Specify an alternative source code path for debugging. " "See Debug Source Code below for details."), ), click.Option( ("--stage-trials", ), is_flag=True, help=( "For batch operations, stage trials without running them." ), ), click.Option(("-r", "--remote"), metavar="REMOTE", help="Run the operation remotely."), click.Option( ("-y", "--yes"), help="Do not prompt before running operation.", is_flag=True, ), click.Option( ("-f", "--force-flags"), help=("Accept all flag assignments, even for undefined or " "invalid flags."), is_flag=True, ), click.Option( ("--stop-after", ), metavar="N", type=click_util.NUMBER, help="Stop operation after N minutes.", ), click.Option( ("--needed", ), is_flag=True, help=("Run only if there is not an available matching run. " "A matching run is of the same operation with the same " "flag values that is not stopped due to an error."), ), click.Option( ( "-b", "--background", ), is_flag=True, help="Run operation in background.", ), click.Option( ("--pidfile", ), metavar="PIDFILE", help= ("Run operation in background, writing the background process " "ID to PIDFILE."), ), click.Option( ( "-n", "--no-wait", ), help=("Don't wait for a remote operation to complete. Ignored " "if run is local."), is_flag=True, ), click.Option( ("--save-trials", ), metavar="PATH", help= ("Saves generated trials to a CSV batch file. See BATCH FILES " "for more information."), ), click.Option( ("--set-trace", ), help="Enter the Python debugger at the operation entry point.", is_flag=True, ), click.Option( ( "-q", "--quiet", ), help="Do not show output.", is_flag=True), click.Option(("--print-cmd", ), help="Show operation command and exit.", is_flag=True), click.Option( ("--print-env", ), help="Show operation environment and exit.", is_flag=True, ), click.Option( ("--print-trials", ), help="Show generated trials and exit.", is_flag=True, ), click.Option(("--help-model", ), help="Show model help and exit.", is_flag=True), click.Option(("-h", "--help-op"), help="Show operation help and exit.", is_flag=True), click.Option( ("--test-output-scalars", ), metavar="OUTPUT", help= ("Test output scalars on output. Use '-' to read from standard " "intput."), ), click.Option(("--test-sourcecode", ), help="Test source code selection.", is_flag=True), click.Option(("--test-flags", ), help="Test flag configuration.", is_flag=True), ], ) return fn
def _get_option_os(self): return click.Option( ['--os', 'operating_system'], help='Operating System to filter on. Default is windows', default='windows', type=click.Choice(self.SUPPORTED_OS))
print("read", kwargs) class OptionForCommand(click.Option): def __init__(self, *args, for_command, **kwargs): self.for_command = for_command super().__init__(*args, **kwargs) read = SectionedHelpCommand( "read", callback=click.pass_context(read_callback), params=[ click.Argument(["format"], type=click.Choice(["json", "csv"])), click.Option(["--help"], is_flag=True, type=bool), OptionForCommand(["--header/--no-header"], help="Is there a header?", for_command="csv"), OptionForCommand(["--some-json-option"], help="Something about json", for_command="json"), ], add_help_option=False, ) cli.add_command(read) @cli.command(add_help_option=False) @click.argument("format")
domain, seed=seed, show_reward=show_reward, epsilon=epsilon, epsilon_decay=eps_decay, epsilon_min=eps_min, ) else: raise NotImplementedError("Method {} is not supported".format(name)) if __name__ == "__main__": run_experiment( select_domain, select_agent, default_max_steps=10000, default_num_policy_checks=10, default_checks_per_policy=50, other_options=[ click.Option(["--map", "map_"], type=str, default="6x6guided"), click.Option(["--noise"], type=float, default=0.1), click.Option(["--epsilon"], type=float, default=0.1), click.Option(["--epsilon-min"], type=float, default=None), click.Option(["--beta"], type=float, default=0.05), click.Option(["--step-penalty"], type=float, default=0.01), click.Option(["--episode-cap"], type=int, default=40), click.Option(["--vi-threshold"], type=float, default=1e-6), click.Option(["--show-reward"], is_flag=True), ], )
# 检查限价单价格是否合法 "validate_price": True, # 检查标的证券是否可以交易 "validate_is_trading": True, # 检查可用资金是否充足 "validate_cash": True, # 检查股票可平仓位是否充足 "validate_stock_position": True, # 检查期货可平仓位是否充足 "validate_future_position": True, } def load_mod(): from .mod import RiskManagerMod return RiskManagerMod() """ 注入 --short-stock option 可以通过 `rqalpha run --short-stock` 来开启允许股票卖空 """ cli_prefix = "mod__sys_risk__" cli.commands['run'].params.append( click.Option(("--no-short-stock/--short-stock", "mod__sys_risk__validate_stock_position"), is_flag=True, default=True, help="[sys_risk] enable stock shorting"))
def test_suggest_possible_options(runner, value, expect): cli = click.Command( "cli", params=[click.Option(["--bound"]), click.Option(["--count"])]) result = runner.invoke(cli, [value]) assert expect in result.output
def _get_option_output(self): return click.Option( ['--output', '-o', 'output'], help='Output format for the result. Default is json', default='json', type=click.Choice(self.OUTPUT_FORMATS))
def test_flag_duplicate_names(runner): with pytest.raises(ValueError, match="cannot use the same flag for true/false"): click.Option(["--foo/--foo"], default=False)
def _get_option_outdir(self): return click.Option(['--outdir', '-d', 'outdir'], help='Output folder for the result', required=True)
def test_do_not_show_no_default(runner): """When show_default is True and no default is set do not show None.""" opt = click.Option(["--limit"], show_default=True) ctx = click.Context(click.Command("cli")) message = opt.get_help_record(ctx)[1] assert "[default: None]" not in message
def _get_option_bodyfile(self): return click.Option( ['--body', '-b', 'body'], help='body file as output by tsk fls command, with md5 hashes', required=True)
def get_version(ctx, param, value): if not value or ctx.resilient_parsing: return message = 'Flask %(version)s\nPython %(python_version)s' click.echo(message % { 'version': __version__, 'python_version': sys.version, }, color=ctx.color) ctx.exit() version_option = click.Option(['--version'], help='Show the flask version', expose_value=False, callback=get_version, is_flag=True, is_eager=True) class DispatchingApp(object): """Special application that dispatches to a Flask application which is imported by name in a background thread. If an error happens it is recorded and shown as part of the WSGI handling which in case of the Werkzeug debugger means that it shows up in the browser. """ def __init__(self, loader, use_eager_loading=False): self.loader = loader self._app = None self._lock = Lock() self._bg_loading_exc_info = None
def _get_option_nsrl_files(self): return click.Option( ['--nsrl', '-n', 'nsrl'], help='a file in NSRLFile.txt format', required=True, )
def __call__(self, f): # this is the decorator call which registers options in reverse order if self.with_rollback: _param_memo( f, click.Option( ("--rollback", ), is_flag=True, help="Rollback the transaction even if the script " "does not raise an exception. Note that if the " "script itself commits, this option has no effect. " "This is why it is not named dry run. This option " "is implied when an interactive console is " "started.", ), ) _param_memo( f, click.Option( ("--logfile", ), type=click.Path(dir_okay=False), help="Specify the log file.", ), ) _param_memo( f, click.Option( ("--log-level", ), default=self.default_log_level, show_default=True, help="Specify the logging level. Accepted values depend " "on the Odoo version, and include debug, info, " "warn, error.", ), ) if self.with_database: _param_memo( f, click.Option( ("--database", "-d"), envvar=["PGDATABASE"], help="Specify the database name. If present, this " "parameter takes precedence over the database " "provided in the Odoo configuration file.", ), ) if self.with_addons_path: _param_memo( f, click.Option( ("--addons-path", ), envvar=["ODOO_ADDONS_PATH"], help="Specify the addons path. If present, this " "parameter takes precedence over the addons path " "provided in the Odoo configuration file.", ), ) _param_memo( f, click.Option( ("--config", "-c"), envvar=["ODOO_RC", "OPENERP_SERVER"], type=click.Path(exists=True, dir_okay=False), callback=self._register, help="Specify the Odoo configuration file. Other " "ways to provide it are with the ODOO_RC or " "OPENERP_SERVER environment variables, " "or ~/.odoorc (Odoo >= 10) " "or ~/.openerp_serverrc.", ), ) return f
def _get_option_nsrl_folder(self): return click.Option( ['--nsrl', '-n', 'nsrl'], help='path of NSRL files (NSRLFile.txt.zip and NSRLProd.txt)', required=True, )
class DeviceGroup(click.MultiCommand): class Command: def __init__(self, name, decorators, *, default_output=None, **kwargs): self.name = name self.decorators = list(decorators) self.decorators.reverse() self.default_output = default_output self.kwargs = kwargs def __call__(self, func): self.func = func func._device_group_command = self self.kwargs.setdefault('help', self.func.__doc__) return func @property def command_name(self): return self.name or self.func.__name__.lower() def wrap(self, ctx, func): gco = ctx.find_object(GlobalContextObject) if gco is not None and gco.output is not None: output = gco.output elif self.default_output: output = self.default_output else: output = format_output( "Running command {0}".format(self.command_name) ) func = output(func) for decorator in self.decorators: func = decorator(func) return click.command(self.command_name, **self.kwargs)(func) def call(self, owner, *args, **kwargs): method = getattr(owner, self.func.__name__) return method(*args, **kwargs) DEFAULT_PARAMS = [ click.Option(['--ip'], required=True, callback=validate_ip), click.Option(['--token'], required=True, callback=validate_token), ] def __init__(self, device_class, name=None, invoke_without_command=False, no_args_is_help=None, subcommand_metavar=None, chain=False, result_callback=None, result_callback_pass_device=True, **attrs): self.commands = getattr(device_class, '_device_group_commands', None) if self.commands is None: raise RuntimeError( "Class {} doesn't use DeviceGroupMeta meta class." " It can't be used with DeviceGroup." ) self.device_class = device_class self.device_pass = click.make_pass_decorator(device_class) attrs.setdefault('params', self.DEFAULT_PARAMS) attrs.setdefault('callback', click.pass_context(self.group_callback)) if result_callback_pass_device and callable(result_callback): result_callback = self.device_pass(result_callback) super().__init__(name or device_class.__name__.lower(), invoke_without_command, no_args_is_help, subcommand_metavar, chain, result_callback, **attrs) def group_callback(self, ctx, *args, **kwargs): gco = ctx.find_object(GlobalContextObject) if gco: kwargs['debug'] = gco.debug ctx.obj = self.device_class(*args, **kwargs) def command_callback(self, miio_command, miio_device, *args, **kwargs): return miio_command.call(miio_device, *args, **kwargs) def get_command(self, ctx, cmd_name): if cmd_name not in self.commands: ctx.fail('Unknown command (%s)' % cmd_name) cmd = self.commands[cmd_name] return self.commands[cmd_name].wrap(ctx, self.device_pass(partial( self.command_callback, cmd ))) def list_commands(self, ctx): return sorted(self.commands.keys())
# -------------------------------------------------------- # Resize video images # -------------------------------------------------------- @cli.command() @click.option('--input', required=True, type=click.File('r'), help="Path features .pkl") @click.option('--output', required=True, type=click.Path(exists=True), help="Path to output folder (.index, timing.txt)") @click.option('--type', required=True, type=click.Option([ 'Flat', 'PCA80,Flat', 'IVF512,Flat', 'IVF512,SQ4', 'IVF512,SQ8', 'PCAR8,IMI2x10,SQ8' ]), help="FAISS factory type") @click.option('--store-db/--no-store-db', default=True, help='Store result in SQLITE DB') @click.option('--store-index/--no-store-index', default=True, help='Store index?') @click.option('--append/--no-append', default=True, help='Append to timing output file') def train(**kwargs): """Train FAISS options""" fp_pkl = kwargs['features'] fpp_pkl = Path(fpp_pkl)