在Python 3.6.6上使用Click 7.0编写的CLI(在conda环境下(响应缓慢。
使用pip(使用setuptools(安装软件包后,调用CLI时需要打印帮助消息:
$ time cli
Usage: cli [OPTIONS] COMMAND [ARGS]...
Welcome in the CLI!
Options:
--version Show the version and exit.
--help Show this message and exit.
real 0m0,523s
user 0m0,482s
sys 0m0,042s
然而,当直接从以下来源调用CLI时,我不会有这种滞后:
$ time python myproject/cli.py
Usage: cli.py [OPTIONS] COMMAND [ARGS]...
Welcome in the CLI!
Options:
--version Show the version and exit.
--help Show this message and exit.
real 0m0,088s
user 0m0,071s
sys 0m0,016s
以下是myproject/cli.py
:的内容
import click
@click.group('cli', invoke_without_command=True)
@click.pass_context
@click.version_option(version='0.0.1', prog_name="test")
def cli(ctx):
"""
Welcome in the CLI!
"""
if ctx.invoked_subcommand is None:
# show help if no option passed to cli
if all(v==False for v in ctx.params.values()):
click.echo(ctx.get_help())
if __name__ == '__main__':
cli()
setup.py的配置如下:
setup(
name=name,
version=__version__,
packages=find_packages(),
install_requires=install_requires,
author=author,
author_email=author_email,
description=description,
entry_points='''
[console_scripts]
cli=myproject.cli:cli
''',
keywords=keywords,
cmdclass=cmdclass,
include_package_data=True,
)
有人能帮我吗?对于CLI来说,获得这样的滞后真的很不方便。
对于小型Python CLI,这种延迟非常值得注意。这与setuptools围绕CLI端点创建的包装器有关。它通过端点实现了一些辅助功能,比如检查(虚拟(python环境是否具有所有必需的依赖项。
人们已经创建了一些解决方案,用诸如快速入口点之类的工具来规避这些辅助功能。看看它,它可能适合你的用例。
注意:这种速度的提高对于小型CLI最为明显。如果您有更大的CLI/Project,则需要将导入结构为本地导入,以防止在执行特定操作时加载所有导入。尤其是在CLI上使用auto-complete时,可能还需要更改导入。