启动应用程序
您可以使用 typer.launch()
从 CLI 程序启动应用程序。
它将根据您传递的 URL 或文件类型启动相应的应用程序
import typer
def main():
print("Opening Typer's docs")
typer.launch("https://typer.fastapi.org.cn")
if __name__ == "__main__":
typer.run(main)
检查它
$ python main.py
Opening Typer docs
// Opens browser with Typer's docs
定位文件¶
您还可以使用 locate=True
让操作系统打开文件浏览器,指示文件所在位置
from pathlib import Path
import typer
APP_NAME = "my-super-cli-app"
def main():
app_dir = typer.get_app_dir(APP_NAME)
app_dir_path = Path(app_dir)
app_dir_path.mkdir(parents=True, exist_ok=True)
config_path: Path = Path(app_dir) / "config.json"
if not config_path.is_file():
config_path.write_text('{"version": "1.0.0"}')
config_file_str = str(config_path)
print("Opening config directory")
typer.launch(config_file_str, locate=True)
if __name__ == "__main__":
typer.run(main)
提示
此示例中其余代码只是确保应用程序目录存在并创建配置文件。
但最重要的部分是 typer.launch(config_file_str, locate=True)
,其中参数 locate=True
。
检查它
$ python main.py
Opening config directory
// Opens a file browser indicating where the config file is located