本文內容

本文內容

如果您與其他人共用專案、使用建置系統，或是打算將專案複製到需要還原環境的其他任何位置，則必須指定專案所需的外部套件。If you share a project with others, use a build system, or plan to copy the project to any other location where you need to restore an environment, you need to specify the external packages that the project requires.建議的方法是使用 requirements.txt 檔案 (readthedocs.org)，此檔案包含 pip 命令清單，可安裝所需的相依套件版本。The recommended approach is to use a requirements.txt file (readthedocs.org) that contains a list of commands for pip that installs the required versions of dependent packages.最常見的命令是 pip freeze > requirements.txt，它會將環境的目前套件清單記錄到 requirements.txt。The most common command is pip freeze > requirements.txt, which records an environment's current package list into requirements.txt.

就技術而言，任何檔案名稱都可用來追蹤必要條件 (透過在安裝套件時使用 -r <full path to file>)，但 Visual Studio 為 requirements.txt 提供了專屬支援：Technically, any filename may be used to track requirements (by using -r <full path to file> when installing a package), but Visual Studio provides specific support for requirements.txt:

若您已在環境中安裝所有必要套件，可以在 [方案總管] 中的環境上按一下滑鼠右鍵，然後選取 [產生 requirements.txt] 以建立必要的檔案。If you already have all the necessary packages installed in an environment, you can right-click that environment in Solution Explorer and select Generate requirements.txt to create the necessary file.如果該檔案已經存在，系統會提示您如何更新它：If the file already exists, a prompt appears for how to update it:

[重新整理現有項目] 會偵測套件需求並更新版本規範，以符合您目前已安裝的版本。Refresh existing entries detects package requirements and updates the version specifiers to match the version you currently have installed.

[Update and add entries (更新及新增項目)] 會重新整理所找到的任何需求，並將所有其他套件新增到檔案結尾。Update and add entries refreshes any requirements that are found, and adds all other packages to the end of the file.

由於 requirements.txt 檔案的用意是要固定住環境的需求，因此所有安裝的套件都已寫明精確的版本。Because requirements.txt files are intended to freeze the requirements of an environment, all installed packages are written with precise versions.使用精確的版本可確保您可以在另一部電腦上輕鬆重現您的環境。Using precise versions ensures that you can easily reproduce your environment on another computer.即使安裝套件時已指定版本範圍，仍然會包含這些套件作為另一個套件的相依性，或隨附於 pip 以外的安裝程式。Packages are included even if they were installed with a version range, as a dependency of another package, or with an installer other than pip.

如果套件是 pip 無法安裝的套件，並且出現在 requirements.txt 檔案中，整個安裝就會失敗。If a package cannot be installed by pip and it appears in a requirements.txt file, the entire installation fails.在此情況下，請手動編輯檔案以將此套件排除，或使用 pip 的選項來參考該套件的可安裝版本。In this case, manually edit the file to exclude this package or to use pip's options to refer to an installable version of the package.例如，您可能偏好使用 pip wheel 來編譯相依性並將 --find-links <path> 選項新增到您的 requirements.txt：For example, you may prefer to use pip wheel to compile a dependency and add the --find-links <path> option to your requirements.txt: