问题:在virtualenv中使用Python 3

使用virtualenv,我使用默认版本的Python(2.7)运行项目。在一个项目中,我需要使用Python 3.4。

我曾经brew install python3将其安装在Mac上。现在,如何创建使用新版本的virtualenv?

例如sudo virtualenv envPython3

如果我尝试:

virtualenv -p python3 test

我得到:

Running virtualenv with interpreter /usr/local/bin/python3
Using base prefix '/usr/local/Cellar/python3/3.4.0_1/Frameworks/Python.framework/Versions/3.4'
New python executable in test/bin/python3.4
Also creating executable in test/bin/python
Failed to import the site module
Traceback (most recent call last):
  File "/Users/user/Documents/workspace/test/test/bin/../lib/python3.4/site.py", line 67, in <module>
    import os
  File "/Users/user/Documents/workspace/test/test/bin/../lib/python3.4/os.py", line 634, in <module>
    from _collections_abc import MutableMapping
ImportError: No module named '_collections_abc'
ERROR: The executable test/bin/python3.4 is not functioning
ERROR: It thinks sys.prefix is '/Users/user/Documents/workspace/test' (should be '/Users/user/Documents/workspace/test/test')
ERROR: virtualenv is not compatible with this system or executable

Using virtualenv, I run my projects with the default version of Python (2.7). On one project, I need to use Python 3.4.

I used brew install python3 to install it on my Mac. Now, how do I create a virtualenv that uses the new version?

e.g. sudo virtualenv envPython3

If I try:

virtualenv -p python3 test

I get:

Running virtualenv with interpreter /usr/local/bin/python3
Using base prefix '/usr/local/Cellar/python3/3.4.0_1/Frameworks/Python.framework/Versions/3.4'
New python executable in test/bin/python3.4
Also creating executable in test/bin/python
Failed to import the site module
Traceback (most recent call last):
  File "/Users/user/Documents/workspace/test/test/bin/../lib/python3.4/site.py", line 67, in <module>
    import os
  File "/Users/user/Documents/workspace/test/test/bin/../lib/python3.4/os.py", line 634, in <module>
    from _collections_abc import MutableMapping
ImportError: No module named '_collections_abc'
ERROR: The executable test/bin/python3.4 is not functioning
ERROR: It thinks sys.prefix is '/Users/user/Documents/workspace/test' (should be '/Users/user/Documents/workspace/test/test')
ERROR: virtualenv is not compatible with this system or executable

回答 0

只需运行

virtualenv -p python3 envname

OP编辑后更新:

有没有在OP的版本virtualenv中的一个bug,如所描述这里。该问题已通过运行解决:

pip install --upgrade virtualenv

simply run

virtualenv -p python3 envname

Update after OP’s edit:

There was a bug in the OP’s version of virtualenv, as described here. The problem was fixed by running:

pip install --upgrade virtualenv

回答 1

Python 3具有对虚拟环境venv的内置支持。最好改用它。参考文档:

通过执行pyvenv脚本来创建虚拟环境:

pyvenv /path/to/new/virtual/environment

适用于Python 3.6及更高版本的更新:

由于pawciobiel正确注释了pyvenv因此从Python 3.6开始不推荐使用,新方法是:

python3 -m venv /path/to/new/virtual/environment

Python 3 has a built-in support for virtual environments – venv. It might be better to use that instead. Referring to the docs:

Creation of virtual environments is done by executing the pyvenv script:

pyvenv /path/to/new/virtual/environment

Update for Python 3.6 and newer:

As pawciobiel correctly comments, pyvenv is deprecated as of Python 3.6 and the new way is:

python3 -m venv /path/to/new/virtual/environment

回答 2

我尝试过pyenv,它对于切换python版本(全局,文件夹或virtualenv中的本地)非常方便:

brew install pyenv

然后安装所需的Python版本:

pyenv install 3.5.0

并只需创建virtualenv并包含所需解释器版本的路径即可:

virtualenv -p /Users/johnny/.pyenv/versions/3.5.0/bin/python3.5 myenv

就是这样,检查版本:

. ./myenv/bin/activate && python -V

也有pyenv的插件pyenv-virtualenv,但是它对我不起作用。

I’v tried pyenv and it’s very handy for switching python versions (global, local in folder or in the virtualenv):

brew install pyenv

then install Python version you want:

pyenv install 3.5.0

and simply create virtualenv with path to needed interpreter version:

virtualenv -p /Users/johnny/.pyenv/versions/3.5.0/bin/python3.5 myenv

That’s it, check the version:

. ./myenv/bin/activate && python -V

There are also plugin for pyenv pyenv-virtualenv but it didn’t work for me somehow.


回答 3

安装先决条件。

sudo apt-get install python3 python3-pip virtualenvwrapper

创建一个基于Python3的虚拟环境。(可选)启用--system-site-packages标志。

mkvirtualenv -p /usr/bin/python3 <venv-name>

设置到虚拟环境中。

workon <venv-name>

使用pip程序包管理器安装其他要求。

pip install -r requirements.txt
pip install <package_name>

当同时处理多个python项目时,通常建议安装pdbpp全局通用包,然后在virtualenvs中重用它们。

除了消耗最少的磁盘空间和网络带宽外,使用此技术还节省了很多时间来获取软件包和安装软件包。

sudo -H pip3 -v install pdbpp
mkvirtualenv -p $(which python3) --system-site-packages <venv-name>

Django特定说明

如果有很多系统范围的python软件包,那么建议不要使用--system-site-packagesflag,尤其是在开发过程中,因为我注意到它会大大降低Django的启动速度。我认为Django环境初始化是手动扫描并从系统路径附加所有站点包,这可能是原因。甚至python manage.py shell变得很慢。

话虽如此,实验哪个选项更好。跳过--system-site-packagesDjango项目的标志可能是安全的。

Install prerequisites.

sudo apt-get install python3 python3-pip virtualenvwrapper

Create a Python3 based virtual environment. Optionally enable --system-site-packages flag.

mkvirtualenv -p /usr/bin/python3 <venv-name>

Set into the virtual environment.

workon <venv-name>

Install other requirements using pip package manager.

pip install -r requirements.txt
pip install <package_name>

When working on multiple python projects simultaneously it is usually recommended to install common packages like pdbpp globally and then reuse them in virtualenvs.

Using this technique saves a lot of time spent on fetching packages and installing them, apart from consuming minimal disk space and network bandwidth.

sudo -H pip3 -v install pdbpp
mkvirtualenv -p $(which python3) --system-site-packages <venv-name>

Django specific instructions

If there are a lot of system wide python packages then it is recommended to not use --system-site-packages flag especially during development since I have noticed that it slows down Django startup a lot. I presume Django environment initialisation is manually scanning and appending all site packages from the system path which might be the reason. Even python manage.py shell becomes very slow.

Having said that experiment which option works better. Might be safe to just skip --system-site-packages flag for Django projects.


回答 4

virtualenv --python=/usr/bin/python3 <name of env>

为我工作。

virtualenv --python=/usr/bin/python3 <name of env>

worked for me.


回答 5

您可以在创建环境时指定特定的Python版本
virtualenv.py中提到

virtualenv --python=python3.5 envname

在某些情况下,这必须是可执行文件的完整路径:

virtualenv --python=/Users/username/.pyenv/versions/3.6.0/bin/python3.6 envname

如何-p工作

parser.add_option(
    '-p', '--python',
    dest='python',
    metavar='PYTHON_EXE',
    help='The Python interpreter to use, e.g., --python=python3.5 will use the python3.5 '
    'interpreter to create the new environment.  The default is the interpreter that '
    'virtualenv was installed with (%s)' % sys.executable)

You can specify specific Version of Python while creating environment.
It’s mentioned in virtualenv.py

virtualenv --python=python3.5 envname

In some cases this has to be the full path to the executable:

virtualenv --python=/Users/username/.pyenv/versions/3.6.0/bin/python3.6 envname

How -p works

parser.add_option(
    '-p', '--python',
    dest='python',
    metavar='PYTHON_EXE',
    help='The Python interpreter to use, e.g., --python=python3.5 will use the python3.5 '
    'interpreter to create the new environment.  The default is the interpreter that '
    'virtualenv was installed with (%s)' % sys.executable)

回答 6

我有同样的ERROR信息。在我的情况下,tbrisker的解决方案不起作用。相反,这解决了问题:

$ python3 -m venv .env

I had the same ERROR message. tbrisker’s solution did not work in my case. Instead this solved the issue:

$ python3 -m venv .env

回答 7

这就是您所需要的,以便在python / python3中运行虚拟环境

首先,如果virtualenv未安装,请运行

pip3 install virtualenv 

现在运行:

virtualenv -p python3 <env name> 

有时,cmd virtualenv失败,请使用以下命令:

python3 -m virtualenv <env_name>  # you can specify full path instead <env_name> to install the file in a different location other than the current location

现在激活虚拟环境:

source <env_name>/bin/activate

要么:

source `pwd`/<env_name>/bin/activate

现在运行

which python

您应该看到目录和<env_name>/bin/python后缀的完整路径

要退出virtualenv,请运行:

deactivate 

This is all you need, in order to run a virtual environment in python / python3

First if virtualenv not installed, run

pip3 install virtualenv 

Now Run:

virtualenv -p python3 <env name> 

Sometime the cmd virtualenv fails, if so use this:

python3 -m virtualenv <env_name>  # you can specify full path instead <env_name> to install the file in a different location other than the current location

Now activate the virtual env:

source <env_name>/bin/activate

Or:

source `pwd`/<env_name>/bin/activate

Now run

which python

You should see the full path to your dir and <env_name>/bin/python suffix

To exit the virtualenv, run:

deactivate 

回答 8

Python现在带有自己的虚拟环境实现,名称为“ venv”。我建议使用它,而不是virtualenv。

引用venv-docs

自3.6版起不推荐使用:pyvenv是为Python 3.3和3.4创建虚拟环境的推荐工具,在Python 3.6中不推荐使用。

在版本3.5中进行了更改:现在建议使用venv创建虚拟环境。

对于Windows,要在某些项目上启动venv,请打开cmd:

python -m venv "c:\path\to\myenv"

(如果目录路径包含空格,建议在目录路径周围使用双引号。例如:“ C:/ My Dox / Spaced Directory / Something”)

设置venv后,您将在项目目录中看到一些新文件夹。其中之一就是“脚本”。

要激活或调用venv,您需要:

C:\> <venv>\Scripts\activate.bat

您可以通过在Shell中键入“ deactivate”来停用虚拟环境。这样,您现在就可以安装特定于项目的库,该库位于文件夹“ Lib”下。

===============================编辑1 ================ ====================下面将要讨论的场景不是最初要求的,只是在有人将vscode与python扩展一起使用的情况下添加此场景

如果您使用vs代码及其python扩展名,您的pylint可能会遇到问题,该问题指向全局安装。在这种情况下,pylint将无法查看虚拟环境中安装的模块,因此在导入时将显示错误。

是克服此问题的简单方法。

cd Workspace\Scripts
.\Activate.ps1
code .

我们基本上是先激活环境,然后再调用vs代码,以便pylint在环境中启动并可以看到所有本地包。

Python now comes with its own implementation of virtual environment, by the name of “venv”. I would suggest using that, instead of virtualenv.

Quoting from venv – docs,

Deprecated since version 3.6: pyvenv was the recommended tool for creating virtual environments for Python 3.3 and 3.4, and is deprecated in Python 3.6.

Changed in version 3.5: The use of venv is now recommended for creating virtual environments.

For windows, to initiate venv on some project, open cmd:

python -m venv "c:\path\to\myenv"

(Would suggest using double quote around directory path if it contains any spaces. Ex: “C:/My Dox/Spaced Directory/Something”)

Once venv is set up, you will see some new folders inside your project directory. One of them would be “Scripts”.

To activate or invoke venv you need:

C:\> <venv>\Scripts\activate.bat

You can deactivate a virtual environment by typing “deactivate” in your shell. With this, you are now ready to install your project specific libraries, which will reside under the folder “Lib”.

================================ Edit 1 ==================================== The scenario which will be discussed below is not what originally asked, just adding this in case someone use vscode with python extension

In case, you use vs code with its python extension, you might face an issue with its pylint which points to the global installation. In this case, pylint won’t be able to see the modules that are installed in your virtual environment and hence will show errors while importing.

Here is a simple method to get past this.

cd Workspace\Scripts
.\Activate.ps1
code .

We are basically activating the environment first and then invoking vs-code so that pylint starts within the environment and can see all local packages.


回答 9

除了其他答案,我建议检查您正在执行哪个virtualenv实例:

which virtualenv

如果在/ usr / local / bin中出现问题,则可能甚至可能安装了virtualenv(可能使用easy_tools或pip实例)而没有使用系统的程序包管理器(在OP中为棕色)。这是我的问题。

多年前-当我更加无知的时候-我安装了virtualenv,它掩盖了我系统的软件包提供的virtualenv。

删除了这个破旧的virtualenv之后,我的问题就消失了。

In addition to the other answers, I recommend checking what instance of virtualenv you are executing:

which virtualenv

If this turns up something in /usr/local/bin, then it is possible – even likely – that you installed virtualenv (possibly using an instance of easy_tools or pip) without using your system’s package manager (brew in OP’s case). This was my problem.

Years ago – when I was even more ignorant – I had installed virtualenv and it was masking my system’s package-provided virtualenv.

After removing this old, broken virtualenv, my problems went away.


回答 10

在python3.6中,我python3 -m venv myenv根据文档尝试 了,但是花费了很长时间。因此,非常简单快捷的命令是: python -m venv yourenv 它在python3.6上对我有效。

In python3.6 I tried python3 -m venv myenv, as per the documentation, but it was taking so long. So the very simple and quick command is python -m venv yourenv It worked for me on python3.6.


回答 11

在Mac上,我必须执行以下操作才能使其正常工作。

mkvirtualenv --python=/usr/bin/python3 YourEnvNameHere

On Mac I had to do the following to get it to work.

mkvirtualenv --python=/usr/bin/python3 YourEnvNameHere

回答 12

如果您将python3(brew install python3)与virtualenv burrito一起安装,则可以 mkvirtualenv -p $(which python3) env_name

当然,我知道virtualenv burrito只是一个包装,但是多年来,它对我很有用,减少了一些学习难度。

If you install python3 (brew install python3) along with virtualenv burrito, you can then do mkvirtualenv -p $(which python3) env_name

Of course, I know virtualenv burrito is just a wrapper, but it has served me well over the years, reducing some learning curves.


回答 13

virtualenv --python=/usr/local/bin/python3 <VIRTUAL ENV NAME> 这将为 您的虚拟环境添加python3路径。

virtualenv --python=/usr/local/bin/python3 <VIRTUAL ENV NAME> this will add python3 path for your virtual enviroment.


回答 14

对我有用

virtualenv --no-site-packages --distribute -p /usr/bin/python3 ~/.virtualenvs/py3

It worked for me

virtualenv --no-site-packages --distribute -p /usr/bin/python3 ~/.virtualenvs/py3

回答 15

对于那些在使用Anaconda3(Python 3)时遇到麻烦的人。

你可以用

conda create -n name_of_your_virtualenv python=python_version 

激活环境(Linux,MacOS)

source activate name_of_your_virtualenv

对于Windows

activate name_of_your_virtualenv

For those having troubles while working with Anaconda3 (Python 3).

You could use

conda create -n name_of_your_virtualenv python=python_version 

To activate the environment ( Linux, MacOS)

source activate name_of_your_virtualenv

For Windows

activate name_of_your_virtualenv

回答 16

我尝试了以上所有方法,但仍然没有效果。因此,作为蛮力,我只是重新安装了anaconda,重新安装了virtualenv …,它确实起作用了。

Amans-MacBook-Pro:~ amanmadan$ pip install virtualenv
You are using pip version 6.1.1, however version 8.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Collecting virtualenv
  Downloading virtualenv-15.0.3-py2.py3-none-any.whl (3.5MB)
    100% |████████████████████████████████| 3.5MB 114kB/s 
Installing collected packages: virtualenv
Successfully installed virtualenv-15.0.3
Amans-MacBook-Pro:python amanmadan$ virtualenv my_env
New python executable in /Users/amanmadan/Documents/HadoopStuff/python/my_env/bin/python
Installing setuptools, pip, wheel...done.
Amans-MacBook-Pro:python amanmadan$ 

I tried all the above stuff, it still didn’t work. So as a brute force, I just re-installed the anaconda, re-installed the virtualenv… and it worked.

Amans-MacBook-Pro:~ amanmadan$ pip install virtualenv
You are using pip version 6.1.1, however version 8.1.2 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
Collecting virtualenv
  Downloading virtualenv-15.0.3-py2.py3-none-any.whl (3.5MB)
    100% |████████████████████████████████| 3.5MB 114kB/s 
Installing collected packages: virtualenv
Successfully installed virtualenv-15.0.3
Amans-MacBook-Pro:python amanmadan$ virtualenv my_env
New python executable in /Users/amanmadan/Documents/HadoopStuff/python/my_env/bin/python
Installing setuptools, pip, wheel...done.
Amans-MacBook-Pro:python amanmadan$ 

回答 17

我想将python 2.7.5保留为Centos 7的默认版本,但在虚拟环境中将python 3.6.1与python 2.x中的其他虚拟环境一起运行

我发现以下链接是最新python版本(python 3.6.1)的最佳解决方案 https://www.digitalocean.com/community/tutorial_series/how-to-install-and-set-up-a-local-programming -for-python-3环境。它显示了不同平台的步骤,但是基本步骤是

  1. 为您的平台安装python3.x(如果不存在)
  2. 为您的平台安装python3.x-devel
  3. 在python 3.x中创建虚拟环境(例如$ python3.6 -m venv virenv_test_p3 /)
  4. 激活python 3.x的测试环境(例如源virenv_test_p3 / bin / activate)
  5. 安装要在新的python 3虚拟环境中使用且受支持的软件包(例如pip install Django == 1.11.2)

I wanted to keep python 2.7.5 as default version on Centos 7 but have python 3.6.1 in a virtual environment running alongside other virtual environments in python 2.x

I found the below link the best solution for the newest python version ( python 3.6.1) https://www.digitalocean.com/community/tutorial_series/how-to-install-and-set-up-a-local-programming-environment-for-python-3. It shows the steps for different platforms but the basic steps are

  1. Install python3.x (if not present) for your platform
  2. Install python3.x-devel for your platform
  3. Create virtual environment in python 3.x (for example $ python3.6 -m venv virenv_test_p3/ )
  4. Activate the testenvironment for python 3.x (for example source virenv_test_p3/bin/activate)
  5. Install the packages which you want to use in your new python 3 virtual environment and which are supported ( for example pip install Django==1.11.2)

回答 18

下面的简单命令可以使用3.5版创建虚拟环境

apt-get install python3-venv

python3.5 -m venv <your env name>

如果您希望虚拟环境版本为3.6

python3.6 -m venv <your env name>

The below simple commands can create a virtual env with version 3.5

apt-get install python3-venv

python3.5 -m venv <your env name>

if you want virtual env version as 3.6

python3.6 -m venv <your env name>

回答 19

对于正在使用pipenv并想要安装特定版本的用户:

pipenv install --python 3.6

For those of you who are using pipenv and want to install specific version:

pipenv install --python 3.6

回答 20

由于存在与miniconda3安装冲突的问题,因此出现了相同的错误,因此当您键入“哪个virtualenv”并且安装了miniconda并指向该安装时,您可以将其删除(如果您喜欢我并且没有移动)或更改环境变量以指向所需的安装。

I got the same error due to it being a conflict with miniconda3 install so when you type “which virtualenv” and if you’ve installed miniconda and it’s pointing to that install you can either remove it (if your like me and haven’t moved to it yet) or change your environment variable to point to the install you want.


回答 21

在Windows命令行上,以下内容对我有用。首先找出您的python可执行文件所在的位置:

where python

这会将路径输出到系统上其他python.exe的路径。这是我的:

C:\Users\carandangc\Anaconda3\python.exe
C:\Python27\python.exe

因此,对于Python3而言,这位于我的第一个路径中,因此我进入了要在其中创建虚拟环境文件夹的应用程序的根文件夹。然后,我运行以下命令,其中包括我的Python3可执行文件的路径,将我的虚拟环境命名为“ venv”:

virtualenv --python=/Users/carandangc/Anaconda3/python.exe venv

接下来,激活虚拟环境:

call venv\Scripts\activate.bat

最后,安装此虚拟环境的依赖项:

pip install -r requirements.txt

如果您知道虚拟环境中应用程序所需的库/模块,则可以手动填充此requirements.txt。如果您的应用程序在另一个环境中运行,则可以通过运行以下命令(在运行它的环境中的cd到应用程序文件夹中)来自动生成依赖项:

pip freeze > requirements.txt

然后,一旦您具有“冻结”的requests.txt,则可以使用以下命令(在cd到应用程序文件夹之后)在另一台计算机或干净的环境中安装需求:

pip install -r requirements.txt

要在虚拟环境中查看python版本,请运行:

python --version

然后,瞧……您的Python3正在虚拟环境中运行。为我输出:

Python 3.7.2

On Windows command line, the following worked for me. First find out where your python executables are located:

where python

This will output the paths to the different python.exe on your system. Here were mine:

C:\Users\carandangc\Anaconda3\python.exe
C:\Python27\python.exe

So for Python3, this was located in the first path for me, so I cd to the root folder of the application where I want to create a virtual environment folder. Then I run the following which includes the path to my Python3 executable, naming my virtual environment ‘venv’:

virtualenv --python=/Users/carandangc/Anaconda3/python.exe venv

Next, activate the virtual environment:

call venv\Scripts\activate.bat

Finally, install the dependencies for this virtual environment:

pip install -r requirements.txt

This requirements.txt could be populated manually if you know the libraries/modules needed for your application in the virtual environment. If you had the application running in another environment, then you can automatically produce the dependencies by running the following (cd to the application folder in the environment where it is working):

pip freeze > requirements.txt

Then once you have the requirements.txt that you have ‘frozen’, then you can install the requirements on another machine or clean environment with the following (after cd to the application folder):

pip install -r requirements.txt

To see your python version in the virtual environment, run:

python --version

Then voila…you have your Python3 running in your virtual environment. Output for me:

Python 3.7.2

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。