python 如何将typer命令放在单独的模块中而不变成子命令?

qoefvg9y  于 2023-05-05  发布在  Python
关注(0)|答案(1)|浏览(121)

这里是一个工作,但导致期权位置灵活性和帮助问题的软糖:

  • main.py:*
import typer
import mycommand
app = typer.Typer()
app.add_typer(mycommand.app, name='mycommand')
@app.command()
def othercmd():
    pass
if __name__ == '__main__':
    app()
  • mycommand.py:*
from typing import List
import typer
app = typer.Typer()
@app.callback(invoke_without_command=True)   # Not a sub command - run this by default
def mycommand(files: List[str] = typer.Argument(...), name: str = typer.Option(None)):
    if name: print(f'Hello {name}')
    print(files)

现在可以使用python main.py mycommand --name Butty myfile.txt运行此命令。但是,尝试使用python main.py mycommand myfile.txt --name Butty运行时,会将该选项加载到files参数中。
发布main.py mycommand --help揭示了原因;在回调选项和参数之后需要一个额外的命令和参数:

Usage: main.py mycommand [OPTIONS] FILES... COMMAND [ARGS]...

Arguments:
  FILES...  [required]

Options:
  --name TEXT
  --help       Show this message and exit.

有没有一种方法可以在一个单独的模块中添加一个命令作为“默认”命令,它的React与使用@app.command()相同?

kninwzqo

kninwzqo1#

显然有办法。不确定这是否是他们的本意,但这对大多数人都有效。

  • main.py*
import typer
import mycommand

app = typer.Typer()

app.command()(mycommand.yourcommand)

@app.command()
def othercmd():
    pass

if __name__ == '__main__':
    app()

您的其他模块可能如下所示。对打字员的需求也消失了。

  • mycommand.py*
from typing import List
import typer

def yourcommand(files: List[str] = typer.Argument(...), name: str = typer.Option(None)):
    if name: print(f'Hello {name}')
    print(files)

这篇Github Issue Post可能是你想要的,尽管我已经给出了解决方案。

相关问题