沉冰浮水

沉冰浮水

做最终到的事,成为最终成为的人!
github
bilibili
mastodon
zhihu
douban

「折騰」Docker + pipenv 運行 Python 專案

前言#

「筆記」和「操作手冊」應該怎麼區分呢?

正文#

有一些使用 Github Actions 跑 Python 的專案,其中一種方案是使用 Docker + pipenv,後者是 Python 的套件管理工具,類似於 npm;

本文將記錄如何在自建 Linux 環境使用該方案……

# 克隆專案
GIT_PATH=~/Git
git clone [email protected]:VaultVulp/action-pipenv.git $GIT_PATH/action-pipenv

# 構建 Docker 鏡像
cd $GIT_PATH/action-pipenv
docker build -t py-pipenv .

・執行 mkdir -p ~/test/py-pipenv 創建測試目錄,然後在該目錄下創建main.py文件,內容如下:

import json
import feedparser
import pprint

# 讀取 rss
rss_list = feedparser.parse('https://www.wdssmq.com/feed.php')
# 提取標題和鏈接
rlt_list = [{'title': entry['title'], 'link':entry['link']} for entry in rss_list['entries']]
# 打印結果
pprint.pprint(rlt_list)
# 保存為 json 文件
with open('output.json', 'w') as f:
    json.dump(rlt_list, f)

・在該目錄下創建Pipfile文件,內容如下:

[[source]]
url = "https://pypi.org/simple"
verify_ssl = true
name = "pypi"

[scripts]
main = "python main.py"

[packages]
feedparser = "*"
# 運行之構建虛擬環境(virtualenv)
PY_DIR=~/test/py-pipenv
ENVS_DIR=${PY_DIR}/virtualenvs
docker run --name py-run \
    --rm \
    --workdir /app \
    -v ${PY_DIR}:/app \
    -v ${ENVS_DIR}/:/root/.local/share/virtualenvs \
    py-pipenv \
    "install -d"

・在${PY_DIR}內會生成virtualenvs目錄,其中包含了虛擬環境的相關文件,在 Pipfile 內依賴項不變的情況下只需要執行一次構建;

# 運行實際代碼
PY_DIR=~/test/py-pipenv
ENVS_DIR=${PY_DIR}/virtualenvs
docker run --name py-run \
    --rm \
    --workdir /app \
    -v ${PY_DIR}:/app \
    -v ${ENVS_DIR}/:/root/.local/share/virtualenvs \
    py-pipenv \
    "run main"

・相當於執行了pipenv run main,在${PY_DIR}內會生成output.json文件;

補充#

  • --rm 參數表示運行完畢後自動刪除容器;
  • --workdir 指定工作目錄;
  • -v 掛載目錄到容器內;
  • py-pipenv 是前邊構建鏡像指定的名稱;
  • "install -d""run main" 將作為參數傳遞給容器內的 pipenv 命令;

相關鏈接#

「小事」Python 的 Docker 鏡像更新了一波_雜七雜八_沉冰浮水:

https://www.wdssmq.com/post/20210820542.html

VaultVulp/action-pipenv: Use pipenv commands in your GitHub Actions Workflow:

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。