我有这段代码可以正常工作:
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/