如何使用 virtualenv 安装 python 包而不全局安装它们?

如何使用 virtualenv 安装 python 包而不全局安装它们?

我已经安装了virtualenvsudo apt-get install virtualenv在本教程中您需要使用env/bin/文件夹自己的pippip3命令在虚拟环境中安装模块,它是明确表示你不使用 sudo去做这个。

不幸的是,这对我来说不起作用,PermissionError当我尝试这样做时,我得到了一个。但是之前使用 sudopip3会全局安装模块,所以我根本无法利用虚拟环境。

例如,当我在 env/bin/ 文件夹中时,我运行pip3 install pytest

Collecting pytest
  Downloading pytest-3.0.7-py2.py3-none-any.whl (172kB)
    100% |████████████████████████████████| 174kB 1.2MB/s 
Collecting py>=1.4.29 (from pytest)
  Downloading py-1.4.33-py2.py3-none-any.whl (83kB)
    100% |████████████████████████████████| 92kB 2.1MB/s 
Requirement already satisfied: setuptools in /usr/lib/python3/dist-packages (from pytest)
Installing collected packages: py, pytest
Exception:
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/local/lib/python3.5/dist-packages/pip/commands/install.py", line 342, in run
    prefix=options.prefix_path,
  File "/usr/local/lib/python3.5/dist-packages/pip/req/req_set.py", line 784, in install
    **kwargs
  File "/usr/local/lib/python3.5/dist-packages/pip/req/req_install.py", line 851, in install
    self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
  File "/usr/local/lib/python3.5/dist-packages/pip/req/req_install.py", line 1064, in move_wheel_files
    isolated=self.isolated,
  File "/usr/local/lib/python3.5/dist-packages/pip/wheel.py", line 345, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/usr/local/lib/python3.5/dist-packages/pip/wheel.py", line 316, in clobber
    ensure_dir(destdir)
  File "/usr/local/lib/python3.5/dist-packages/pip/utils/__init__.py", line 83, in ensure_dir
    os.makedirs(path)
  File "/usr/lib/python3.5/os.py", line 241, in makedirs
    mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.5/dist-packages/py-1.4.33.dist-info'

我该如何以更轻松的方式开始使用virtualenvUbuntu 16.04?

答案1

创建虚拟环境后,您需要激活它:

$ virtualenv myenv
$ source myenv/bin/activate
(myenv) $ pip install pytest

或者对于 Python 3:

$ virtualenv -p `which python3` myenv
$ source myenv/bin/activate
(myenv) $ pip3 install pytest

当您使用完环境后,您可以像这样停用它:

$ deactivate

相关内容