Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Buildout 實戰:可重複、跨平台的環境建置工具

關於 Buildout

Buildout 由 Zope 公司的 Jim Fulton 開發,主要用途是管理並組裝新的應用程式,對象不限於 Python 程式,Apache 這類服務同樣適用。它的核心目標是打造可重複、跨平台的建置流程:透過一份設定檔,就能把多個元件組裝、部署成完整應用,即使其中摻雜非 Python 的元件也難不倒它。能力上,它既能像 setuptools 那樣自動下載並更新相依套件,也能像 virtualenv 那樣提供封閉隔離的開發環境。

使用 Buildout

它非常聰明,你只需要準備兩樣東西:一份最新的 bootstrap.py,以及一個帶有 "recipes" 或 "eggs" 設定的 buildout.cfg。

bootstrap.py 下載:https://svn.zope.org/*checkout*/zc.buildout/trunk/bootstrap/bootstrap.py

具體步驟如下。

1. 建立開發目錄 demo-buildout,並建立設定檔:

#mkdir demo-buildout
#cd demo-buildout
#touch buildout.cfg

2. 下載引導腳本並執行,產生相關檔案與目錄:

#wget https://svn.zope.org/*checkout*/zc.buildout/trunk/bootstrap/bootstrap.py
#python bootstrap.py
Creating directory '/root/buildout-demo/bin'.
Creating directory '/root/buildout-demo/parts'.
Creating directory '/root/buildout-demo/eggs'.
Creating directory '/root/buildout-demo/develop-eggs'.
Generated script '/root/buildout-demo/bin/buildout'.

腳本建立了 bin、parts、eggs、develop-eggs 四個目錄,並在 bin 下產生 buildout 執行檔。

各目錄的用途:

  • bin:存放生成的腳本檔
  • parts:存放生成的中間資料,多數時候用不上
  • develop-eggs:存放指向開發目錄的連結檔,與 buildout.cfg 的 develop 選項相關
  • eggs:存放從網路下載的 egg 套件,一般在 buildout.cfg 的 egg 選項中定義

3. 建立設定檔,示例如下:

#vim buildout.cfg

[buildout]
# 每個 buildout 都要有一個 parts 列表,也可以為空
# parts 用來指定構建什麼;若 parts 中指定的段裡還有 parts,會遞歸構建
parts = tools

[tools]
# 每一段都要指定一個 recipe,recipe 含 python 代碼,用來安裝這一段
# zc.recipe.egg 就是把下面的 egg 安裝到 eggs 目錄
recipe = zc.recipe.egg
# 定義 python 解釋器
interpreter = python
# 需要安裝的 egg
eggs = pyramid

這份設定表示把 Pyramid 整合進 Python 環境。Pyramid 是一款結構簡單、穩定性好、響應速度快、文檔完備且擴展性強的 Web 框架。

執行建置:

#bin/buildout
Installing tools.
Getting distribution for 'pyramid'.
......

用 buildout 建立專案:

#bin/pcreate -t starter myproject

接著修改設定檔:

#vim buildout.cfg

[buildout]

parts = tools

[tools]
recipe = zc.recipe.egg
interpreter = python
eggs = pyramid

[apps]
recipe = zc.recipe.egg
eggs = myproject

再次執行:

#bin/buildout

在 Buildout 環境中啟動 myproject:

#bin/pserve myproject/development.ini
Starting server in PID 40619.
serving on https://0.0.0.0:6543

4. 對運行目錄的完全掌控

Buildout 對運行目錄擁有完全的控制權。每次執行時它都會重讀 buildout.cfg 來比對指令,如果你把某個 egg 從清單裡刪掉,對應的命令行工具與函式庫也會被一併移除。

例如把設定改成:

[buildout]

parts =

egg 與自訂直譯器都被移除後,執行:

#bin/buildout -N
Uninstalling tools

-N 表示僅列出變更後的結果。再看 bin 目錄,只剩 Buildout 自己的命令列工具了。

Copyright © Linux教程網 All Rights Reserved