構造一個簡單的CLI程序
typer
這個從去年就被各種營銷號吹成Web框架的 第三方庫, 與 FastAPI 同出一人之手,它不是Web框架,它是一個用來構建CLI程序的庫,我們就簡單搞個例子
# 更多用法,看文檔
import typer
# 實例一下
app = typer.Typer()
# 加到命令組中 hello
@app.command()
def hello(name: str):
typer.echo(f"Hello {name}")
# 加到命令組中 goodbye 接收 一個必要參數name, --formal 可修改默認值參數
@app.command()
def goodbye(name: str, formal: bool = False):
if formal:
typer.echo(f"Goodbye Ms. {name}. Have a good day.")
else:
typer.echo(f"Bye {name}!")
poetry
依賴環境和包管理器,個人覺得最大的亮點就是可以直接打包發布到PyPi上
pip install poetry 進行安裝
# 常用命令
1. 在已有項目中初始化(圖方便就一直回車): poetry init
2. 完全初始化一個項目: poetry new 項目名
# 上述內容 一路回車之后 得到一個pyproject.toml文件
3. 添加依賴庫並安裝: poetry add typer
... 其他命令 ... 各位自己翻文檔吧
正片開始
-
新建一個目錄
tclidemo
-
poetry init
一路回車 -
poetry add typer
安裝typer -
目錄下新建一個同名的包(也可不同名)
-
在
包
里面新建一個main.py
內容就是上面typer
中的內容 -
pyproject.toml
添加[tool.poetry.scripts]
后如下[tool.poetry] # 這個name 必須和 我們要打包那個目錄一個名稱,且不能和pypi(曾經有和現在有的包)重名 # https://pypi.org/help/#file-name-reuse name = "tclidemo" version = "0.1.4" # 包版本號 安裝時 最好指定版本安裝 pip install xx==0.1.2 description = "" authors = ["zy7y <xxxxxxx@163.com>"] [tool.poetry.dependencies] python = "^3.9" typer = "^0.4.0" [tool.poetry.dev-dependencies] [build-system] requires = ["poetry-core>=1.0.0"] build-backend = "poetry.core.masonry.api" [tool.poetry.scripts] # 前面是命令 開頭 , = 后面是 指定typer實例, 對應的就是 打包包名.模塊名(main.py文件).typer對象名 tdo = 'tclidemo.main:app'
-
打包&上傳pypi
PyPI · The Python Package Index
# 執行后在當前目錄下生成一個dist目錄,poetry 和 npm 命令還差不多.... poetry build (venv) E:\coding\tree-cli>poetry build Building tclidemo (0.1.4) - Building sdist - Built tclidemo-0.1.4.tar.gz - Building wheel - Built tclidemo-0.1.4-py3-none-any.whl # 上傳 poetry publish # 之后會要求輸入 pypi 的賬號密碼(沒有的先去注冊 https://pypi.org/) (venv) E:\coding\tree-cli>poetry publish Username: zy7y Password: Publishing tclidemo (0.1.4) to PyPI - Uploading tclidemo-0.1.4-py3-none-any.whl 0% - Uploading tclidemo-0.1.4-py3-none-any.whl 100% - Uploading tclidemo-0.1.4-py3-none-any.whl 100% - Uploading tclidemo-0.1.4.tar.gz 0% - Uploading tclidemo-0.1.4.tar.gz 100% - Uploading tclidemo-0.1.4.tar.gz 100%
-
如果沒報錯,那就穩了,新起個虛擬環境
python -m venv venv
# 安裝上傳的包 , 如果確實上傳了裝不上 最好等個一分鍾哦 pip install tclidemo==0.1.4 # 執行tdo --help tdo --help
(venv) C:\Users\win10\Desktop\apiAutoTest>tdo --help Usage: tdo [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: goodbye hello
最后
兩個庫官方文檔如下,更多用法等你發掘。 可以試試 pip install tclidemo==0.1.4 哦
https://typer.tiangolo.com/ # typer
https://python-poetry.org/docs/ # poetry
參考文檔:https://click-docs-zh-cn.readthedocs.io/zh/latest/setuptools.html