在python中创建venv并克隆git repo的操作

2024-05-15 09:06:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我在所有这些方面都是比较新的,我对这一排动作有问题。假设您创建了一个目录,并且希望为某个项目创建一个python虚拟环境,并克隆了一些git repo(例如,从GitHub)。然后在该目录中cd,并使用venv模块(对于python3)创建一个虚拟环境。为此,请运行以下命令:

     python3 -m venv my_venv

这将在您的目录中创建一个名为my_env的虚拟环境。要激活此环境,请运行以下命令

     source ./my_env/bin/activate

如果在该目录中还有一个requirements.txt文件可以运行

     pip3 install -r ./requirements.txt

使用安装各种依赖项和软件包。这就是我感到困惑的地方。如果你想克隆git回购,你到底在哪里克隆?在同一个目录中,您只需运行git clone并创建git repos,或者需要在另一个文件夹中cd。为了让python venv获取克隆的repos,上述内容是否足够,或者在您将repos克隆到目录中后必须安装venv


Tags: 项目git命令目录envtxtvenvmy
1条回答
网友
1楼 · 发布于 2024-05-15 09:06:25

首先,您需要了解什么是虚拟环境,当您了解虚拟环境的用途时,行动的顺序将更加明确

Python applications will often use packages and modules that don’t come as part of the standard library. Applications will sometimes need a specific version of a library, because the application may require that a particular bug has been fixed or the application may be written using an obsolete version of the library’s interface.

This means it may not be possible for one Python installation to meet the requirements of every application. If application A needs version 1.0 of a particular module but application B needs version 2.0, then the requirements are in conflict and installing either version 1.0 or 2.0 will leave one application unable to run.

The solution for this problem is to create a virtual environment, a self-contained directory tree that contains a Python installation for a particular version of Python, plus a number of additional packages.

Different applications can then use different virtual environments. To resolve the earlier example of conflicting requirements, application A can have its own virtual environment with version 1.0 installed while application B has another virtual environment with version 2.0. If application B requires a library be upgraded to version 3.0, this will not affect application A’s environment.

※参考:12. Virtual Environments and Packages


一般来说,以下顺序最合适

  1. $ git clone <Project A> # Cloning project repository
  2. $ cd <Project A> # Enter to project directory
  3. $ python3 -m venv my_venv # If not created, creating virtualenv
  4. $ source ./my_venv/bin/activate # Activating virtualenv
  5. (my_venv)$ pip3 install -r ./requirements.txt # Installing dependencies
  6. (my_venv)$ deactivate # When you want to leave virtual environment

离开虚拟环境后,步骤5中安装的所有依赖项都将不可用

相关问题 更多 >