gpt4 book ai didi

python-click:依赖于另一个选项的选项

转载 作者:太空狗 更新时间:2023-10-30 02:51:31 24 4
gpt4 key购买 nike

这个问题是关于 click 的包:我想设置我的命令,以便某些 optional 依赖于特定的选项值,并且根据其值是必需的。

必需选项:

  1. 输入(输入文件)
  2. doe(整数,代表算法名称)

子选项:如果母鹿是

  1. 等于1 那么option generator_string 应该变成required=True
  2. 等于2 那么option number_of_sample_points应该变成required=True
  3. 等于3 那么option number_of_center_points应该变成required=True

有效示例:

  1. --input ./input.txt --doe 1 --generator_string 1234
  2. --input ./input.txt --doe 2 --number_of_sample_points 3
  3. --input ./input.txt --doe 3 --number_of_center_points 2

代码:

import click


def check_output(ctx, param, value):
if value == 1:
if not ctx.params['generator_string']:
setOptionAsRequired(ctx, 'generator_string')
return value


def setOptionAsRequired(ctx, name):
for p in ctx.command.params:
if isinstance(p, click.Option) and p.name == name:
p.required = True


@click.option('--input', required=True, type=click.Path(exists=True) )
@click.option('--doe', required=True, type=int, callback=check_output )
@click.option('--generator_string', required=False, type=str, is_eager=True)
@click.option('--number_of_sample_points', required=False, type=int, is_eager=True)
@click.option('--number_of_center_points', required=False, type=int, is_eager=True)
@click.command(context_settings=dict(max_content_width=800))
def main(input, doe, generator_string, number_of_sample_points, number_of_center_points):
click.echo('is valid command')

if __name__ == '__main__':
main()

最佳答案

我建议使用自定义 click.Command 类来做到这一点,例如:

自定义类:

def command_required_option_from_option(require_name, require_map):

class CommandOptionRequiredClass(click.Command):

def invoke(self, ctx):
require = ctx.params[require_name]
if require not in require_map:
raise click.ClickException(
"Unexpected value for --'{}': {}".format(
require_name, require))
if ctx.params[require_map[require].lower()] is None:
raise click.ClickException(
"With {}={} must specify option --{}".format(
require_name, require, require_map[require]))
super(CommandOptionRequiredClass, self).invoke(ctx)

return CommandOptionRequiredClass

使用自定义类

required_options = {
1: 'generator_string',
2: 'number_of_sample_points',
3: 'number_of_center_points',
}

@click.command(cls=command_required_option_from_option('doe', required_options))
...

这是如何运作的?

之所以可行,是因为 click 是一个设计良好的 OO 框架。 @click.command() 装饰器通常实例化一个 click.Command 对象,但允许使用 cls 参数覆盖此行为。因此,在我们自己的类中继承 click.Command 并覆盖所需的方法是一件相对容易的事情。

在这种情况下,我们重写 click.Command.invoke(),然后在运行命令之前验证是否已设置所需的选项

测试代码:

import click

required_options = {
1: 'generator_string',
2: 'number_of_sample_points',
3: 'number_of_center_points',
}

@click.command(context_settings=dict(max_content_width=800),
cls=command_required_option_from_option('doe', required_options))
@click.option('--input', required=True,
type=click.Path(exists=True))
@click.option('--doe', required=True, type=int)
@click.option('--generator_string', required=False, type=str, is_eager=True)
@click.option('--number_of_sample_points', required=False, type=int,
is_eager=True)
@click.option('--number_of_center_points', required=False, type=int,
is_eager=True)
def main(input, doe, generator_string, number_of_sample_points,
number_of_center_points):
click.echo('input: {}'.format(input))
click.echo('doe: {}'.format(doe))
click.echo('generator_string: {}'.format(generator_string))
click.echo('Num of sample_points: {}'.format(number_of_sample_points))
click.echo('Num of center_points: {}'.format(number_of_center_points))


if __name__ == "__main__":
commands = (
'--input ./input.txt --doe 0',
'--input ./input.txt --doe 1',
'--input ./input.txt --doe 2',
'--input ./input.txt --doe 3',
'--input ./input.txt --doe 1 --generator_string 1234',
'--input ./input.txt --doe 2 --number_of_sample_points 3',
'--input ./input.txt --doe 3 --number_of_center_points 2',
'',
'--help',
)

import sys, time

time.sleep(1)
print('Click Version: {}'.format(click.__version__))
print('Python Version: {}'.format(sys.version))
for cmd in commands:
try:
time.sleep(0.1)
print('-----------')
print('> ' + cmd)
time.sleep(0.1)
main(cmd.split())

except BaseException as exc:
if str(exc) != '0' and \
not isinstance(exc, (click.ClickException, SystemExit)):
raise

结果:

Click Version: 6.7
Python Version: 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) [MSC v.1900 64 bit (AMD64)]
-----------
> --input ./input.txt --doe 0
Error: Unexpected value for --'doe': 0
-----------
> --input ./input.txt --doe 1
Error: With doe=1 must specify option --generator_string
-----------
> --input ./input.txt --doe 2
Error: With doe=2 must specify option --number_of_sample_points
-----------
> --input ./input.txt --doe 3
Error: With doe=3 must specify option --number_of_center_points
-----------
> --input ./input.txt --doe 1 --generator_string 1234
input: ./input.txt
doe: 1
generator_string: 1234
Num of sample_points: None
Num of center_points: None
-----------
> --input ./input.txt --doe 2 --number_of_sample_points 3
input: ./input.txt
doe: 2
generator_string: None
Num of sample_points: 3
Num of center_points: None
-----------
> --input ./input.txt --doe 3 --number_of_center_points 2
input: ./input.txt
doe: 3
generator_string: None
Num of sample_points: None
Num of center_points: 2
-----------
>
Usage: test.py [OPTIONS]

Error: Missing option "--input".
-----------
> --help
Usage: test.py [OPTIONS]

Options:
--input PATH [required]
--doe INTEGER [required]
--generator_string TEXT
--number_of_sample_points INTEGER
--number_of_center_points INTEGER
--help Show this message and exit.

关于python-click:依赖于另一个选项的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55584012/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com