管理相依項
管理相依性 #
相依性群組 #
Poetry 提供一種方式,可以透過群組來組織相依性。例如,您可能有相依性,僅需要用於測試專案或建置文件。
要宣告新的相依性群組,請使用 tool.poetry.group.<group>
區段,其中 <group>
是相依性群組的名稱(例如,test
)
[tool.poetry.group.test] # This part can be left out
[tool.poetry.group.test.dependencies]
pytest = "^6.0.0"
pytest-mock = "*"
所有相依性在群組之間都必須相容,因為它們會解析,無論它們是否為安裝所需(請參閱 安裝群組相依性)。
將相依性群組想像成與相依性相關聯的標籤:它們不會影響相依性是否會預設解析並安裝,它們只不過是一種邏輯地組織相依性的方式而已。
宣告在 tool.poetry.dependencies
中的相依性是明確的 main
群組的一部分。
[tool.poetry.dependencies] # main dependency group
httpx = "*"
pendulum = "*"
[tool.poetry.group.test.dependencies]
pytest = "^6.0.0"
pytest-mock = "*"
相依性群組,除了明確的 main
群組之外,只能包含開發過程中需要的相依性。只能使用 Poetry 安裝這些相依性。
要宣告一堆相依性,以在執行期間加入專案的其他功能,請改用 其他項目。可以使用 pip
,由最終使用者安裝其他項目。
關於定義 dev
相依性群組的注意事項
自 Poetry 1.2.0 之後,定義 dev
相依性群組的正確方式如下
[tool.poetry.group.dev.dependencies]
pytest = "^6.0.0"
pytest-mock = "*"
從 Poetry 1.2.0 開始建議使用此群組標記法,在較早版本中無法使用。為了向後相容舊版 Poetry,宣告在 dev-dependencies
區段中的任何相依項會自動加入 dev
群組。因此,以上和以下的標記法是相等的
# Poetry pre-1.2.x style, understood by Poetry 1.0–1.2
[tool.poetry.dev-dependencies]
pytest = "^6.0.0"
pytest-mock = "*"
Poetry 將會逐步淘汰 dev-dependencies
標記法,此標記法很快就會被淘汰,因此建議將現有的開發相依項移轉到新的 group
標記法。
選用群組 #
可以將相依項群組宣告為選用。如果您有一群在特定環境下或出於特定目的才需要的相依項時,這樣比較合理。
[tool.poetry.group.docs]
optional = true
[tool.poetry.group.docs.dependencies]
mkdocs = "*"
除了 **預設** 相依項之外,還能使用 install
指令的 --with
選項安裝選用群組。
poetry install --with docs
將相依項新增到群組 #
建議使用 add
指令將相依項新增到群組。可以使用 --group (-G)
選項進行此操作。
poetry add pytest --group test
如果群組不存在,將會自動建立。
安裝群組相依項 #
**預設情況下**,執行 poetry install
時將安裝 所有非選用群組 的相依項。
能使用 --without
選項 **排除** 一個或多個群組
poetry install --without test,docs
也能使用 --with
選項選取 選用群組
poetry install --with docs
同時使用時,--without
優先於 --with
。例如,以下的指令只會安裝選用 test
群組中指定的相依項。
poetry install --with test,docs --without docs
最後,在某些情況下,您可能只想安裝 **特定群組** 的相依項,而不安裝預設相依項集合。您可以使用 --only
選項來達成此目的。
poetry install --only docs
如果您只想安裝專案的執行時期相依項,可以使用 --only main
標記法。
poetry install --only main
如果您只想安裝專案根目錄,而不要安裝其他相依項,可以使用 --only-root
選項。
poetry install --only-root
從群組中移除相依項 #
remove
命令支援使用 --group
選項來移除特定套件群組中的套件
poetry remove mkdocs --group docs
同步相依關係 #
Poetry 支援所謂的相依關係同步。相依關係同步會確保 poetry.lock
檔中鎖定的相依關係是環境中僅有的相依關係,移除所有不必要的部分。
只要使用 install
指令的 `--sync` 選項即可辦到
poetry install --sync
--sync
選項可以與任何 相依關係群組 相關選項合併,以將環境與特定群組同步。請注意,額外功能是分開的。無論 --sync
是否設定,任何未選取安裝的額外功能都會遭到移除。
poetry install --without dev --sync
poetry install --with docs --sync
poetry install --only dev
--sync
選項會取代現在已不建議使用的 --remove-untracked
配置可選群組 #
當你省略 --sync
選項時,你可以安裝任何可選群組子集,而不會移除已安裝的群組。例如,在多階段 Docker 建置中,這非常有用,而且你可以在不同的建置階段多次執行 `poetry install`。