Pip 在虚拟环境中全局安装包

问题描述 投票:0回答:1

我想在本地安装 python 包,并且当前已通过终端命令“python3 -m pip list; python3 -m venv venv; venv/bin/pip list”设置了一个虚拟环境,输出如下:

Space Invaders/start python3 -m pip list; python3 -m venv venv; venv/bin/pip list

Package           Version
----------------- ---------
arcade            2.6.17
attrs             23.2.0
cffi              1.16.0
Pillow            9.3.0
pip               24.0
pip-autoremove    0.10.0
pycparser         2.22
pyglet            2.0.dev23
pymunk            6.4.0
pytiled-parser    2.2.0
requests          2.31.0
setuptools        69.0.2
typing_extensions 4.12.2

Package    Version
---------- -------
pip        23.3.1
setuptools 69.0.2

在我在激活的环境中安装软件包之前,这似乎是正确的:

Space Invaders/start source ./venv/bin/activate
(venv) Space Invaders/start python3 -m pip install arcade

(venv)   Space Invaders/start pip list

Package          Version
---------------- ---------
arcade           2.6.17
attrs            23.2.0
cffi             1.16.0
Pillow           9.3.0
pip              23.3.1
pycparser        2.22
pyglet           2.0.dev23
pymunk           6.4.0
pytiled-parser   2.2.0
setuptools       69.0.2
typing_extension 4.12.2

停用环境后,运行命令“venv/bin/pip list”会显示全局包的设置,而不是在虚拟环境输出中安装 pip 时安装的包:


Package           Version
----------------- ---------
arcade            2.6.17
attrs             23.2.0
cffi              1.16.0
Pillow            9.3.0
pip               23.3.1
pycparser         2.22
pyglet            2.0.dev23
pymunk            6.4.0
pytiled-parser    2.2.0
setuptools        69.0.2
typing_extensions 4.12.2

如何确保 pip 只安装虚拟环境中的包而不引用全局包?

python python-3.x pip python-venv
1个回答
1
投票

您需要激活您的虚拟环境

>> python3 -m venv .env  # create venv

>> source .env/bin/activate  # activating venv

>> which python3  # path to python. Should be in venv folder
/path/to/your/folder/.env/bin/python3

>> which pip  # path to pip. Should be in venv folder
/path/to/your/folder/.env/bin/pip

>> pip list  # list all packages inside env
Package Version
------- -------
pip     24.0

>> pip install requests  # install library
...

>> pip list  # list of libraries inside venv
Package            Version
------------------ --------
certifi            2024.7.4
charset-normalizer 3.3.2
idna               3.7
pip                24.0
requests           2.32.3
urllib3            2.2.2


>> deactivate  # leave from venv and use system python

>> which python  # path to python. Here should be in /usr/bin or similar global path
/usr/bin/python 

>> pip list  # list packages in global python. Should not be the same as in venv
...

© www.soinside.com 2019 - 2024. All rights reserved.