[英]How can I put typer commands in seperate modules without becoming sub-commands?
這是一個有效但會導致選項 position 靈活性和幫助出現問題的軟糖:
主要文件:
import typer
import mycommand
app = typer.Typer()
app.add_typer(mycommand.app, name='mycommand')
@app.command()
def othercmd():
pass
if __name__ == '__main__':
app()
我的命令.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
運行會將選項加載到文件參數中。
發出main.py mycommand --help
揭示了原因; 在回調選項和 arguments 之后需要一個額外的命令和參數:
Usage: main.py mycommand [OPTIONS] FILES... COMMAND [ARGS]...
Arguments:
FILES... [required]
Options:
--name TEXT
--help Show this message and exit.
有沒有辦法在單獨的模塊中將命令添加到打字機作為“默認”命令,這與使用@app.command()
的反應相同?
顯然有辦法。 不確定這是否是他們打算使用它的方式,但這對大多數人都有效。
主程序
import typer
import mycommand
app = typer.Typer()
app.command()(mycommand.yourcommand)
@app.command()
def othercmd():
pass
if __name__ == '__main__':
app()
你的其他模塊可能如下所示。 打字裝飾器的需求也消失了。
我的命令.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是你可能正在尋找的東西,盡管我已經提出了解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.