python - 属性错误: 'function' object has no attribute 'name' when using Click to create Hierarchical command groups

标签 python command-line-interface python-click

我正在尝试使用分层命令创建命令行应用程序(我的子命令将有子命令)。但是,当我尝试一个非常基本的应用程序时,我收到一个 AttributeError

我可以用一个简单的例子来复制这个。

目录布局:

.
├── cli.py
└── commands
    ├── config_cmds.py
    ├── __init__.py

cli.py

# -*- coding: utf-8 -*-

import sys
import click


from commands.config_cmds import configcmd

@click.group()
@click.version_option()
def cli(args=None):
    """A command line application"""
    return 0

cli.add_command(configcmd)


if __name__ == "__main__":
    sys.exit(cli())  # pragma: no cover

config_cmds.py

import click

@click.group
@click.version_option()
def configcmd():
    """Configuration management for this CLI"""
    click.echo("In config")

如果我运行此应用程序,则会收到以下错误:

$ python cli.py
Traceback (most recent call last):
  File "cli.py", line 15, in <module>
    cli.add_command(configcmd)
  File "/home/frank/.virtualenvs/clitest/lib/python3.6/site-packages/click/core.py", line 1221, in add_command
    name = name or cmd.name
AttributeError: 'function' object has no attribute 'name'

我的目录结构是基于this设置的回答。

我使用的是 python 3.6 和 Click 版本 7.0。

如何解决此属性错误,以便可以拥有命令层次结构并将命令拆分为多个文件?

最佳答案

您需要调用 click.group() 装饰器,例如:

@click.group()
@click.version_option()
def configcmd():
    """Configuration management for this CLI"""
    click.echo("In config")

测试代码:

import sys
import click

from commands.config_cmd import configcmd


@click.group()
@click.version_option()
def cli(args=None):
    """A command line application"""
    return 0


cli.add_command(configcmd)


@configcmd.command()
def test_cmd():
    click.echo('In test_cmd')


if __name__ == "__main__":
    commands = (
        'configcmd test_cmd',
        'configcmd --help',
        '--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)
            cli(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)]
-----------
> configcmd test_cmd
In config
In test_cmd
-----------
> configcmd --help
Usage: test.py configcmd [OPTIONS] COMMAND [ARGS]...

  Configuration management for this CLI

Options:
  --version  Show the version and exit.
  --help     Show this message and exit.

Commands:
  test_cmd
-----------
> --help
Usage: test.py [OPTIONS] COMMAND [ARGS]...

  A command line application

Options:
  --version  Show the version and exit.
  --help     Show this message and exit.

Commands:
  configcmd  Configuration management for this CLI
-----------
> 
Usage: test.py [OPTIONS] COMMAND [ARGS]...

  A command line application

Options:
  --version  Show the version and exit.
  --help     Show this message and exit.

Commands:
  configcmd  Configuration management for this CLI

关于python - 属性错误: 'function' object has no attribute 'name' when using Click to create Hierarchical command groups,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55996487/

相关文章:

python - 通过使用 Foo() 参数运行子命令,在主单击组命令上实例化 Foo() 类

python - 如何使用 click、coverage.py 和 Tox 测试 Python CLI 程序?

python - 如何使用递归通过将集合拆分为第一个和其余部分来获取子集(python)

bash - 通过 CLI 在 AWS ECS 上停止任务(程序输出作为参数输入 bash)

python - 打字机-cli : How to use custom data type with typer

node.js - Knexfile不读取环境变量?

amazon-web-services - 使用 aws cli 将带有元数据的项目上传到 Amazon S3 存储桶

python - 使用 pip 在 python 3.5 和 virtualenv 上安装 twisted

python - 如何将两个数据帧与 'wildcards' 合并?

python - matlab 到 python : get matlab cell array values