Python venv 文件夹究竟是如何工作的?我的项目使用此 venv 文件夹中的依赖项使用不同的 Python 版本执行项目?

How exactly works Python venv folder? My project use the dependencies into this venv folder executing the project using a different Python version?

我是 Python 的绝对初学者(我来自 Java),我对项目中的 venv 文件夹有以下疑问。

所以基本上我有这个项目结构:

如您所见,它包含 venv 文件夹。阅读 Python 官方文档: https://docs.python.org/3/library/venv.html

我可以阅读:

The venv module provides support for creating lightweight “virtual environments” with their own site directories, optionally isolated from system site directories. Each virtual environment has its own Python binary (which matches the version of the binary that was used to create this environment) and can have its own independent set of installed Python packages in its site directories.

据我所知,这意味着,使用 venv,每个项目都有自己的 venv 文件夹,其中包含:

  1. bin 文件夹:它包含 Python 解释器二进制文件(在本例中为 Python 3.7)。

  2. lib 文件夹:包含我使用 pip3 安装的依赖项(事实上我安装了 scapyscapy_http 通过 pip3)

这是因为我的PyCharmIDE设置为使用Python3.7

如果这个推理是正确的(我完全不确定),这意味着当我 运行 类似:

python3 packet_sniffer.py

packet_sniffer.py 脚本(包含在之前的项目中)将 运行 使用 Python 3 二进制 和我的 venv 文件夹中的依赖项。正确吗?

如果我的推理是正确的,我有以下疑问:

当我 运行 使用 Python 2 by

时会发生什么
python packet_sniffer.py

我想它不再使用嵌入到我项目的 venv 文件夹中的 Python 3 版本。我在使用 scapy 的哪些依赖项?它来自哪里?

如您所见 运行 python 而不是 python3 我正在使用 Python2个版本:

root@kali:~# python --version
Python 2.7.17
root@kali:~# python3 --version
Python 3.7.5

python 虚拟环境

venv 文件夹是安装 python 虚拟环境的建议标准。 要使用虚拟环境,您必须先激活它。

注意:在安装应用程序所需的任何包之前激活您的python虚拟环境。

从命令行执行:

source venv/bin/activate
python packet_sniffer.py 

注意:您不需要指定python的具体版本,因为它默认为用于创建虚拟环境的版本。

PyCharm 可以配置为利用 python 虚拟环境

https://www.jetbrains.com/help/pycharm/creating-virtual-environment.html

如果您创建一个虚拟环境,然后激活它,如果您调用以下任何一个,安装在这个虚拟环境中的 python 解释器将是 运行:python foo.py / python3 foo.py。调用 python foo.py 或 python3 foo.py 之间会有 NO 区别(如果您安装了 python3 of当然)。

lib 文件夹将包含您在此虚拟环境中通过 pip 安装的相关依赖项,当您通过此虚拟环境使用 python 解释器时,您将使用上述依赖项

So from what I can understand it means that, using venv, every project have its own venv folder containing:

  1. The bin folder: it contains the Python interpreter binary (in this specific case Python 3.7).

  2. The lib folder: containing the dependencies that I have installed using pip3 (infact I installed scapy and scapy_http via pip3)

使用 venv 每个项目都有自己的 虚拟环境 文件夹,您可以随意命名,包含 bin 文件夹和 lib 文件夹。

如果您激活了虚拟环境,那么您所说的关于执行 python3 的一切都是正确的。但是,所有 other 命令仍然可用,并且会 运行 从它们所在的任何地方假设它们可以被您的 shell 找到。因此,您的 python 命令可能 运行 正在安装 python.

的系统级安装版本

如果您想确切地知道python口译员运行来自哪里:

 python
 >>> import sys
 >>> print(sys.executable)
 C:\Python27\python.exe