我希望 Typer 按照我初始化的顺序显示我的命令,并且它按字母顺序显示这些命令。 我尝试了不同的方法,包括这个:https://github.com/tiangolo/typer/issues/246 在此我得到断言错误。其他人喜欢子类化一些 Typer 和 click 类,但实际上没有任何作用。
简化代码:
import typer
import os
app = typer.Typer()
@app.command()
def change_value(file_name, field):
print("Here I will change the", file_name, field)
@app.command()
def close_field(file_name, field):
print("I will close field")
@app.command()
def add_transaction(file_name):
print("I will add the transaction")
if __name__ == "__main__":
app()
请帮忙:)
编辑: 根据 @Barmar 的请求,我添加了根据打字机创建者的方法改编的代码及其抛出的错误:
代码:
import typer
import click
from click import Context
from typing import Iterable
class OrderedCommands(click.Group):
def list_commands(self, ctx: Context) -> Iterable[str]:
return self.commands.keys()
app = typer.Typer(cls=OrderedCommands)
@app.command()
def change_value(file_name, field):
print("Here I will change the", file_name, field)
@app.command()
def close_field(file_name, field):
print("I will close field")
@app.command()
def add_transaction(file_name):
print("I will add the transaction")
if __name__ == "__main__":
app()
好吧,我在其他地方找到了解决方案,同时尝试将票发布到 Typer(他们有非常全面的故障排除!)
https://github.com/tiangolo/typer/issues/428
按照我希望的显示顺序显示命令的应用程序如下所示:
import typer
from click import Context
from typer.core import TyperGroup
class OrderCommands(TyperGroup):
def list_commands(self, ctx: Context):
return list(self.commands) # get commands using self.commands
app = typer.Typer(
cls=OrderCommands,
no_args_is_help=True
)
@app.command()
def change_value(file_name, field):
# TODO: get the row of the field from the name or ask about it if the name is correct, but the row is not specified
# TODO: ask for the value if the field is verified
print("Here I will change the", file_name, field)
@app.command()
def close_field(file_name, field):
print("I will close field")
@app.command()
def add_transaction(file_name):
print("I will add the transaction")
if __name__ == "__main__":
app()