如何在 Linux 上激活虚拟环境?
当我们谈到将依赖项与逻辑代码放在不同的位置时,我们实际上只是在创建一个虚拟环境,在 Python 中,我们通常使用术语 venv 来指代它。
因此,venv 只不过是一个虚拟环境,它反过来又是一个工具,允许我们将项目所需的依赖项保存在单独的文件夹中。我们创建的这些独立文件夹被称为 Python 虚拟环境。
Python venv 是最广泛使用的工具之一。
现在我们了解了什么是虚拟环境以及它的用途,接下来让我们看看如何在 Linux 上使用 Python 创建一个虚拟环境,以及它有哪些特性和功能。
简单来说,venv 工具就是 Python 中的一个模块,它用于支持创建轻量级且包含独立站点目录的"虚拟环境"。这些虚拟环境与系统的站点目录相互隔离。值得注意的是,这些虚拟环境 有自己的 Python 二进制文件,并且还可以拥有一组已安装在其站点目录中的 Python 软件包。
创建虚拟环境
可以使用以下命令创建虚拟环境 −
python3 -m venv /path_to_new_virtual_environment
现在让我们在 Unix 环境中运行上述命令,我使用的是 Mac OS,命令如下所示 −
python3 -m venv /Users/immukul/linux-questions-code
运行该命令后,您不会收到任何消息,终端将返回到其起始位置,现在您只需找到要执行该操作的目录即可。您创建一个虚拟环境,并且在该目录中必须具有与下面显示的输出相似或相同的文件 −
immukul@192 linux-questions-code % ls -ltr total 16 -rw-r--r-- 1 immukul staff 28 Jul 4 13:33 textfile.txt drwxr-xr-x 2 immukul staff 64 Jul 5 20:52 include drwxr-xr-x 3 immukul staff 96 Jul 5 20:52 lib -rw-r--r-- 1 immukul staff 90 Jul 5 20:52 pyvenv.cfg drwxr-xr-x 12 immukul staff 384 Jul 5 20:52 bin
以上就是如何在 Linux 中创建虚拟环境。venv 模块允许我们使用和运行一些参数,这些参数主要可以通过在终端中输入以下命令获取。
python3 -m venv
此命令将输出所有位置参数以及您可以在 venv 模块中使用的可选参数。
输出
usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear] [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps] ENV_DIR [ENV_DIR ...] venv: error: the following arguments are required: ENV_DIR immukul@192 ~ % python3 -m venv -h usage: venv [-h] [--system-site-packages] [--symlinks | --copies] [--clear] [--upgrade] [--without-pip] [--prompt PROMPT] [--upgrade-deps] ENV_DIR [ENV_DIR ...] Creates virtual Python environments in one or more target directories. Positional arguments: ENV_DIR A directory to create the environment in. Optional arguments: -h, --help Show this help message and exit --system-site-packages Give the virtual environment access to the system site-packages dir. --symlinks Try to use symlinks rather than copies, when symlinks are not the default for the platform. --copies Try to use copies rather than symlinks, even when symlinks are the default for the platform. --clear Delete the contents of the environment directory if it already exists, before environment creation. --upgrade Upgrade the environment directory to use this version of Python, assuming Python has been upgraded in-place. --without-pip Skips installing or upgrading pip in the virtual environment (pip is bootstrapped by default) --prompt PROMPT Provides an alternative prompt prefix for this environment. upgrade-deps Upgrade core dependencies: pip setup tools to the latest version in PyPI
相关文章
有用资源
linux 参考教程 - 该教程包含有关 linux 的更多信息:https://www.cainiaomax.com/linux/

