🧾 問題一:ModuleNotFoundError: No module named 'jenkins'
🔍 現象:
在本地運行正常,但在 Jenkins 中運行腳本時報錯,提示找不到 jenkins
模塊。
? 原因分析:
- Python 默認只從當前目錄或已安裝包中查找模塊。
- Jenkins 執行腳本時的工作路徑可能不是項目根目錄。
from jenkins.config_manager import load_config
這種導入方式要求 Python 能找到jenkins
目錄,但默認情況下不會自動加入。
? 推薦解決方案:
方案一:在 Jenkins Pipeline 中設置 PYTHONPATH
bat '''@echo oncd /d "%WORKSPACE%"set PYTHONPATH=%WORKSPACE%.venv\\Scripts\\python.exe jenkins\\notification_sender.py
'''
??
%WORKSPACE%
是 Jenkins 內置變量,指向任務的工作空間根目錄。
方案二:在腳本中動態添加路徑(適用于調試或臨時使用)
import sys
import oscurrent_script_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(current_script_dir)
if project_root not in sys.path:sys.path.insert(0, project_root)from jenkins.config_manager import load_config
🧾 問題二:download_apk
路徑不一致導致文件分散
🔍 現象:
下載目錄一會出現在項目根目錄下,一會出現在 jenkins/
目錄下,導致重復下載、清理混亂。
? 原因分析:
- 使用了相對路徑
os.getcwd()
,而該函數返回的是當前執行命令所在的目錄。 - 如果從不同位置運行腳本,
download_dir
的路徑會不同。
? 推薦解決方案:
統一使用腳本所在目錄定位 download_apk
代碼如下:
# 獲取當前腳本目錄
current_script_dir = os.path.dirname(os.path.abspath(__file__))
download_dir = os.path.join(current_script_dir, "..", "download_apk")
這樣無論你從哪里運行腳本,[download_apk]都會固定在項目根目錄下。
? 總結:避免這些問題的最佳實踐
問題 | 最佳實踐 | 工具支持 |
---|---|---|
模塊導入錯誤 (No module named 'jenkins' ) | 設置 PYTHONPATH 或動態添加 sys.path | Jenkins Pipeline + Python |
下載目錄路徑不一致 | 使用 __file__ 定位絕對路徑 | Python 腳本內部處理 |
📌 最推薦的組合方案(Jenkins + Python)
Jenkinsfile 中的標準 bat 執行模板:
pipeline {agent anystages {stage('Run Script') {steps {script {bat '''@echo oncd /d "%WORKSPACE%"set PYTHONPATH=%WORKSPACE%.venv\\Scripts\\python.exe jenkins\\your_script.py'''}}}}
}
Python 腳本中標準路徑處理邏輯:
import os
import sys# 獲取當前腳本所在目錄
current_script_dir = os.path.dirname(os.path.abspath(__file__))
# 添加項目根目錄到 sys.path
project_root = os.path.dirname(current_script_dir)
if project_root not in sys.path:sys.path.insert(0, project_root)# 設置下載目錄為項目根目錄下的 download_apk
download_dir = os.path.join(project_root, 'download_apk')
📝 附加建議:
- 保持工作空間一致性
- Jenkins 中盡量通過
cd /d "%WORKSPACE%"
固定工作目錄。
- Jenkins 中盡量通過
- 使用虛擬環境
- 使用
.venv
確保依賴隔離。
- 使用
- 日志輸出清晰化
- 添加打印語句確認當前工作目錄和模塊路徑:
print("Current working dir:", os.getcwd()) print("sys.path:", sys.path)
- 添加打印語句確認當前工作目錄和模塊路徑: