用 Python Click 编写的 CLI 响应缓慢

ler*_*ygr 7 python setuptools anaconda conda python-click

我在 Python 3.6.6(在 conda 环境下)上使用 Click 7.0 编写的 CLI 响应缓慢。

使用 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
Run Code Online (Sandbox Code Playgroud)

但是,直接从源调用 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
Run Code Online (Sandbox Code Playgroud)

以下是内容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()
Run Code Online (Sandbox Code Playgroud)

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,
)
Run Code Online (Sandbox Code Playgroud)

有人可以帮我解决这个问题吗?对于 CLI 来说,这真的很不方便。

Jor*_*ter 0

对于小型 Python CLI,这种延迟非常明显。它与 setuptools 围绕 CLI 端点创建的包装器有关。它通过您的端点实现一些辅助功能,例如检查您的(虚拟)python 环境是否具有所有必需的依赖项。

人们已经创建了使用fast-entry_points等工具来规避这些辅助功能的解决方案。检查一下,它可能适合您的用例。

注意:对于小型 CLI,这种速度提升最为明显。如果您有较大的 CLI/项目,则需要将导入构建为本地导入,以防止在执行特定操作时加载所有导入。特别是在 CLI 上使用自动完成功能时,可能值得更改导入。