python - 使用 click 时主函数的命令行参数

标签 python arguments python-click

我有这段代码可以正常工作:

import click

@click.command(context_settings=dict(help_option_names=['-h', '--help']))
@click.option('--team_name', required=True, help='Team name')
@click.option('--input_file', default='url_file.txt', help='Input file name for applications, URLs')
@click.option('--output_file', default='test_results_file.txt', help='Output file name to store test results')
def main(team_name, input_file, output_file):
    # function body

if __name__ == '__main__':
    main()                  # how does this work?

如您所见,main 被调用时没有参数,尽管它应该接收三个参数。这是如何工作的?

最佳答案

正如评论中所提到的,这是由装饰者处理的。 click.command 装饰器将函数转换为 click.Command 的实例。

每个选项装饰器构建一个 click.Option 实例并将其附加到 click.Command 对象以供稍后使用。

这个click.Command 对象实现了一个__call__ method这是通过调用 main() 来调用的。

def __call__(self, *args, **kwargs):
    """Alias for :meth:`main`."""
    return self.main(*args, **kwargs)

它非常简单,只需调用 click.Command.main() .

click.Command.main() 的顶部附近是:

if args is None:
    args = get_os_args()
else:
    args = list(args)

此代码从命令行获取 argv 或使用提供的 args 列表。此方法中的进一步代码将命令行解析为上下文,以及最终的 calling of your main()。使用之前构建的 click.Option 实例的值:

with self.make_context(prog_name, args, **extra) as ctx:
    rv = self.invoke(ctx)

这就是神秘的 3 个论点的来源。

关于python - 使用 click 时主函数的命令行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57045515/

相关文章:

python - 如何将 OCSP 支持添加到 Python 请求库中?

python - 印度银行 IFSC 代码的正则表达式

python - 查找列表中包含的字符的位置

javascript - 在 javascript/jquery 中传递可选参数

r - rlang::fn_fmls() 可以嵌套吗?

go - 传递变量作为 exec.Command() 的参数

python - 使用每个类的 ImageDataGenerator 仅使用 N 个图像

python - 使用 Python click 调用另一个子命令似乎无法验证字段

python 点击​​命令的详细帮助

python - 如何在 Python Click 中将选项的默认值设置为另一个参数?