構造一個簡單的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已有的包衝突
name = "tclidemo"
version = "0.1.4" # 包版本號 安裝時 最好指定版本安裝 pip install xx==0.1.2
description = ""
authors = ["zy7y <[email protected]>"] [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