首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用python和typer为类方法编写命令行

使用python和typer为类方法编写命令行
EN

Stack Overflow用户
提问于 2022-01-20 21:49:33
回答 1查看 548关注 0票数 2

我在用

Typer使用python编写命令行程序。

代码

下面是我遇到麻烦的例子脚本。

代码语言:javascript
复制
import typer

app = typer.Typer()

@app.command()
def hello(name):
    typer.echo(f'Hello!')

@app.command()
def goodbye():
    typer.echo(f'Goodbye.')

class Grettings:

    @app.command()
    def aloha(self):
        typer.echo('Aloha!')

    @app.command()
    def bonjour(self):
        typer.echo('Bonjour!')

if __name__ == '__main__':
    app()

当将下列命令输入终端时,就会给出预期的输出。

代码语言:javascript
复制
python main.py hello   
python main.py goodbye

问题

但是,当调用类方法时,我会得到以下异常。

代码语言:javascript
复制
python main.py aloha  
python main.py bonjour

    Usage: main.py aloha [OPTIONS] SELF
    Try 'main.py aloha --help' for help.
    
    Error: Missing argument 'SELF'.

显然,这是因为还没有初始化类。但这似乎是一个常见的问题,所以我认为这个问题有一个简单的解决方案。

研究

我发现的可能解决方案包括在所使用的类/方法上使用装饰器,或者使用需要继承以“公开”类方法的特殊类。

来自回答 of 实例方法的装饰器可以访问类吗?的提示:

在构建类之前调用任何装饰符,因此装饰器不知道。

EN

回答 1

Stack Overflow用户

发布于 2022-01-21 20:44:41

使用修饰实例方法发出

Typer试图以Grettings().aloha()的形式调用回调。这将在Python中失败,错误如下:

TypeError: hallo()缺少一个必需的位置参数:'self‘

Typer中命令调用的演示

请参阅Python中记录的以下演示:

第1部分:它是如何工作的(使用静态函数,没有自变量)

代码语言:javascript
复制
>>> import typer
>>> app = typer.Typer()
>>> app
<typer.main.Typer object at 0x7f0713f59c18>
>>> app.__dict__
{'_add_completion': True, 'info': <typer.models.TyperInfo object at 0x7f0713f59c50>, 'registered_groups': [], 'registered_commands': [], 'registered_callback': None}
>>> @app.command()
... def hello():
...     typer.echo('hello')
... 
>>> app.__dict__['registered_commands']
[<typer.models.CommandInfo object at 0x7f0711e69cf8>]
>>> app.__dict__['registered_commands'][0].cls
<class 'typer.core.TyperCommand'>
>>> app.__dict__['registered_commands'][0].callback
<function hello at 0x7f070f539378>
>>> app.__dict__['registered_commands'][0].callback()
hello

第2部分:它是如何工作的(使用实例方法,需要自变量)

代码语言:javascript
复制
>>> class German:
...     @app.command()
...     def hallo(self):
...         typer.echo('Hallo')
... 
>>> app.__dict__['registered_commands'][1]
<typer.models.CommandInfo object at 0x7f070f59ccf8>
>>> app.__dict__['registered_commands'][1].callback
<function German.hallo at 0x7f070f539158>
>>> app.__dict__['registered_commands'][1].callback()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: hallo() missing 1 required positional argument: 'self'
>>> app.__dict__['registered_commands'][1].callback(German())
Hallo

注意:在最后一条语句I中,一个新实例作为参数self传递给回调,调用成功,并获得预期的输出。

固定码

我改变了三件事:

  1. 将类Grettings重命名为Greetings (拼写)
  2. 将现有的两个方法重新定义为像巴玛尔的评论这样的静态类方法。
  3. 此外,我还添加了一个新的实例方法nihao(self)来演示失败。
代码语言:javascript
复制
import typer

app = typer.Typer()


@app.command()
def hello(name):
    typer.echo(f'Hello!')

@app.command()
def goodbye():
    typer.echo(f'Goodbye.')

class Greetings:
    @app.command()
    def aloha():              # function or class-method (implicitly static)
        typer.echo('Aloha!')

    @staticmethod             # explicitly static
    @app.command()
    def bonjour():            # no self argument!
        typer.echo('Bonjour!')

    @app.command()
    def nihao(self):          # callback invocation fails because missing self argument
        typer.echo('Nihao!')


if __name__ == '__main__':
    app()

行为和预期的输出

虽然所提供的命令仍然将nihao列为可用的,但调用它将与您所经历的一样失败。

但是现在可以调用命令修饰的静态方法。

代码语言:javascript
复制
$ python3 SO_typer.py --help
Usage: SO_typer.py [OPTIONS] COMMAND [ARGS]...

Options:
  --install-completion [bash|zsh|fish|powershell|pwsh]
                                  Install completion for the specified shell.
  --show-completion [bash|zsh|fish|powershell|pwsh]
                                  Show completion for the specified shell, to
                                  copy it or customize the installation.

  --help                          Show this message and exit.

Commands:
  aloha
  bonjour
  goodbye
  hello
  nihao

self在调用时没有传递任何参数,因此️中文问候语失败:

代码语言:javascript
复制
$ python3 SO_typer.py nihao
Usage: SO_typer.py nihao [OPTIONS] SELF
Try 'SO_typer.py nihao --help' for help.

Error: Missing argument 'SELF'.

夏威夷问候语之所以行得通,是因为现在可以进行静态调用:

代码语言:javascript
复制
$ python3 SO_typer.py aloha
Aloha!

另请参阅

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70793842

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档