标签归档:virtualenv

在virtualenv中使用Python 3

问题:在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

如何离开/退出/停用Python virtualenv

问题:如何离开/退出/停用Python virtualenv

我正在使用virtualenv和virtualenvwrapper。我可以使用workon命令在virtualenv之间切换。

me@mymachine:~$ workon env1
(env1)me@mymachine:~$ workon env2
(env2)me@mymachine:~$ workon env1
(env1)me@mymachine:~$ 

如何退出所有虚拟机并再次在真实计算机上工作?现在,我唯一要回到的方法me@mymachine:~$是退出外壳并启动一个新外壳。真烦人。有没有什么要执行的命令,如果是的话,这是什么?如果这样的命令不存在,我将如何创建它?

I’m using virtualenv and the virtualenvwrapper. I can switch between virtualenv’s just fine using the workon command.

me@mymachine:~$ workon env1
(env1)me@mymachine:~$ workon env2
(env2)me@mymachine:~$ workon env1
(env1)me@mymachine:~$ 

How do I exit all virtual machines and work on my real machine again? Right now, the only way I have of getting back to me@mymachine:~$ is to exit the shell and start a new one. That’s kind of annoying. Is there a command to work on “nothing”, and if so, what is it? If such a command does not exist, how would I go about creating it?


回答 0

通常,激活virtualenv会给您提供一个名为:

$ deactivate

这使情况恢复正常。

我只是再次专门查看的代码virtualenvwrapper,是的,它也支持deactivate从所有virtualenvs逃脱的方式。

如果您要离开Anaconda环境,则该命令取决于您的的版本conda。最新版本(如4.6)conda直接在您的shell中安装一个函数,在这种情况下,您可以运行:

conda deactivate

较旧的conda版本改为使用独立脚本实现停用:

source deactivate

Usually, activating a virtualenv gives you a shell function named:

$ deactivate

which puts things back to normal.

I have just looked specifically again at the code for virtualenvwrapper, and, yes, it too supports deactivate as the way to escape from all virtualenvs.

If you are trying to leave an Anaconda environment, the command depends upon your version of conda. Recent versions (like 4.6) install a conda function directly in your shell, in which case you run:

conda deactivate

Older conda versions instead implement deactivation using a stand-alone script:

source deactivate

回答 1

我所定义的别名workoff,作为相反workon

alias workoff='deactivate'

很容易记住:

[bobstein@host ~]$ workon django_project
(django_project)[bobstein@host ~]$ workoff
[bobstein@host ~]$

I defined an alias, workoff, as the opposite of workon:

alias workoff='deactivate'

It is easy to remember:

[bobstein@host ~]$ workon django_project
(django_project)[bobstein@host ~]$ workoff
[bobstein@host ~]$

回答 2

采用:

$ deactivate 

如果这不起作用,请尝试

$ source deactivate

任何知道Bash的source工作原理的人都会认为这很奇怪,但是围绕virtualenv的一些包装器/工作流将其实现为对Bash的补充/对应source activate。你的旅费可能会改变。

Use:

$ deactivate 

If this doesn’t work, try

$ source deactivate

Anyone who knows how Bash source works will think that’s odd, but some wrappers/workflows around virtualenv implement it as a complement/counterpart to source activate. Your mileage may vary.


回答 3

要激活Python虚拟环境:

$cd ~/python-venv/
$./bin/activate

停用:

$deactivate

To activate a Python virtual environment:

$cd ~/python-venv/
$./bin/activate

To deactivate:

$deactivate

回答 4

我发现在Miniconda3环境中时,我必须运行:

conda deactivate

deactivate没有source deactivate为我工作,也没有为我工作。

I found that when within a Miniconda3 environment I had to run:

conda deactivate

Neither deactivate nor source deactivate worked for me.


回答 5

您可以使用virtualenvwrapper来简化您的使用方式virtualenv

安装virtualenvwrapper

pip install virtualenvwrapper

如果您使用的是标准外壳,请打开~/.bashrc~/.zshrc使用Oh My Zsh。添加这两行:

export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

要激活现有的virtualenv,请使用命令workon

$ workon myenv
(myenv)$

为了停用您的virtualenv:

(myenv)$ deactivate

这是我的教程,逐步介绍了如何安装virtualenv和virtualenvwrapper。

You can use virtualenvwrapper in order to ease the way you work with virtualenv.

Installing virtualenvwrapper:

pip install virtualenvwrapper

If you are using a standard shell, open your ~/.bashrc or ~/.zshrc if you use Oh My Zsh. Add these two lines:

export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh

To activate an existing virtualenv, use command workon:

$ workon myenv
(myenv)$

In order to deactivate your virtualenv:

(myenv)$ deactivate

Here is my tutorial, step by step on how to install virtualenv and virtualenvwrapper.


回答 6

由于无法通过寻找这种命令的常用方法来发现deactivate通过源创建的功能,因此您可能希望创建一个仅执行该功能的命令。~/bin/activate~/bindeactivate

问题是,如果一个脚本名叫deactivate包含单个命令,则该脚本deactivate如果不在venv中意外执行,将导致无限循环。一个常见的错误。

通过仅deactivate在函数存在时执行(即已通过source创建activate),可以避免这种情况。

#!/bin/bash

declare -Ff deactivate  && deactivate

Since the deactivate function created by sourcing ~/bin/activate cannot be discovered by the usual means of looking for such a command in ~/bin, you may wish to create one that just executes the function deactivate.

The problem is that a script named deactivate containing a single command deactivate will cause an endless loop if accidentally executed while not in the venv. A common mistake.

This can be avoided by only executing deactivate if the function exists (i.e. has been created by sourcing activate).

#!/bin/bash

declare -Ff deactivate  && deactivate

回答 7

使用deactivate

(my_env) user@user:~/my_env$ deactivate
user@user-Lenovo-E40-80:~/my_env$ 

注意,(my_env)不见了。

Use deactivate.

(my_env) user@user:~/my_env$ deactivate
user@user-Lenovo-E40-80:~/my_env$ 

Note, (my_env) is gone.


回答 8

我使用基于autoenv的zsh- autoenv

zsh-autoenv自动获取(已知/列入白名单的).autoenv.zsh文件,通常在项目根目录中使用。它处理“进入”和“离开”事件,变量的嵌套和隐藏(覆盖和还原)。

这是一个例子:

; cd dtree 
Switching to virtual environment: Development tree utiles
;dtree(feature/task24|✓); cat .autoenv.zsh       
# Autoenv.
echo -n "Switching to virtual environment: "
printf "\e[38;5;93m%s\e[0m\n" "Development tree utiles"
workon dtree
# eof
dtree(feature/task24|✓); cat .autoenv_leave.zsh 
deactivate

因此,当我离开dtree目录时,虚拟环境将自动退出。

"Development tree utiles" 只是一个名字而已。

I use zsh-autoenv which is based off autoenv.

zsh-autoenv automatically sources (known/whitelisted) .autoenv.zsh files, typically used in project root directories. It handles “enter” and leave” events, nesting, and stashing of variables (overwriting and restoring).

Here is an example:

; cd dtree 
Switching to virtual environment: Development tree utiles
;dtree(feature/task24|✓); cat .autoenv.zsh       
# Autoenv.
echo -n "Switching to virtual environment: "
printf "\e[38;5;93m%s\e[0m\n" "Development tree utiles"
workon dtree
# eof
dtree(feature/task24|✓); cat .autoenv_leave.zsh 
deactivate

So when I leave the dtree directory, the virtual environment is automatically exited.

"Development tree utiles" is just a name… No hidden mean linking to the Illuminati in here.


回答 9

使用deactivatevenv activate脚本提供的功能,您需要信任正确激活了禁用功能的代码,才能将所有环境变量完全重置为以前的状态-不仅要考虑原始激活,还要考虑所有开关配置其他在此期间您可能已经完成的工作

可能很好,但是确实会带来一种新的,非零的风险,即事后修改环境。

但是,从工艺上讲,直接更改其父级的环境变量在技术上是不可能的,因此我们可以使用单独的子外壳来确保我们venv的进程不会留下任何残留更改:


激活:

$ bash --init-file PythonVenv/bin/activate

  • 这将在周围启动一个新的shell venv。您原来的bash外壳保持不变。

停用:

$ exit[CTRL]+[D]

  • 这将退出整个外壳venv,并使您回到激活脚本对环境进行任何更改之前的原始外壳。

例:

[user@computer ~]$ echo $VIRTUAL_ENV
No virtualenv!

[user@computer ~]$ bash --init-file PythonVenv/bin/activate

(PythonVenv) [user@computer ~]$ echo $VIRTUAL_ENV
/home/user/PythonVenv

(PythonVenv) [user@computer ~]$ exit
exit

[user@computer ~]$ echo $VIRTUAL_ENV
No virtualenv!

Using the deactivate feature provided by the venv’s activate script requires you to trust the deactivation function to be properly coded to cleanly reset all environment variables back to how they were before— taking into account not only the original activation, but also any switches, configuration, or other work you may have done in the meantime.

It’s probably fine, but it does introduce a new, non-zero risk of leaving your environment modified afterwards.

However, it’s not technically possible for a process to directly alter the environment variables of its parent, so we can use a separate sub-shell to be absolutely sure our venvs don’t leave any residual changes behind:


To activate:

$ bash --init-file PythonVenv/bin/activate

  • This starts a new shell around the venv. Your original bash shell remains unmodified.

To deactivate:

$ exit OR [CTRL]+[D]

  • This exits the entire shell the venv is in, and drops you back to the original shell from before the activation script made any changes to the environment.

Example:

[user@computer ~]$ echo $VIRTUAL_ENV
No virtualenv!

[user@computer ~]$ bash --init-file PythonVenv/bin/activate

(PythonVenv) [user@computer ~]$ echo $VIRTUAL_ENV
/home/user/PythonVenv

(PythonVenv) [user@computer ~]$ exit
exit

[user@computer ~]$ echo $VIRTUAL_ENV
No virtualenv!

回答 10

在处理安装程序脚本时,我遇到了同样的问题。我看了一下bin / activate_this.py做了什么,并将其反转了。

例:

#! /usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys

# Path to virtualenv
venv_path = os.path.join('/home', 'sixdays', '.virtualenvs', 'test32')

# Save old values
old_os_path = os.environ['PATH']
old_sys_path = list(sys.path)
old_sys_prefix = sys.prefix


def deactivate():
    # Change back by setting values to starting values
    os.environ['PATH'] = old_os_path
    sys.prefix = old_sys_prefix
    sys.path[:0] = old_sys_path


# Activate the virtualenvironment
activate_this = os.path.join(venv_path, 'bin/activate_this.py')
execfile(activate_this, dict(__file__=activate_this))


# Print list of pip packages for virtualenv for example purpose
import pip
print str(pip.get_installed_distributions())

# Unload pip module
del pip

# Deactivate/switch back to initial interpreter
deactivate()

# Print list of initial environment pip packages for example purpose
import pip
print str(pip.get_installed_distributions())

我不确定100%是否能按预期工作。我可能完全错过了一些东西。

I had the same problem while working on an installer script. I took a look at what the bin/activate_this.py did and reversed it.

Example:

#! /usr/bin/python
# -*- coding: utf-8 -*-
import os
import sys

# Path to virtualenv
venv_path = os.path.join('/home', 'sixdays', '.virtualenvs', 'test32')

# Save old values
old_os_path = os.environ['PATH']
old_sys_path = list(sys.path)
old_sys_prefix = sys.prefix


def deactivate():
    # Change back by setting values to starting values
    os.environ['PATH'] = old_os_path
    sys.prefix = old_sys_prefix
    sys.path[:0] = old_sys_path


# Activate the virtualenvironment
activate_this = os.path.join(venv_path, 'bin/activate_this.py')
execfile(activate_this, dict(__file__=activate_this))


# Print list of pip packages for virtualenv for example purpose
import pip
print str(pip.get_installed_distributions())

# Unload pip module
del pip

# Deactivate/switch back to initial interpreter
deactivate()

# Print list of initial environment pip packages for example purpose
import pip
print str(pip.get_installed_distributions())

I am not 100% sure if it works as intended. I may have missed something completely.


在virtualenv中使用不同的Python版本

问题:在virtualenv中使用不同的Python版本

我有一个目前使用python 2.5.4运行的Debian系统。我正确安装了virtualenv,一切正常。我是否可以将virtualenv与其他版本的Python一起使用?

我编译了Python 2.6.2,并希望将其与一些virtualenv一起使用。覆盖二进制文件是否足够?还是我必须更改有关库的某些内容?

I have a Debian system currently running with python 2.5.4. I got virtualenv properly installed, everything is working fine. Is there a possibility that I can use a virtualenv with a different version of Python?

I compiled Python 2.6.2 and would like to use it with some virtualenv. Is it enough to overwrite the binary file? Or do I have to change something in respect to the libraries?


回答 0

在创建virtualenv实例时,只需使用--python(或short -p)选项来指定要使用的Python可执行文件,例如:

virtualenv --python=/usr/bin/python2.6 <path/to/new/virtualenv/>

注意:对于Python 3.3或更高版本,请参阅下面的Aelfinn 答案

Just use the --python (or short -p) option when creating your virtualenv instance to specify the Python executable you want to use, e.g.:

virtualenv --python=/usr/bin/python2.6 <path/to/new/virtualenv/>

N.B. For Python 3.3 or later, refer to The Aelfinn’s answer below.


回答 1

从Python 3开始,Python Docs建议使用以下命令创建虚拟环境:

python3 -m venv <myenvname>

请注意,venv不允许使用其他版本的Python创建虚拟环境。为此,请安装并使用virtualenv 软件包


过时的信息

pyvenv 脚本可用于创建虚拟环境

pyvenv /path/to/new/virtual/environment

但自Python 3.6起已弃用。

Since Python 3, the Python Docs suggest creating the virtual environment with the following command:

python3 -m venv <myenvname>

Please note that venv does not permit creating virtual environments with other versions of Python. For that, install and use the virtualenv package.


Obsolete information

The pyvenv script can be used to create a virtual environment

pyvenv /path/to/new/virtual/environment

but it has been deprecated since Python 3.6.


回答 2

这些是您在共享托管环境上时需要执行的步骤,需要从源代码安装和编译Python,然后venv从您的Python版本创建。对于Python 2.7.9。您将按照以下方式进行操作:

mkdir ~/src
wget http://www.python.org/ftp/python/2.7.9/Python-2.7.9.tgz
tar -zxvf Python-2.7.9.tgz
cd Python-2.7.9
mkdir ~/.localpython
./configure --prefix=$HOME/.localpython
make
make install

虚拟环境

cd ~/src
wget https://pypi.python.org/packages/5c/79/5dae7494b9f5ed061cff9a8ab8d6e1f02db352f3facf907d9eb614fb80e9/virtualenv-15.0.2.tar.gz#md5=0ed59863994daf1292827ffdbba80a63
tar -zxvf virtualenv-15.0.2.tar.gz
cd virtualenv-15.0.2/
~/.localpython/bin/python setup.py install
virtualenv ve -p $HOME/.localpython/bin/python2.7
source ve/bin/activate   

自然,这可以适用于您想要复制工作和部署的确切环境的任何情况。

These are the steps you can follow when you are on a shared hosting environment and need to install & compile Python from source and then create venv from your Python version. For Python 2.7.9. you would do something along these lines:

mkdir ~/src
wget http://www.python.org/ftp/python/2.7.9/Python-2.7.9.tgz
tar -zxvf Python-2.7.9.tgz
cd Python-2.7.9
mkdir ~/.localpython
./configure --prefix=$HOME/.localpython
make
make install

virtual env

cd ~/src
wget https://pypi.python.org/packages/5c/79/5dae7494b9f5ed061cff9a8ab8d6e1f02db352f3facf907d9eb614fb80e9/virtualenv-15.0.2.tar.gz#md5=0ed59863994daf1292827ffdbba80a63
tar -zxvf virtualenv-15.0.2.tar.gz
cd virtualenv-15.0.2/
~/.localpython/bin/python setup.py install
virtualenv ve -p $HOME/.localpython/bin/python2.7
source ve/bin/activate   

Naturally, this can be applicable to any situation where you want to replicate the exact environment you work and deploy on.


回答 3

virtualenv --python=/usr/bin/python2.6 <path/to/myvirtualenv>
virtualenv --python=/usr/bin/python2.6 <path/to/myvirtualenv>

回答 4

有一个更简单的方法,

virtualenv venv --python=python2.7

感谢您的评论,这仅在系统级别安装了python2.7的情况下才有效(例如/usr/bin/python2.7)。

否则,如果您使用自制软件,则可以使用该路径提供所需的内容。

virtualenv venv --python=/usr/local/bin/python

您可以使用以下命令找到python安装的路径

which python

这也适用于python 3。

which python3
>> /usr/local/bin/python3
virtualenv venv --python=/usr/local/bin/python3

最终凝结为:

virtualenv venv -p `which python`
virtualenv venv -p `which python3`

There is an easier way,

virtualenv venv --python=python2.7

Thanks to a comment, this only works if you have python2.7 installed at the system level (e.g. /usr/bin/python2.7).

Otherwise, if you are using homebrew you can use the path to give you what you want.

virtualenv venv --python=/usr/local/bin/python

You can find the path to your python installation with

which python

This will also work with python 3.

which python3
>> /usr/local/bin/python3
virtualenv venv --python=/usr/local/bin/python3

Ultimately condensing to:

virtualenv venv -p `which python`
virtualenv venv -p `which python3`

回答 5

在Windows下对我来说这有效:

virtualenv --python=c:\Python25\python.exe envname

没有python.exeWindowsError: [Error 5] Access is denied 我有安装virtualenv 1.6.1的Python2.7.1,我想要python 2.5.2。

Under Windows for me this works:

virtualenv --python=c:\Python25\python.exe envname

without the python.exe I got WindowsError: [Error 5] Access is denied I have Python2.7.1 installed with virtualenv 1.6.1, and I wanted python 2.5.2.


回答 6

Mac OSX 10.6.8(Snow Leopard):

1)当您这样做时pip install virtualenv,pip命令与您的一个python版本相关联,virtualenv并被安装到该python版本中。你可以做

 $ which pip   

看看是什么版本的python。如果您看到类似以下内容:

 $ which pip
 /usr/local/bin/pip

然后做:

$ ls -al /usr/local/bin/pip
lrwxrwxr-x  1 root  admin  65 Apr 10  2015 /usr/local/bin/pip ->
../../../Library/Frameworks/Python.framework/Versions/2.7/bin/pip

您可以在输出中看到python版本。

默认情况下,它将是用于您创建的任何新环境的python版本。但是,您可以使用以下命令指定计算机上安装的任何版本的python,以便在新环境中使用-p flag

$ virtualenv -p python3.2 my_env  
Running virtualenv with interpreter /usr/local/bin/python3.2  
New python executable in my_env/bin/python  
Installing setuptools, pip...done.  

virtualenv my_env 将在当前目录中创建一个文件夹,其中将包含Python可执行文件以及pip [command]的副本,可用于安装其他软件包。

http://docs.python-guide.org/en/latest/dev/virtualenvs/

virtualenv 只需将python从您计算机上的某个位置复制到新创建的my_env / bin /目录中。

2)系统python在中/usr/bin,而我安装的各种python版本默认情况下安装在:

 /usr/local/bin

3)我安装的各种python的名称都类似于python2.7python3.2,我可以使用这些名称而不是完整路径。

========虚拟环境=========

1)我在使virtualenvwrapper正常工作时遇到一些问题。这就是我最后输入的内容~/.bash_profile

export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/django_projects  #Not very important -- mkproject command uses this
#Added the following based on: 
#http://stackoverflow.com/questions/19665327/virtualenvwrapper-installation-snow-leopard-python
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python2.7 
#source /usr/local/bin/virtualenvwrapper.sh
source /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh

2)-p option与virtualenvwrapper 的工作原理不同:我必须指定要在新环境中使用的python解释器的完整路径(当我不想使用默认的python版本时):

$ mkvirtualenv -p /usr/local/bin/python3.2 my_env
Running virtualenv with interpreter /usr/local/bin/python3
New python executable in my_env/bin/python
Installing setuptools, pip...done.
Usage: source deactivate

removes the 'bin' directory of the environment activated with 'source
activate' from PATH. 

与virtualenv不同,virtualenvwrapper将在$ WORKON_HOME环境变量指定的位置创建环境。这样可以将您所有的环境都放在一个地方。

Mac OSX 10.6.8 (Snow Leopard):

1) When you do pip install virtualenv, the pip command is associated with one of your python versions, and virtualenv gets installed into that version of python. You can do

 $ which pip   

to see what version of python that is. If you see something like:

 $ which pip
 /usr/local/bin/pip

then do:

$ ls -al /usr/local/bin/pip
lrwxrwxr-x  1 root  admin  65 Apr 10  2015 /usr/local/bin/pip ->
../../../Library/Frameworks/Python.framework/Versions/2.7/bin/pip

You can see the python version in the output.

By default, that will be the version of python that is used for any new environment you create. However, you can specify any version of python installed on your computer to use inside a new environment with the -p flag:

$ virtualenv -p python3.2 my_env  
Running virtualenv with interpreter /usr/local/bin/python3.2  
New python executable in my_env/bin/python  
Installing setuptools, pip...done.  

virtualenv my_env will create a folder in the current directory which will contain the Python executable files, and a copy of the pip [command] which you can use to install other packages.

http://docs.python-guide.org/en/latest/dev/virtualenvs/

virtualenv just copies python from a location on your computer into the newly created my_env/bin/ directory.

2) The system python is in /usr/bin, while the various python versions I installed were, by default, installed into:

 /usr/local/bin

3) The various pythons I installed have names like python2.7 or python3.2, and I can use those names rather than full paths.

========VIRTUALENVWRAPPER=========

1) I had some problems getting virtualenvwrapper to work. This is what I ended up putting in ~/.bash_profile:

export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/django_projects  #Not very important -- mkproject command uses this
#Added the following based on: 
#http://stackoverflow.com/questions/19665327/virtualenvwrapper-installation-snow-leopard-python
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python2.7 
#source /usr/local/bin/virtualenvwrapper.sh
source /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh

2) The -p option works differently with virtualenvwrapper: I have to specify the full path to the python interpreter to be used in the new environment(when I do not want to use the default python version):

$ mkvirtualenv -p /usr/local/bin/python3.2 my_env
Running virtualenv with interpreter /usr/local/bin/python3
New python executable in my_env/bin/python
Installing setuptools, pip...done.
Usage: source deactivate

removes the 'bin' directory of the environment activated with 'source
activate' from PATH. 

Unlike virtualenv, virtualenvwrapper will create the environment at the location specified by the $WORKON_HOME environment variable. That keeps all your environments in one place.


回答 7

这两个命令应该可以正常工作。

virtualenv -p python2 myenv (对于python2)

virtualenv -p python3 myenv (对于python3)

These two commands should work fine.

virtualenv -p python2 myenv (For python2)

virtualenv -p python3 myenv (For python3)


回答 8

假设您当前在virtualenv中安装了python 2.7。但是要使用python3.2,您必须使用以下命令进行更新:

$ virtualenv --python=/usr/bin/python3.2 name_of_your_virtualenv

然后通过以下方式激活您的virtualenv

$ source activate name_of_your_virtualenv

然后python --version在shell中执行:检查您的版本是否已更新。

Suppose you currently have python 2.7 installed in your virtualenv. But want to make use of python3.2, You would have to update this with:

$ virtualenv --python=/usr/bin/python3.2 name_of_your_virtualenv

Then activate your virtualenv by:

$ source activate name_of_your_virtualenv

and then do: python --version in shell to check whether your version is now updated.


回答 9

您可以virtualenv使用所需的python版本进行调用。例如:

python3 -m virtualenv venv

或者,直接指向您的virtualenv路径。例如,对于Windows:

c:\Python34\Scripts\virtualenv.exe venv

并通过运行:

venv/bin/python

Python 3.5.1 (v3.5.1:37a07cee5969, Dec  5 2015, 21:12:44) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

您可以看到虚拟环境中安装的python版本

You can call virtualenv with python version you want. For example:

python3 -m virtualenv venv

Or alternatively directly point to your virtualenv path. e.g. for windows:

c:\Python34\Scripts\virtualenv.exe venv

And by running:

venv/bin/python

Python 3.5.1 (v3.5.1:37a07cee5969, Dec  5 2015, 21:12:44) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

you can see the python version installed in virtual environment


回答 10

-p方法效果很好,但是您必须记住每次都使用它。如果您的目标是通常切换到较新版本的Python,那很痛苦,而且还可能导致错误。

您的另一种选择是设置一个环境变量,其作用与相同-p。通过~/.bashrc文件或在登录会话中管理环境变量的任何位置进行设置:

export VIRTUALENV_PYTHON=/path/to/desired/version

然后virtualenv,只要您未-p在命令行上指定,就可以使用它。

The -p approach works well, but you do have to remember to use it every time. If your goal is to switch to a newer version of Python generally, that’s a pain and can also lead to mistakes.

Your other option is to set an environment variable that does the same thing as -p. Set this via your ~/.bashrc file or wherever you manage environment variables for your login sessions:

export VIRTUALENV_PYTHON=/path/to/desired/version

Then virtualenv will use that any time you don’t specify -p on the command line.


回答 11

通过使用命令替换为您找到python2甚至更加容易:

virtualenv -p $(which python2) <path/to/new/virtualenv/>

或者在使用virtualenvwrapper时:

mkvirtualenv -p $(which python2) <env_name>

Even easier, by using command substitution to find python2 for you:

virtualenv -p $(which python2) <path/to/new/virtualenv/>

Or when using virtualenvwrapper :

mkvirtualenv -p $(which python2) <env_name>


回答 12

对于Mac(High Sierra),在python3上安装virtualenv并为python2创建virtualenv:

 $ python3 -m pip install virtualenv
 $ python3 -m virtualenv --python=python2 vp27
 $ source vp27/bin/activate
 (vp27)$ python --version
 Python 2.7.14

For Mac(High Sierra), install the virtualenv on python3 and create a virtualenv for python2:

 $ python3 -m pip install virtualenv
 $ python3 -m virtualenv --python=python2 vp27
 $ source vp27/bin/activate
 (vp27)$ python --version
 Python 2.7.14

回答 13

在Mac上,我使用pyenv和virtualenvwrapper。我必须创建一个新的virtualenv。您需要自制软件,如果您使用的是Mac,我假设您已经安装了自制软件,但这只是为了好玩:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"


brew install pyenv
pyenv install 2.7.10
pyenv global 2.7.10
export PATH=/Users/{USERNAME}/.pyenv/versions/2.7.10/bin:$PATH
mkvirtualenv -p ~/.pyenv/versions/2.7.10/bin/python  {virtual_env_name}

我也首先冻结了我的需求,因此我可以使用以下命令重新安装在新的virtualenv中:

pip install -r requirements.txt

On the mac I use pyenv and virtualenvwrapper. I had to create a new virtualenv. You need homebrew which I’ll assume you’ve installed if you’re on a mac, but just for fun:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"


brew install pyenv
pyenv install 2.7.10
pyenv global 2.7.10
export PATH=/Users/{USERNAME}/.pyenv/versions/2.7.10/bin:$PATH
mkvirtualenv -p ~/.pyenv/versions/2.7.10/bin/python  {virtual_env_name}

I also froze my requirements first so i could simply reinstall in the new virtualenv with:

pip install -r requirements.txt

回答 14

[2019年11月]我需要在基于Python 3.8的Arch Linux系统上安装Python 3.7环境(env)。Python 3.7不再存在于系统上,因此我无法降级Python以安装所需的软件包。

此外,我想在虚拟环境(venv)中使用该软件包/ Python 3.7。这就是我做的。


下载Python版本的源文件:

我从下载了Python 3.7.4源文件

https://www.python.org/downloads/source/

/mnt/Vancouver/apps/python_versions/src/Python-3.7.4.tgz

然后,我将该存档(源文件)提取到

/mnt/Vancouver/apps/python_versions/src/Python-3.7.4/


安装:

[注意:在我的系统中是env,不是venv。]

cd /mnt/Vancouver/apps/python_versions/src/Python-3.7.4/
time ./configure                 ## 17 sec
time make                        ## 1 min 51 sec
time sudo make install           ## 18 sec
time make clean                  ## 0.3 sec

检查已安装的Python版本:

$ which python
/usr/bin/python

$ python --version
Python 3.8.0

$ which python3.7
/usr/local/bin/python3.7

$ python    ## Python 3.8 [system / env]
Python 3.8.0 (default, Oct 23 2019, 18:51:26) 
[GCC 9.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

$ python3.7    ## newly-installed Python 3.7 package
Python 3.7.4 (default, Nov 20 2019, 11:36:53) 
[GCC 9.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.version)
3.7.4 (default, Nov 20 2019, 11:36:53) 
[GCC 9.2.0]
>>>

$ python3.7 --version                                                                                                 
Python 3.7.4

如何为特定的Python版本创建venv:

https://docs.python.org/3/tutorial/venv.html

12.2。创建虚拟环境

用于创建和管理虚拟环境的模块称为venvvenv通常会安装可用的最新版本的Python。如果您的系统上有多个Python版本,则可以通过运行python3或所需的任意版本来选择特定的Python版本。

要创建虚拟环境,请确定要放置目录的目录,然后使用带有目录路径的脚本运行venv模块:

python3 -m venv tutorial-env

tutorial-env如果该目录不存在,它将创建一个目录,并在其中创建包含Python解释器,标准库和各种支持文件的副本的目录。…


在[Python 3.8作业环境/系统上]建立Python 3.7 venv:

python3.7 -m venv ~/venv/py3.7      ## create Python 3.7-based venv
source ~/venv/py3.7/bin/activate    ## activate that venv
deactivate                          ## deactivate that venv (when done, there)

添加到~/.bashrc

alias p37='echo "   [Python 3.7 venv (source ~/venv/py3.7/bin/activate)]" && source ~/venv/py3.7/bin/activate'

测试Python 3.7 venv:

$ p37                                                                                                                 
[Python 3.7 venv (source ~/venv/py3.7/bin/activate)]

(py3.7)$ python --version
Python 3.7.4

(py3.7)$ python
Python 3.7.4 (default, Nov 20 2019, 11:36:53) 
[GCC 9.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.version)
3.7.4 (default, Nov 20 2019, 11:36:53) 
[GCC 9.2.0] 
>>>

[November 2019] I needed to install a Python 3.7 environment (env) on my Python 3.8-based Arch Linux system. Python 3.7 was no longer on the system, so I could not downgrade Python, to install a package that I needed.

Furthermore, I wanted to use that package / Python 3.7 inside a virtual environment (venv). This is how I did it.


Download Python version source files:

I downloaded the Python 3.7.4 source files from

https://www.python.org/downloads/source/

to

/mnt/Vancouver/apps/python_versions/src/Python-3.7.4.tgz

I then extracted that archive (source files) to

/mnt/Vancouver/apps/python_versions/src/Python-3.7.4/


Installation:

[Note: in my system env, not a venv.]

cd /mnt/Vancouver/apps/python_versions/src/Python-3.7.4/
time ./configure                 ## 17 sec
time make                        ## 1 min 51 sec
time sudo make install           ## 18 sec
time make clean                  ## 0.3 sec

Examine installed Python versions:

$ which python
/usr/bin/python

$ python --version
Python 3.8.0

$ which python3.7
/usr/local/bin/python3.7

$ python    ## Python 3.8 [system / env]
Python 3.8.0 (default, Oct 23 2019, 18:51:26) 
[GCC 9.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

$ python3.7    ## newly-installed Python 3.7 package
Python 3.7.4 (default, Nov 20 2019, 11:36:53) 
[GCC 9.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.version)
3.7.4 (default, Nov 20 2019, 11:36:53) 
[GCC 9.2.0]
>>>

$ python3.7 --version                                                                                                 
Python 3.7.4

How to create a venv for a specific Python version:

https://docs.python.org/3/tutorial/venv.html

12.2. CREATING VIRTUAL ENVIRONMENTS

The module used to create and manage virtual environments is called venv. venv will usually install the most recent version of Python that you have available. If you have multiple versions of Python on your system, you can select a specific Python version by running python3 or whichever version you want.

To create a virtual environment, decide upon a directory where you want to place it, and run the venv module as a script with the directory path:

python3 -m venv tutorial-env

This will create the tutorial-env directory if it doesn’t exist, and also create directories inside it containing a copy of the Python interpreter, the standard library, and various supporting files. …


Create Python 3.7 venv [on a Python 3.8 operating env / system]:

python3.7 -m venv ~/venv/py3.7      ## create Python 3.7-based venv
source ~/venv/py3.7/bin/activate    ## activate that venv
deactivate                          ## deactivate that venv (when done, there)

Added to ~/.bashrc:

alias p37='echo "   [Python 3.7 venv (source ~/venv/py3.7/bin/activate)]" && source ~/venv/py3.7/bin/activate'

Test Python 3.7 venv:

$ p37                                                                                                                 
[Python 3.7 venv (source ~/venv/py3.7/bin/activate)]

(py3.7)$ python --version
Python 3.7.4

(py3.7)$ python
Python 3.7.4 (default, Nov 20 2019, 11:36:53) 
[GCC 9.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.version)
3.7.4 (default, Nov 20 2019, 11:36:53) 
[GCC 9.2.0] 
>>>

回答 15

在Linux的Windows子系统中:

  1. 为python3创建环境:

    virtualenv --python=/usr/bin/python3 env
  2. 激活它:

    source env/bin/activate

In windows subsystem for linux:

  1. Create environment for python3:

    virtualenv --python=/usr/bin/python3 env
    
  2. Activate it:

    source env/bin/activate
    

回答 16

在Windows上:

py -3.4x32 -m venv venv34

要么

py -2.6.2 -m venv venv26

这将使用py启动器,它将为您找到正确的python可执行文件(假设您已安装了它)。

On windows:

py -3.4x32 -m venv venv34

or

py -2.6.2 -m venv venv26

This uses the py launcher which will find the right python executable for you (assuming you have it installed).


回答 17

是的,以上答案是正确的,并且在基于LinuxMAC OS X的基于Unix的系统上可以正常工作

我试图为Python2Python3创建virtualenv使用以下命令。

在这里,我已经使用venv2venv3作为其名称Python2Python3分别。

Python2»

MacBook-Pro-2:~ admin$ virtualenv venv2 --python=`which python2`
Running virtualenv with interpreter /usr/local/bin/python2
New python executable in /Users/admin/venv2/bin/python
Installing setuptools, pip, wheel...done.
MacBook-Pro-2:~ admin$ 
MacBook-Pro-2:~ admin$ ls venv2/bin/
activate        easy_install        pip2.7          python2.7
activate.csh        easy_install-2.7    python          wheel
activate.fish       pip         python-config
activate_this.py    pip2            python2
MacBook-Pro-2:~ admin$ 

Python3»

MacBook-Pro-2:~ admin$ virtualenv venv3 --python=`which python3`
Running virtualenv with interpreter /usr/local/bin/python3
Using base prefix '/Library/Frameworks/Python.framework/Versions/3.6'
New python executable in /Users/admin/venv3/bin/python3
Also creating executable in /Users/admin/venv3/bin/python
Installing setuptools, pip, wheel...done.
MacBook-Pro-2:~ admin$ 
MacBook-Pro-2:~ admin$ ls venv3/bin/
activate        easy_install        pip3.6          python3.6
activate.csh        easy_install-3.6    python          wheel
activate.fish       pip         python-config
activate_this.py    pip3            python3
MacBook-Pro-2:~ admin$ 

检查Python安装位置

MacBook-Pro-2:~ admin$ which python2
/usr/local/bin/python2
MacBook-Pro-2:~ admin$ 
MacBook-Pro-2:~ admin$ which python3
/usr/local/bin/python3
MacBook-Pro-2:~ admin$ 

Yes, the above answers are correct and works fine on Unix based systems like Linux & MAC OS X.

I tried to create virtualenv for Python2 & Python3 with the following commands.

Here I have used venv2 & venv3 as their names for Python2 & Python3 respectively.

Python2 »

MacBook-Pro-2:~ admin$ virtualenv venv2 --python=`which python2`
Running virtualenv with interpreter /usr/local/bin/python2
New python executable in /Users/admin/venv2/bin/python
Installing setuptools, pip, wheel...done.
MacBook-Pro-2:~ admin$ 
MacBook-Pro-2:~ admin$ ls venv2/bin/
activate        easy_install        pip2.7          python2.7
activate.csh        easy_install-2.7    python          wheel
activate.fish       pip         python-config
activate_this.py    pip2            python2
MacBook-Pro-2:~ admin$ 

Python3 »

MacBook-Pro-2:~ admin$ virtualenv venv3 --python=`which python3`
Running virtualenv with interpreter /usr/local/bin/python3
Using base prefix '/Library/Frameworks/Python.framework/Versions/3.6'
New python executable in /Users/admin/venv3/bin/python3
Also creating executable in /Users/admin/venv3/bin/python
Installing setuptools, pip, wheel...done.
MacBook-Pro-2:~ admin$ 
MacBook-Pro-2:~ admin$ ls venv3/bin/
activate        easy_install        pip3.6          python3.6
activate.csh        easy_install-3.6    python          wheel
activate.fish       pip         python-config
activate_this.py    pip3            python3
MacBook-Pro-2:~ admin$ 

Checking Python installation locations

MacBook-Pro-2:~ admin$ which python2
/usr/local/bin/python2
MacBook-Pro-2:~ admin$ 
MacBook-Pro-2:~ admin$ which python3
/usr/local/bin/python3
MacBook-Pro-2:~ admin$ 

回答 18

对我有用

sudo apt-get install python3-minimal

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

It worked for me

sudo apt-get install python3-minimal

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

回答 19

我使用pyenv来管理我的python版本。

pyenv install 3.7.3
pyenv local 3.7.3

检查您的python版本:

$ python --version
Python 3.7.3

使用venv创建虚拟环境:

python -m venv .

然后激活虚拟环境:

source bin/activate

检查您的python版本:

$ python --version
Python 3.7.3

您可能需要删除以前的虚拟环境

rm -rf bin

I use pyenv to manage my python version.

pyenv install 3.7.3
pyenv local 3.7.3

Check your python version:

$ python --version
Python 3.7.3

Create the virtual environment with venv:

python -m venv .

Then activate the Virtual Environment:

source bin/activate

Check your python version:

$ python --version
Python 3.7.3

You may need to remove the previous virtual environment

rm -rf bin

回答 20

对于Windows,这些似乎有些复杂。如果您使用的是运行python 3.3或更高版本的Windows,则可以使用python启动器py更加轻松地执行此操作。只需安装不同的python版本,然后运行:

py -[my version] -m venv env

这将env使用python在当前目录中创建一个虚拟环境[my version]。举个例子:

py -3.7 -m venv env
./env/Scripts/activate

这将创建一个env使用python3.7 的虚拟环境并将其激活。不需要路径或其他复杂的东西。

These seem a little overcomplicated for Windows. If you’re on Windows running python 3.3 or later, you can use the python launcher py to do this much more easily. Simply install the different python version, then run:

py -[my version] -m venv env

This will create a virtual environment called env in your current directory, using python [my version]. As an example:

py -3.7 -m venv env
./env/Scripts/activate

This creates a virtual environment called env using python3.7 and activates it. No paths or other complex stuff required.


回答 21

virtualenv -p python3 myenv

链接到创建virtualenv


回答 22

对于2019年的Debian(debian 9)系统,我发现了一个简单的解决方案,可以从虚拟环境中解决问题。

假设虚拟环境是通过以下方式创建的:

python3.7 -m venv myenv

但只有python2和的版本python2.7,因此您需要python3.7的最新功能。

然后,只需运行以下命令:

(myvenv) $ python3.7 -m venv --upgrade /home/username/path/to/myvenv/

如果系统上已经提供python3.7软件包,则会添加这些软件包。

For Debian (debian 9) Systems in 2019, I discovered a simple solution that may solve the problem from within the virtual environment.

Suppose the virtual environment were created via:

python3.7 -m venv myenv

but only has versions of python2 and python2.7, and you need the recent features of python3.7.

Then, simply running the command:

(myvenv) $ python3.7 -m venv --upgrade /home/username/path/to/myvenv/

will add python3.7 packages if they are already available on your system.


回答 23

这是virtualenv的错误。只需升级您的点子即可解决。

pip install --upgrade virtualenv

This was a bug with virtualenv. Just upgrading your pip should be the fix.

pip install --upgrade virtualenv


回答 24

正如在多个答案中已经提到的那样,使用virtualenv是一个干净的解决方案。但是,每个人都应该注意的一个小陷阱是,如果在bash_aliases中设置了python的别名,例如:

python=python3.6

该别名也将在虚拟环境中使用。因此,在这种情况下,无论使用什么解释器创建环境,python -V在虚拟环境中运行的始终将输出3.6

virtualenv venv --python=pythonX.X

As already mentioned in multiple answers, using virtualenv is a clean solution. However a small pitfall that everyone should be aware of is that if an alias for python is set in bash_aliases like:

python=python3.6

this alias will also be used inside the virtual environment. So in this scenario running python -V inside the virtual env will always output 3.6 regardless of what interpreter is used to create the environment:

virtualenv venv --python=pythonX.X

回答 25

它在Windows上使用python 2安装对我有用:

  1. 第1步:安装python 3版本。
  2. 步骤2:为虚拟环境创建一个env文件夹。
  3. 第3步:c:\ Python37 \ python -m venv c:\ path \ to \ env。

这就是我在现有python 2安装上创建Python 3虚拟环境的方式。

It worked for me on windows with python 2 installation :

  1. Step 1: Install python 3 version .
  2. Step 2: create a env folder for the virtual environment.
  3. Step 3 : c:\Python37\python -m venv c:\path\to\env.

This is how i created Python 3 virtual environment on my existing python 2 installation.


回答 26

您可以这样做:

virtualenv -p python3 .

You can do it by doing this:

virtualenv -p python3 .

回答 27

是的,您只需要安装其他版本的python,并在命令中定义其他版本的python的位置,例如:

virtualenv / home / payroll / Documents / env -p / usr / bin / python3

Yes you just need to install the other version of python, and define the location of your other version of python in your command like :

virtualenv /home/payroll/Documents/env -p /usr/bin/python3


回答 28

这是如何在Visual Studio Code文件夹中创建虚拟环境
的分步说明:我使用了Powershell(管理员模式):1.我在要创建虚拟环境的地方创建了VSCode文件夹-“ D:\ Code_Python_VE”。
2.接下来,我键入命令-“ pip3 install virtualenv”。(D:\ Code_Python_VE> pip3安装virtualenv)3. D:\ Code_Python_VE> python3 -m venv project_env
4. D:\ Code_Python_VE> project_env \ Scripts \ activate.bat
5. D:\ Code_Python_VE> ls-这将列出一个新的目录“ project_env”。
6. D:\ Code_Python_VE>代码。这将启动Visual Studio代码。确保命令是(代码。)。
7.创建具有以下内容的launch.jason:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "python",
            "request": "launch",
            "name": "Python: Current File (Integrated Terminal 1)",
            "program": "${file}"
        },
        {
            "name": "Python: Current File (Integrated Terminal 2)",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal"
        }
    ]
}

(请搜索如何转到“调试”窗口并在VS Code中添加新配置)。

  1. 在Visual Studio代码中按F1键,命令托盘将打开-选择Python Interpreter,然后选择虚拟环境project_env。
  2. 使用一条语句print(“ Hello World”)添加test.py文件。
  3. 运行该程序。
  4. 在Visual Studio Code终端-
    (project_env)d:\ Code_Python_VE> python -m pip install –upgrade
    希望对您有所帮助。

Here is the stepbystep how to create the Virtual environment in Visual Studio Code folder: I used Powershell (Administrator mode):
1. I create a VSCode folder – “D:\Code_Python_VE” where I want to create Virtual environment.
2. Next I type the command – “pip3 install virtualenv”. (D:\Code_Python_VE> pip3 install virtualenv) 3. D:\Code_Python_VE> python3 -m venv project_env
4. D:\Code_Python_VE>project_env\Scripts\activate.bat
5. D:\Code_Python_VE> ls – This will list a new directory “project_env”.
6. D:\Code_Python_VE> code . This will start Visual Studio Code. Make sure the command is (code .).
7. Create launch.jason with following content:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "type": "python",
            "request": "launch",
            "name": "Python: Current File (Integrated Terminal 1)",
            "program": "${file}"
        },
        {
            "name": "Python: Current File (Integrated Terminal 2)",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal"
        }
    ]
}

(Please search how to go to Debug window and Add new Configuration in VS Code).

  1. Press F1 in Visual studio code and the command pallet will open – Select Python Interpreter and select the virtual environment project_env.
  2. Add test.py file with one statement print(“Hello World”).
  3. Run this program.
  4. In Visual studio Code terminal –
    (project_env) d:\Code_Python_VE>python -m pip install –upgrade
    I hope this helps.

回答 29

UBUNTU 19.04 /全球Python 3.7。

这对我有用,使用推荐的venv进行python 3开发,从而启用了python 3.8环境。

安装3.8和3.8 venv模块

$ sudo apt install python3.8 python3.8-venv ##以及您需要的任何其他模块

使用您要在该环境中创建的python版本创建虚拟环境

$ /usr/bin/python3.8 -m venv python38-env

切换到您的虚拟环境

$源python38-env / bin / activate

python -V = python 3.8

UBUNTU 19.04 / Global Python 3.7.

This worked for me, enabling a Python 3.8 environment using the recommended venv for python 3 development.

Install 3.8 and 3.8 venv module

$ sudo apt install python3.8 python3.8-venv ## plus any other modules you need

Create your Virtual Env using the python version you want in that env

$ /usr/bin/python3.8 -m venv python38-env

switch into your virtual env

$ source python38-env/bin/activate

python -V = python 3.8


如何根据本地目录中的requirements.txt文件使用pip安装软件包?

问题:如何根据本地目录中的requirements.txt文件使用pip安装软件包?

这是问题所在

我有一个require.txt看起来像:

BeautifulSoup==3.2.0
Django==1.3
Fabric==1.2.0
Jinja2==2.5.5
PyYAML==3.09
Pygments==1.4
SQLAlchemy==0.7.1
South==0.7.3
amqplib==0.6.1
anyjson==0.3
...

我有一个本地存档目录,其中包含所有软件包和其他软件包。

我创建了一个新的virtualenv

bin/virtualenv testing

激活它后,我尝试根据本地存档目录中的requirements.txt安装软件包。

source bin/activate
pip install -r /path/to/requirements.txt -f file:///path/to/archive/

我得到一些输出,似乎表明安装正常

Downloading/unpacking Fabric==1.2.0 (from -r ../testing/requirements.txt (line 3))
  Running setup.py egg_info for package Fabric
    warning: no previously-included files matching '*' found under directory 'docs/_build'
    warning: no files found matching 'fabfile.py'
Downloading/unpacking South==0.7.3 (from -r ../testing/requirements.txt (line 8))
  Running setup.py egg_info for package South
....

但后来检查发现该软件包均未正确安装。我无法导入软件包,但在virtualenv的site-packages目录中找不到任何软件包。那么出了什么问题?

Here is the problem

I have a requirements.txt that looks like:

BeautifulSoup==3.2.0
Django==1.3
Fabric==1.2.0
Jinja2==2.5.5
PyYAML==3.09
Pygments==1.4
SQLAlchemy==0.7.1
South==0.7.3
amqplib==0.6.1
anyjson==0.3
...

I have a local archive directory containing all the packages + others.

I have created a new virtualenv with

bin/virtualenv testing

upon activating it, I tried to install the packages according to requirements.txt from the local archive directory.

source bin/activate
pip install -r /path/to/requirements.txt -f file:///path/to/archive/

I got some output that seems to indicate that the installation is fine

Downloading/unpacking Fabric==1.2.0 (from -r ../testing/requirements.txt (line 3))
  Running setup.py egg_info for package Fabric
    warning: no previously-included files matching '*' found under directory 'docs/_build'
    warning: no files found matching 'fabfile.py'
Downloading/unpacking South==0.7.3 (from -r ../testing/requirements.txt (line 8))
  Running setup.py egg_info for package South
....

But later check revealed none of the package is installed properly. I cannot import the package, and none is found in the site-packages directory of my virtualenv. So what went wrong?


回答 0

这对我有用:

$ pip install -r requirements.txt --no-index --find-links file:///tmp/packages

--no-index-忽略软件包索引(仅查看--find-linksURL)。

-f, --find-links <URL>-如果是URL或html文件的路径,请解析出指向归档文件的链接。如果是file://目录的本地路径或URL,请在目录列表中查找档案。

This works for me:

$ pip install -r requirements.txt --no-index --find-links file:///tmp/packages

--no-index – Ignore package index (only looking at --find-links URLs instead).

-f, --find-links <URL> – If a URL or path to an html file, then parse for links to archives. If a local path or file:// URL that’s a directory, then look for archives in the directory listing.


回答 1

我已经阅读了上面的内容,意识到这是一个古老的问题,但它仍未完全解决,仍然位于我的Google搜索结果的顶部,因此,这是一个适用于所有人的答案:

pip install -r /path/to/requirements.txt

I’ve read the above, realize this is an old question, but it’s totally unresolved and still at the top of my google search results so here’s an answer that works for everyone:

pip install -r /path/to/requirements.txt

回答 2

为了使virtualenv将所有文件安装在requirements.txt文件中。

  1. cd到requirements.txt所在的目录
  2. 激活您的虚拟环境
  3. 运行: pip install -r requirements.txt 在您的外壳中

For virtualenv to install all files in the requirements.txt file.

  1. cd to the directory where requirements.txt is located
  2. activate your virtualenv
  3. run: pip install -r requirements.txt in your shell

回答 3

我有一个类似的问题。我尝试了这个:

pip install -U -r requirements.txt 

(-U =更新(如果已安装))

但是问题仍然存在。我意识到缺少一些通用的开发库。

sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk

我不知道这是否对您有帮助。

I had a similar problem. I tried this:

pip install -U -r requirements.txt 

(-U = update if it had already installed)

But the problem continued. I realized that some of generic libraries for development were missed.

sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk

I don’t know if this would help you.


回答 4

pip install -r requirements.txt

有关更多详细信息,请检查帮助选项。

pip install --help

我们可以找到选项“ -r”

-r,–requirement从给定的需求文件安装。此选项可以多次使用。

有关一些常用的pip安装选项的更多信息:(这是pip install命令上的帮助选项)

以上是完整的选项集。请使用pip install –help获得完整的选项列表。

pip install -r requirements.txt

For further details please check the help option.

pip install --help

We can find the option ‘-r’

-r, –requirement Install from the given requirements file. This option can be used multiple times.

Further information on some commonly used pip install options: (This is the help option on pip install command)

Also the above is the complete set of options. Please use pip install –help for complete list of options.


回答 5

简短答案

pip install -r /path/to/requirements.txt

或其他形式:

python -m pip install -r /path/to/requirements.txt

说明

在这里,-r是的缩写--requirement,它要求pip从给定的requirements文件进行安装。

pip只有在检查了requirements文件中所有列出的项目的可用性之后,它才会开始安装,即使有一个项目也不会开始安装requirement不可用。

安装可用软件包的一种解决方法是逐一安装列出的软件包。为此使用以下命令。将显示红色警告,以通知您有关不可用的软件包的信息。

cat requirements.txt | xargs -n 1 pip install

要忽略注释(以开头的行#)和空白行,请使用:

cat requirements.txt | cut -f1 -d"#" | sed '/^\s*$/d' | xargs -n 1 pip install

Short answer

pip install -r /path/to/requirements.txt

or in another form:

python -m pip install -r /path/to/requirements.txt

Explanation

Here, -r is short form of --requirement and it asks the pip to install from the given requirements file.

pip will start installation only after checking the availability of all listed items in the requirements file and it won’t start installation even if one requirement is unavailable.

One workaround to install the available packages is installing listed packages one by one. Use the following command for that. A red color warning will be shown to notify you about the unavailable packages.

cat requirements.txt | xargs -n 1 pip install

To ignore comments (lines starting with a #) and blank lines, use:

cat requirements.txt | cut -f1 -d"#" | sed '/^\s*$/d' | xargs -n 1 pip install

回答 6

通常,您将需要从本地档案中快速安装,而无需探究PyPI。

首先,下载符合您要求的档案:

$ pip install --download <DIR> -r requirements.txt

然后,使用–find-links和安装–no-index

$ pip install --no-index --find-links=[file://]<DIR> -r requirements.txt

Often, you will want a fast install from local archives, without probing PyPI.

First, download the archives that fulfill your requirements:

$ pip install --download <DIR> -r requirements.txt

Then, install using –find-links and –no-index:

$ pip install --no-index --find-links=[file://]<DIR> -r requirements.txt

回答 7

我使用了很多系统,这些系统被开发人员“遵循他们在互联网上找到的指示”所破坏。您pip和您使用python的路径/站点程序包不同,这是非常普遍的。因此,当我遇到奇怪的事物时,我首先要做的是:

$ python -c 'import sys; print(sys.path)'
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages']

$ pip --version
pip 9.0.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)

那是一个快乐的系统

下面是一个不愉快的系统。(或者至少是一个幸福无知的系统,导致其他人感到不高兴。)

$ pip --version
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)

$ python -c 'import sys; print(sys.path)'
['', '/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/site-packages']

$ which pip pip2 pip3
/usr/local/bin/pip
/usr/local/bin/pip3

不高兴,因为pip(python3.6和)正在使用/usr/local/lib/python3.6/site-packageswhile python是(python2.7和)正在使用/usr/local/lib/python2.7/site-packages

当我要确保将要求安装到正确的 python时,请执行以下操作:

$ which -a python python2 python3
/usr/local/bin/python
/usr/bin/python
/usr/local/bin/python2
/usr/local/bin/python3

$ /usr/bin/python -m pip install -r requirements.txt

您听说过,“如果它没有损坏,请不要尝试对其进行修复。” DevOps的版本是“如果您没有破坏它并且可以解决它,请不要尝试对其进行修复。”

I work with a lot of systems that have been mucked by developers “following directions they found on the internet”. It is extremely common that your pip and your python are not looking at the same paths/site-packages. For this reason, when I encounter oddness I start by doing this:

$ python -c 'import sys; print(sys.path)'
['', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu',
'/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old',
'/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages',
'/usr/lib/python2.7/dist-packages']

$ pip --version
pip 9.0.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)

That is a happy system.

Below is an unhappy system. (Or at least it’s a blissfully ignorant system that causes others to be unhappy.)

$ pip --version
pip 9.0.1 from /usr/local/lib/python3.6/site-packages (python 3.6)

$ python -c 'import sys; print(sys.path)'
['', '/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
'/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
'/usr/local/lib/python2.7/site-packages']

$ which pip pip2 pip3
/usr/local/bin/pip
/usr/local/bin/pip3

It is unhappy because pip is (python3.6 and) using /usr/local/lib/python3.6/site-packages while python is (python2.7 and) using /usr/local/lib/python2.7/site-packages

When I want to make sure I’m installing requirements to the right python, I do this:

$ which -a python python2 python3
/usr/local/bin/python
/usr/bin/python
/usr/local/bin/python2
/usr/local/bin/python3

$ /usr/bin/python -m pip install -r requirements.txt

You’ve heard, “If it ain’t broke, don’t try to fix it.” The DevOps version of that is, “If you didn’t break it and you can work around it, don’t try to fix it.”


回答 8

首先,创建一个虚拟环境

在python 3.6中

virtualenv --python=/usr/bin/python3.6 <path/to/new/virtualenv/>

在python 2.7中

virtualenv --python=/usr/bin/python2.7 <path/to/new/virtualenv/>

然后激活环境并安装require.txt文件中所有可用的软件包。

source <path/to/new/virtualenv>/bin/activate
pip install -r <path/to/requirement.txt>

first of all, create a virtual environment

in python 3.6

virtualenv --python=/usr/bin/python3.6 <path/to/new/virtualenv/>

in python 2.7

virtualenv --python=/usr/bin/python2.7 <path/to/new/virtualenv/>

then activate the environment and install all the packages available in the requirement.txt file.

source <path/to/new/virtualenv>/bin/activate
pip install -r <path/to/requirement.txt>

回答 9

使用python 3在虚拟环境中安装Requirements.txt文件:

我遇到过同样的问题。我试图在虚拟环境中安装requirements.txt文件。我找到了解决方案。

最初,我以这种方式创建了虚拟环境:

virtualenv -p python3 myenv

使用以下方法激活环境:

source myenv/bin/activate

现在,我使用以下命令安装了requirements.txt:

pip3 install -r requirements.txt

安装成功,我能够导入模块。

Installing requirements.txt file inside virtual env with python 3:

I had the same issue. I was trying to install requirements.txt file inside a virtual environament. I found the solution.

Initially, I created my virtual env in this way:

virtualenv -p python3 myenv

Activate the environment using:

source myenv/bin/activate

Now I installed the requirements.txt using:

pip3 install -r requirements.txt

Installation was successful and I was able to import the modules.


回答 10

尝试这个

python -m pip install -r requirements.txt

try this

python -m pip install -r requirements.txt

回答 11

pip install --user -r requirements.txt 

要么

pip3 install --user -r requirements.txt 
pip install --user -r requirements.txt 

OR

pip3 install --user -r requirements.txt 

venv,pyvenv,pyenv,virtualenv,virtualenvwrapper,pipenv等有什么区别?

问题:venv,pyvenv,pyenv,virtualenv,virtualenvwrapper,pipenv等有什么区别?

Python 3.3在其标准库中包含了新软件包venv。它有什么作用?与似乎与regex匹配的所有其他软件包(py)?(v|virtual|pip)?env有何不同?

Python 3.3 includes in its standard library the new package venv. What does it do, and how does it differ from all the other packages that seem to match the regex (py)?(v|virtual|pip)?env?


回答 0

PyPI软件包不在标准库中:

  • virtualenv是一个非常流行的工具,可为Python库创建隔离的Python环境。如果您不熟悉此工具,我强烈建议您学习它,因为它是非常有用的工具,在本答案的其余部分中,我将对其进行比较。

    它的工作方式是在目录(例如:)中安装一堆文件env/,然后修改PATH环境变量以在其之前添加自定义bin目录(例如:)env/bin/。在完全相同的副本pythonpython3二进制文件放在这个目录中,但是Python编程寻找相对于其路径优先库,环境中的目录。它不是Python标准库的一部分,但是受到PyPA(Python包装管理局)的正式认可。激活后,您可以使用在虚拟环境中安装软件包pip

  • pyenv用于隔离Python版本。例如,您可能想针对Python 2.7、3.6、3.7和3.8测试代码,因此需要一种在它们之间切换的方法。一旦被激活,它的前缀PATH与环境变量~/.pyenv/shims,那里有专用的文件相匹配的Python命令(pythonpip)。这些不是Python附带命令的副本。它们是特殊的脚本,它们可以根据PYENV_VERSION环境变量,.python-version文件或~/.pyenv/version文件即时确定要运行哪个版本的Python 。pyenv使用命令,还可以简化下载和安装多个Python版本的过程pyenv install

  • pyenv-virtualenv是一个插件pyenv由同一作者的pyenv,允许你使用pyenvvirtualenv在同一时间方便。但是,如果您使用的是Python 3.3或更高版本,请pyenv-virtualenv尝试运行python -m venv它(如果有),而不是virtualenv。如果您不希望使用便利功能,则可以在不使用的情况下一起使用virtualenv和。pyenvpyenv-virtualenv

  • virtualenvwrappervirtualenv(参见docs)的一组扩展。它为您提供诸如mkvirtualenv,的命令,lssitepackages尤其是workon在不同virtualenv目录之间切换时。如果您需要多个virtualenv目录,此工具特别有用。

  • pyenv-virtualenvwrapperpyenv与作者相同的插件pyenv,可以方便地集成virtualenvwrapperpyenv

  • pipenv旨在结合Pipfilepipvirtualenv为在命令行一个命令。该virtualenv目录通常放置在中~/.local/share/virtualenvs/XXXXXX是项目目录路径的哈希值。这与不同virtualenv,后者的目录通常位于当前工作目录中。pipenv是指在开发Python应用程序(而不是库)时使用。还有的替代品pipenv,例如poetry,我将不在此处列出,因为该问题仅与名称相似的软件包有关。

标准库:

  • pyvenv是Python 3附带的脚本,但由于存在问题(更不用说混乱的名称了)而在Python 3.6中不推荐使用。在Python 3.6及更高版本中,确切的等效项是python3 -m venv

  • venv是Python 3附带的软件包,您可以使用它运行python3 -m venv(尽管出于某些原因,某些发行版将其分成了单独的发行版软件包,例如python3-venv在Ubuntu / Debian上)。它的作用与相同virtualenv,但仅具有部分功能(请参见此处的比较)。virtualenv继续比受欢迎venv,尤其是因为前者同时支持Python 2和3。

给初学者的建议:

这是我对初学者的个人建议:首先学习virtualenvpip,这些工具可在各种情况下与Python 2和3一起使用,并在需要时选择其他工具。

PyPI packages not in the standard library:

  • virtualenv is a very popular tool that creates isolated Python environments for Python libraries. If you’re not familiar with this tool, I highly recommend learning it, as it is a very useful tool, and I’ll be making comparisons to it for the rest of this answer.

    It works by installing a bunch of files in a directory (eg: env/), and then modifying the PATH environment variable to prefix it with a custom bin directory (eg: env/bin/). An exact copy of the python or python3 binary is placed in this directory, but Python is programmed to look for libraries relative to its path first, in the environment directory. It’s not part of Python’s standard library, but is officially blessed by the PyPA (Python Packaging Authority). Once activated, you can install packages in the virtual environment using pip.

  • pyenv is used to isolate Python versions. For example, you may want to test your code against Python 2.7, 3.6, 3.7 and 3.8, so you’ll need a way to switch between them. Once activated, it prefixes the PATH environment variable with ~/.pyenv/shims, where there are special files matching the Python commands (python, pip). These are not copies of the Python-shipped commands; they are special scripts that decide on the fly which version of Python to run based on the PYENV_VERSION environment variable, or the .python-version file, or the ~/.pyenv/version file. pyenv also makes the process of downloading and installing multiple Python versions easier, using the command pyenv install.

  • pyenv-virtualenv is a plugin for pyenv by the same author as pyenv, to allow you to use pyenv and virtualenv at the same time conveniently. However, if you’re using Python 3.3 or later, pyenv-virtualenv will try to run python -m venv if it is available, instead of virtualenv. You can use virtualenv and pyenv together without pyenv-virtualenv, if you don’t want the convenience features.

  • virtualenvwrapper is a set of extensions to virtualenv (see docs). It gives you commands like mkvirtualenv, lssitepackages, and especially workon for switching between different virtualenv directories. This tool is especially useful if you want multiple virtualenv directories.

  • pyenv-virtualenvwrapper is a plugin for pyenv by the same author as pyenv, to conveniently integrate virtualenvwrapper into pyenv.

  • pipenv aims to combine Pipfile, pip and virtualenv into one command on the command-line. The virtualenv directory typically gets placed in ~/.local/share/virtualenvs/XXX, with XXX being a hash of the path of the project directory. This is different from virtualenv, where the directory is typically in the current working directory. pipenv is meant to be used when developing Python applications (as opposed to libraries). There are alternatives to pipenv, such as poetry, which I won’t list here since this question is only about the packages that are similarly named.

Standard library:

  • pyvenv is a script shipped with Python 3 but deprecated in Python 3.6 as it had problems (not to mention the confusing name). In Python 3.6+, the exact equivalent is python3 -m venv.

  • venv is a package shipped with Python 3, which you can run using python3 -m venv (although for some reason some distros separate it out into a separate distro package, such as python3-venv on Ubuntu/Debian). It serves the same purpose as virtualenv, but only has a subset of its features (see a comparison here). virtualenv continues to be more popular than venv, especially since the former supports both Python 2 and 3.

Recommendation for beginners:

This is my personal recommendation for beginners: start by learning virtualenv and pip, tools which work with both Python 2 and 3 and in a variety of situations, and pick up other tools once you start needing them.


回答 1

我只是避免virtualenv在Python3.3 +之后使用,而是使用标准附带的库venv。要创建新的虚拟环境,请输入:

$ python3 -m venv <MYVENV>  

virtualenv尝试将Python二进制文件复制到虚拟环境的bin目录中。但是,它不会更新嵌入到该二进制文件中的库文件链接,因此,如果您将Python从源代码构建到具有相对路径名的非系统目录中,则Python二进制文件会中断。由于这是使副本可分发的Python的方式,因此这是一个很大的缺陷。BTW使用来检查OS X上的嵌入式库文件链接otool。例如,在您的虚拟环境中,键入:

$ otool -L bin/python
python:
    @executable_path/../Python (compatibility version 3.4.0, current version 3.4.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1238.0.0)

因此,我会避免virtualenvwrapperpipenvpyvenv不推荐使用。pyenv似乎是经常使用的地方virtualenv使用,但我会远离它也因为我觉得venv还做什么pyenv是对建。

venv使用用户可安装的库在外壳中创建新的沙盒化的虚拟环境,并且它是多Python安全的新鲜的,因为虚拟环境只能用标准库启动船舶与Python,你必须与各地重新安装任何其他库,而虚拟环境是积极的。沙盒化,因为在虚拟环境外部看不到这些新库安装,因此您可以删除整个环境并重新启动,而不必担心会影响基本的python安装。用户可安装的库,因为创建虚拟环境的目标文件夹时没有pip installsudo在您已经拥有的某个目录中,因此您不需要sudo权限就可以在其中安装库。最终,它是多python安全的,因为在激活虚拟环境时,shell仅看到用于构建该虚拟环境的python版本(3.4、3.5等)。

pyenv类似于venv,它可以让您管理多个python环境。但是,pyenv由于无法方便地将库安装回滚到某些开始状态,因此您admin有时可能需要特权来更新库。所以我认为也最好使用venv

在过去的两年中,我发现了构建系统中的许多问题(emacs软件包,python独立应用程序构建器,安装程序…),最终归结为virtualenv。我认为当我们取消此附加选项并仅使用时,python将是一个更好的平台venv

I would just avoid the use of virtualenv after Python3.3+ and instead use the standard shipped library venv. To create a new virtual environment you would type:

$ python3 -m venv <MYVENV>  

virtualenv tries to copy the Python binary into the virtual environment’s bin directory. However it does not update library file links embedded into that binary, so if you build Python from source into a non-system directory with relative path names, the Python binary breaks. Since this is how you make a copy distributable Python, it is a big flaw. BTW to inspect embedded library file links on OS X, use otool. For example from within your virtual environment, type:

$ otool -L bin/python
python:
    @executable_path/../Python (compatibility version 3.4.0, current version 3.4.0)
    /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1238.0.0)

Consequently I would avoid virtualenvwrapper and pipenv. pyvenv is deprecated. pyenv seems to be used often where virtualenv is used but I would stay away from it also since I think venv also does what pyenv is built for.

venv creates virtual environments in the shell that are fresh and sandboxed, with user-installable libraries, and it’s multi-python safe. Fresh because virtual environments only start with the standard libraries that ship with python, you have to install any other libraries all over again with pip install while the virtual environment is active. Sandboxed because none of these new library installs are visible outside the virtual environment, so you can delete the whole environment and start again without worrying about impacting your base python install. User-installable libraries because the virtual environment’s target folder is created without sudo in some directory you already own, so you won’t need sudo permissions to install libraries into it. Finally it is multi-python safe, since when virtual environments activate, the shell only sees the python version (3.4, 3.5 etc.) that was used to build that virtual environment.

pyenv is similar to venv in that it lets you manage multiple python environments. However with pyenv you can’t conveniently rollback library installs to some start state and you will likely need admin privileges at some point to update libraries. So I think it is also best to use venv.

In the last couple of years I have found many problems in build systems (emacs packages, python standalone application builders, installers…) that ultimately come down to issues with virtualenv. I think python will be a better platform when we eliminate this additional option and only use venv.


回答 2

我掉进了pipenv兔子洞(的确是个黑洞和黑洞……),因为最后一个答案是两年多以前的,所以觉得有必要用有关Python虚拟信封主题的最新进展来更新讨论非常有用。找到了。

免责声明:

这个答案是不是对继续有关的优点的激烈参数pipenv VENV如信封解决方案- 我并没有任代言。这是关于PyPA赞同冲突的标准,以及如何未来发展的virtualenv承诺否定制造要么/或它们之间选择的话。我专注于这两个工具正是因为它们是PyPA的受膏工具。

静脉

如OP所述,venv是用于虚拟化环境的工具。不是第三方解决方案,而是本机工具。PyPA认可venv用于创建虚拟信封:“ 在3.5版中进行了更改:现在建议使用venv创建虚拟环境 ”。

吹牛

pipenv- venv-可以用于创建虚拟信封,但是还可以引入包管理和漏洞检查功能。通过使用 Pipfile交付软件包管理requirements.txt,而不是使用。当 PyPA认可pipenv用于包管理时,这似乎意味着取代了。pipenvpipfilerequirements.txt

但是pipenv使用virtualenv作为创建虚拟信封的工具,而不是 venvPyPA认可它为创建虚拟信封的必备工具。

标准冲突:

因此,如果解决虚拟信封解决方案还不够困难,那么我们现在让PyPA认可使用不同虚拟信封解决方案的两个不同工具。Github关于venv vs virtualenv的激烈辩论可以在这里找到该冲突的重点。

解决冲突:

上面链接中提到的Github辩论已经引导了virtualenv的开发,以适应将来的发行版中venv发展

首选内置venv:如果目标python拥有venv,我们将使用该环境创建环境(然后对其进行后续操作以促进我们提供的其他保证)

结论:

因此,看起来这两个相互竞争的虚拟信封解决方案之间将会有一些未来的融合,但是截至目前,pipenv(使用的)virtualenv与有所不同venv

鉴于pipenv解决的问题以及PyPA给予的祝福,它似乎拥有光明的前景。而且,如果virtualenv实现了其建议的开发目标,那么选择pipenvvenv不再是选择虚拟信封解决方案的理由

I’ve went down the pipenv rabbit hole (it’s a deep and dark hole indeed…) and since the last answer is over 2 years ago, felt it was useful to update the discussion with the latest developments on the Python virtual envelopes topic I’ve found.

DISCLAIMER:

This answer is NOT about continuing the raging debate about the merits of pipenv versus venv as envelope solutions- I make no endorsement of either. It’s about PyPA endorsing conflicting standards and how future development of virtualenv promises to negate making an either/or choice between them at all. I focused on these two tools precisely because they are the anointed ones by PyPA.

venv

As the OP notes, venv is a tool for virtualizing environments. NOT a third party solution, but native tool. PyPA endorses venv for creating VIRTUAL ENVELOPES: “Changed in version 3.5: The use of venv is now recommended for creating virtual environments“.

pipenv

pipenv– like venv – can be used to create virtual envelopes but additionally rolls-in package management and vulnerability checking functionality. Instead of using requirements.txt, pipenv delivers package management via Pipfile. As PyPA endorses pipenv for PACKAGE MANAGEMENT, that would seem to imply pipfile is to supplant requirements.txt.

HOWEVER: pipenv uses virtualenv as its tool for creating virtual envelopes, NOT venv which is endorsed by PyPA as the go-to tool for creating virtual envelopes.

Conflicting Standards:

So if settling on a virtual envelope solution wasn’t difficult enough, we now have PyPA endorsing two different tools which use different virtual envelope solutions. The raging Github debate on venv vs virtualenv which highlights this conflict can be found here.

Conflict Resolution:

The Github debate referenced in above link has steered virtualenv development in the direction of accommodating venv in future releases:

prefer built-in venv: if the target python has venv we’ll create the environment using that (and then perform subsequent operations on that to facilitate other guarantees we offer)

Conclusion:

So it looks like there will be some future convergence between the two rival virtual envelope solutions, but as of now pipenv– which uses virtualenv – varies materially from venv.

Given the problems pipenv solves and the fact that PyPA has given its blessing, it appears to have a bright future. And if virtualenv delivers on its proposed development objectives, choosing a virtual envelope solution should no longer be a case of either pipenv OR venv.


回答 3

2020年4月更新

当我看到这篇文章时,我正在寻找相同的内容。我认为对于像我这样的新Python用户而言,使用什么工具这个问题非常令人困惑和困难。这直接来自PyPA网站上关于pipenv的信息:

虽然本教程将pipenv项目作为工具主要集中在Python应用程序开发而不是Python库开发上,但该项目本身目前正在解决多个流程和维护问题,这些问题阻止了bug修复和新功能的发布(整个2019年过去了,而没有新版本)。这意味着,在短期内,pipenv仍然会遇到一些怪癖和性能问题,而没有明确解决这些问题的时间表。

尽管情况仍然如此,但项目维护人员可能希望研究其他用于应用程序依赖性管理的工具,以代替pipenv或与之一起使用。

假设2020年4月发布的pipenv按计划进行,此后的发布也仍在进行中,那么该教程中的警告将被删除。如果这些发行版不符合要求,那么教程本身将被删除,并替换为可用的依赖项管理选项上的讨论页。

April 2020 Update

I was searching for same when I came across this post. I think this issue of what tool to use is quite confusing and difficult for new Python users like me. This is directly from PyPA website regarding pipenv:

While this tutorial covers the pipenv project as a tool that focuses primarily on the needs of Python application development rather than Python library development, the project itself is currently working through several process and maintenance issues that are preventing bug fixes and new features from being published (with the entirety of 2019 passing without a new release). This means that in the near term, pipenv still suffers from several quirks and performance problems without a clear timeline for resolution of those isses.

While this remains the case, project maintainers are likely to want to investigate Other Tools for Application Dependency Management for use instead of, or together with, pipenv.

Assuming the April 2020 pipenv release goes ahead as planned, and the release after that also remains on track, then this caveat on the tutorial will be removed. If those releases don’t remain on track, then the tutorial itself will be removed, and replaced with a discussion page on the available dependency management options.


Pipenv-面向人类的Python开发工作流

Pipenv 是一个旨在带来最好的包装世界的工具(捆扎师、作曲家、NPM、货物、纱线等)来到Python世界在我们的世界里,Windows是一等公民

它会自动为您的项目创建和管理一个虚拟环境,并在您的Pipfile当您安装/卸载软件包时。它还产生了非常重要的Pipfile.lock,它用于生成确定性构建。

Pipenv寻求解决的问题是多方面的:

  • 您不再需要使用pipvirtualenv分开的。他们一起工作
  • 管理requirements.txt文件can be
    problematic
    ,因此Pipenv使用即将到来的PipfilePipfile.lock取而代之的是,对于基本用例,哪个更优越
  • 散列总是在任何地方使用。保安。自动暴露安全漏洞
  • 让您深入了解依赖关系图(例如$ pipenv graph)
  • 通过加载简化开发工作流.env文件

您可以在浏览器中快速播放Pipenv:

安装

如果您使用的是Debian Buster+:

$ sudo apt install pipenv

或者,如果您使用的是Fedora:

$ sudo dnf install pipenv

或者,如果您使用的是FreeBSD:

# pkg install py36-pipenv

或者,如果您使用的是Windows:

# pip install --user pipenv

当以上选项都不存在时,建议使用Pipx

$ pipx install pipenv

否则,请参阅documentation有关说明,请参阅

✨🍰✨

☤用户表彰

大卫·刚(David Gang)

这个包管理器真的很棒。这是我第一次确切地知道我安装的依赖项是什么,以及可传递依赖项是什么。再加上安装是确定性的这一事实,使得这个包管理器像货物一样是一流的

贾斯汀·迈尔斯·福尔摩斯

Pipenv最终是一种抽象,其目的是让头脑参与进来,而不仅仅是文件系统

☤功能

  • 真正实现确定性构建,同时轻松指定只有你想要的
  • 生成并检查锁定依赖项的文件哈希
  • 自动安装所需的Python,如果pyenv有空房吗?
  • 自动递归地查找您的项目主目录,方法是查找Pipfile
  • 自动生成一个Pipfile,如果不存在
  • 自动在标准位置创建一个Virtualenv
  • 自动将包添加/删除到Pipfile卸载/安装它们时
  • 自动加载.env文件(如果存在)

主要命令有installuninstall,以及lock,它会生成一个Pipfile.lock这些都是用来取代$ pip install用法以及手动虚拟环境管理(要激活虚拟环境,请运行$ pipenv shell)

基本概念

  • 当虚拟环境不存在时,将自动创建一个虚拟环境
  • 当没有参数传递给install,所有套餐[packages]将安装指定的
  • 要初始化Python 3虚拟环境,请运行$ pipenv --three
  • 要初始化Python 2虚拟环境,请运行$ pipenv --two
  • 否则,无论viralenv缺省值是什么,都将是缺省值

其他命令

  • shell将在激活了viralenv的情况下生成一个shell
  • run将运行来自Virtualenv的给定命令,并转发任何参数(例如$ pipenv run python)
  • check断言当前环境满足PEP 508要求
  • graph将打印所有已安装依赖项的漂亮图表

外壳完井

例如,对于鱼,把这个放在你的~/.config/fish/completions/pipenv.fish

eval (pipenv --completion)

或者,使用bash,将此内容放入您的.bashrc.bash_profile

eval "$(pipenv --completion)"

魔术外壳完成现已启用!还有一个fish
plugin
,它将自动为您激活您的子壳!

鱼是最好的贝壳。你应该用它

☤使用率

$ pipenv
Usage: pipenv [OPTIONS] COMMAND [ARGS]...

Options:
  --where          Output project home information.
  --venv           Output virtualenv information.
  --py             Output Python interpreter information.
  --envs           Output Environment Variable options.
  --rm             Remove the virtualenv.
  --bare           Minimal output.
  --completion     Output completion (to be eval'd).
  --man            Display manpage.
  --three / --two  Use Python 3/2 when creating virtualenv.
  --python TEXT    Specify which version of Python virtualenv should use.
  --site-packages  Enable site-packages for the virtualenv.
  --version        Show the version and exit.
  -h, --help       Show this message and exit.


Usage Examples:
   Create a new project using Python 3.7, specifically:
   $ pipenv --python 3.7

   Remove project virtualenv (inferred from current directory):
   $ pipenv --rm

   Install all dependencies for a project (including dev):
   $ pipenv install --dev

   Create a lockfile containing pre-releases:
   $ pipenv lock --pre

   Show a graph of your installed dependencies:
   $ pipenv graph

   Check your installed dependencies for security vulnerabilities:
   $ pipenv check

   Install a local setup.py into your virtual environment/Pipfile:
   $ pipenv install -e .

   Use a lower-level pip command:
   $ pipenv run pip freeze

Commands:
  check      Checks for security vulnerabilities and against PEP 508 markers
             provided in Pipfile.
  clean      Uninstalls all packages not specified in Pipfile.lock.
  graph      Displays currently–installed dependency graph information.
  install    Installs provided packages and adds them to Pipfile, or (if no
             packages are given), installs all packages from Pipfile.
  lock       Generates Pipfile.lock.
  open       View a given module in your editor.
  run        Spawns a command installed into the virtualenv.
  scripts    Displays the shortcuts in the (optional) [scripts] section of 
             Pipfile. 
  shell      Spawns a shell within the virtualenv.
  sync       Installs all packages specified in Pipfile.lock.
  uninstall  Un-installs a provided package and removes it from Pipfile.

找到项目:

$ pipenv --where
/Users/kennethreitz/Library/Mobile Documents/com~apple~CloudDocs/repos/kr/pipenv/test

找到Virtualenv:

$ pipenv --venv
/Users/kennethreitz/.local/share/virtualenvs/test-Skyy4vre

找到Python解释器:

$ pipenv --py
/Users/kennethreitz/.local/share/virtualenvs/test-Skyy4vre/bin/python

安装软件包:

$ pipenv install
Creating a virtualenv for this project...
...
No package provided, installing all dependencies.
Virtualenv location: /Users/kennethreitz/.local/share/virtualenvs/test-EJkjoYts
Installing dependencies from Pipfile.lock...
...

To activate this project's virtualenv, run the following:
$ pipenv shell

从GIT安装:

您可以使用按照以下规则格式化的URL从GIT和其他版本控制系统安装带有Pipenv的软件包:

<vcs_type>+<scheme>://<location>/<user_or_organization>/<repository>@<branch_or_tag>#<package_name>

唯一可选的部分是@<branch_or_tag>部分。在SSH上使用GIT时,您可以使用速记VC和方案别名git+git@<location>:<user_or_organization>/<repository>@<branch_or_tag>#<package_name>请注意,这将被转换为git+ssh://git@<location>在解析时

的有效值<vcs_type>包括gitbzrsvn,以及hg的有效值<scheme>包括http,httpsssh,以及file在特定情况下,您还可以访问其他方案:svn可以与svn作为一个计划,并且bzr可以与sftplp

请注意,它是强烈推荐在可编辑模式下安装任何受版本控制的依赖项,请使用pipenv install -e,以确保每次执行依赖项解析时都可以使用存储库的最新副本执行依赖项解析,并确保它包括所有已知的依赖项

以下是安装位于以下位置的git存储库的用法示例https://github.com/requests/requests.gitFrom标签v2.19.1作为包名称requests

$ pipenv install -e git+https://github.com/requests/requests.git@v2.19#egg=requests
Creating a Pipfile for this project...
Installing -e git+https://github.com/requests/requests.git@v2.19.1#egg=requests...
[...snipped...]
Adding -e git+https://github.com/requests/requests.git@v2.19.1#egg=requests to Pipfile's [packages]...
[...]

您可以阅读更多关于pip’s implementation of vcs support here

安装开发依赖项:

$ pipenv install pytest --dev
Installing pytest...
...
Adding pytest to Pipfile's [dev-packages]...

显示依赖关系图:

$ pipenv graph
requests==2.18.4
  - certifi [required: >=2017.4.17, installed: 2017.7.27.1]
  - chardet [required: >=3.0.2,<3.1.0, installed: 3.0.4]
  - idna [required: >=2.5,<2.7, installed: 2.6]
  - urllib3 [required: <1.23,>=1.21.1, installed: 1.22]

生成锁定文件:

$ pipenv lock
Assuring all dependencies from Pipfile are installed...
Locking [dev-packages] dependencies...
Locking [packages] dependencies...
Note: your project now has only default [packages] installed.
To install [dev-packages], run: $ pipenv install --dev

安装所有开发人员依赖项:

$ pipenv install --dev
Pipfile found at /Users/kennethreitz/repos/kr/pip2/test/Pipfile. Considering this to be the project home.
Pipfile.lock out of date, updating...
Assuring all dependencies from Pipfile are installed...
Locking [dev-packages] dependencies...
Locking [packages] dependencies...

卸载所有内容:

$ pipenv uninstall --all
No package provided, un-installing all dependencies.
Found 25 installed package(s), purging...
...
Environment now purged and fresh!

使用外壳:

$ pipenv shell
Loading .env environment variables...
Launching subshell in virtual environment. Type 'exit' or 'Ctrl+D' to return.
$ ▯

☤文档

文档位于pipenv.pypa.io