我想同时使用几个选项,或者完全不使用,正如标题所说,但是我的方法看起来比较难看,我想知道是否有一种更干净的方法来实现这一点。此外,我还研究了this,关于如何在argparse
中实现它,但是如果可能的话,我想在click
中实现它(我试图避免使用nargs=[...]
)。你知道吗
到目前为止,我得到的是:
@click.group(invoke_without_command=True, no_args_is_help=True)
@click.option(
"-d",
"--group-dir",
type=click.Path(),
default="default",
help='the directory to find the TOML file from which to run multiple jobs at the same time; defaults to the configuration directory of melmetal: "~/.melmetal" on Unix systems, and "C:\\Users\\user\\.melmetal" on Windows',
)
@click.option("-f", "--group-file", help="the TOML file name")
@click.option(
"-n", "--group-name", help="name of the group of jobs"
)
@click.option(
"--no-debug",
is_flag=True,
type=bool,
help="prevent logging from being output to the terminal",
)
@click.pass_context
@logger.catch
def main(ctx, group_dir, group_file, group_name, no_debug):
options = [group_file, group_name]
group_dir = False if not any(options) else group_dir
options.append(group_dir)
if not any(options):
pass
elif not all(options):
logger.error(
colorize("red", "Sorry; you must use all options at once.")
)
exit(1)
else:
[...]
第二个例子是:
if any(createStuff):
if not all(createStuff):
le(
colorize("red", 'Sorry; you must use both the "--config-dir" and "--config-file" options at once.')
)
exit(1)
elif any(filtered):
if len(filtered) is not len(drbc):
le(
colorize("red", 'Sorry; you must use all of "--device", "--repo-name", "--backup-type", and "--config-dir" at once.')
)
exit(1)
else:
ctx = click.get_current_context()
click.echo(ctx.get_help())
exit(0)
当没有给出子命令时,如何获得帮助文本来显示?据我所知,这应该是自动发生的,但对于我的代码,它会自动转到主函数。我的解决方法的一个例子在第二个例子中,即在else
语句下。你知道吗
您可以通过构建从
click.Option
派生的自定义类来强制使用组中的所有选项,并在该类中使用click.Option.handle_parse_result()
方法,如:自定义选项类:
使用自定义类:
要使用自定义类,请将
cls
参数传递给click.option
装饰器,如下所示:另外,给出带有
opt_group
参数的选项组编号。你知道吗这是怎么回事?
这是因为click是一个设计良好的OO框架。
@click.option()
修饰符通常实例化一个click.Option
对象,但允许用cls
参数覆盖此行为。因此,在我们自己的类中从click.Option
继承并超越所需的方法是一件相对容易的事情。你知道吗在本例中,我们跳过
click.Option.handle_parse_result()
,并检查是否指定了组中的其他选项。你知道吗注意:这个答案的灵感来自this answer
测试代码:
结果:
相关问题 更多 >
编程相关推荐