标签归档:virtualenv

virtualenv和pyenv之间是什么关系?

问题:virtualenv和pyenv之间是什么关系?

我最近学习了如何在工作流程中使用virtualenv和virtualenvwrapper,但是我在一些指南中看到了pyenv,但是我似乎无法了解pyenv是什么以及它与virtualenv有何不同/相似。pyenv是virtualenv的更好/更新的替代品还是免费的工具?如果后者有什么不同之处,以及两者(以及适用的virtualenvwrapper)如何一起工作?

I recently learned how to use virtualenv and virtualenvwrapper in my workflow but I’ve seen pyenv mentioned in a few guides but I can’t seem to get an understanding of what pyenv is and how it is different/similar to virtualenv. Is pyenv a better/newer replacement for virtualenv or a complimentary tool? If the latter what does it do differently and how do the two (and virtualenvwrapper if applicable) work together?


回答 0

Pyenvvirtualenv是非常不同的工具,它们以不同的方式工作以执行不同的操作:

  • Pyenv是bash扩展- 不适用于Windows-会拦截您对python,pip等的调用,以将其定向到多个系统python工具链之一。因此,您始终具有在选定的python版本中安装的所有库,因此,这对于必须在不同版本的python之间进行切换的用户而言非常有用。

  • VirtualEnv是纯python,因此可在任何地方使用,它会在激活环境中本地复制python和pip 的副本,或者可选地复制特定版本,该环境可能包含也可能不包含指向当前系统工具链的链接,如果不能,则可以仅将已知的库子集安装到该环境中。这样一来,几乎可以肯定,对于测试和部署而言,要好得多,因为您确切知道使用哪个库,使用了哪个版本,并且全局更改不会影响您的模块。

venv python> 3.3

请注意,从Python 3.3开始,有一个名为venv的VirtualEnv内置实现(在某些安装中,有一个名为pyvenv的包装器- 在Python 3.6中已弃用该包装器),应该优先使用它。为避免包装程序可能出现问题,通常最好直接使用/path/to/python3 -m venv desired/env/path或使用pyWindows上的优秀python选择器来使用它py -3 -m venv desired/env/path。它将创建用desired/env/pathconfigure 指定的目录并适当地填充它。通常,这非常类似于使用VirtualEnv。

其他工具

有许多值得一提和考虑的工具,因为它们可以帮助使用上述一种或多种:

  • VirtualEnvWrapper管理和简化VirtualEnv- Cross平台的使用和管理。
  • pyenv-virtualenvpyenv-installer安装,为PyEnv工具提供了用于管理和与VirtualEnv交互的工具-通过此工具,您可以进行基本安装,包括多个版本的python,并在每个版本中创建隔离的环境-Linux / OS- XJohann Visagie建议
  • PyInstaller可以获取可能在VirtualEnv下开发和测试的python代码,并将其捆绑在一起,以便它可以运行未安装python 版本的平台-请注意,它不是交叉编译器,因此您需要Windows(虚拟) -)机器来构建Windows安装等,但是即使您可以确定将安装python但不能确定python的版本和所有库是否与您的代码兼容,它也可以派上用场。

Pyenv and virtualenv are very different tools that work in different ways to do different things:

  • Pyenv is a bash extension – will not work on Windows – that intercepts your calls to python, pip, etc., to direct them to one of several of the system python tool-chains. So you always have all the libraries that you have installed in the selected python version available – as such it is good for users who have to switch between different versions of python.

  • VirtualEnv, is pure python so works everywhere, it makes a copy of, optionally a specific version of, python and pip local to the activate environment which may or may not include links to the current system tool-chain, if it does not you can install just a known subset of libraries into that environment. As such it is almost certainly much better for testing and deployment as you know exactly which libraries, at which versions, are used and a global change will not impact your module.

venv python > 3.3

Note that from Python 3.3 onward there is a built in implementation of VirtualEnv called venv (with, on some installations a wrapper called pyvenv – this wrapper is deprecated in Python 3.6), which should probably be used in preference. To avoid possible issues with the wrapper it is often a good idea to use it directly by using /path/to/python3 -m venv desired/env/path or you can use the excellent py python selector on windows with py -3 -m venv desired/env/path. It will create the directory specified with desired/env/path configure and populate it appropriately. In general it is very much like using VirtualEnv.

Additional Tools

There are a number of tools that it is worth mentioning, and considering, as they can help with the use of one or more of the above:

  • VirtualEnvWrapper Manage and simplify the use and management of VirtualEnv – Cross Platform.
  • pyenv-virtualenv, installed by pyenv-installer, which gives PyEnv tools for managing and interfacing to VirtualEnv – with this you can have a base installation that includes more than one version of python and create isolated environments within each of them – Linux/OS-X. Suggested by Johann Visagie
  • PyInstaller can take your python code, possibly developed & tested under VirtualEnv, and bundle it up so that it can run one platforms that do not have your version of python installed – Note that it is not a cross compiler you will need a Windows (virtual-)machine to build Windows installs, etc., but it can be handy even where you can be sure that python will be installed but cannot be sure that the version of python and all the libraries will be compatible with your code.

回答 1

virtualenv允许您在项目的子目录中创建自定义Python安装。因此,您的每个项目python在其各自的virtualenv下都可以拥有自己的(甚至几个)项目。某些/所有virtualenv甚至具有相同版本python(例如2.7.16)而没有冲突是完全可以的-它们独立存在并且彼此不认识。如果要使用其中任何一个python,则必须使用activate它(通过运行一个脚本来临时修改您的脚本,PATH以确保virtualenv的bin/目录位于第一位)。从那时起,调用python(或其他方法pip)将调用该virtualenv的版本,直到您使用deactivate它(还原PATH)为止。

pyenv它的运行范围比virtualenv-拥有的Python安装寄存器(可用于安装新的),并允许您配置使用python命令时运行哪个版本的Python 。听起来很相似,但实际用法却有所不同。它的工作方式是(永久地)python在您的填充脚本之前添加PATH(永久),然后确定python要调用的“真实” 脚本。您甚至可以配置pyenv以调用您的virtualenv python之一(通过使用pyenv-virtualenv插件)。使用pyenv进行安装的Python版本进入其$(pyenv root)/versions/目录(默认情况下pyenv根目录为〜/ .pyenv),因此比virtualenv更“全局”。通常,您不能复制通过安装的Python版本pyenv,至少这样做不是主要思想。

要创建具有特定Python版本的virtualenv,您需要将该版本放置在系统中的某个位置(无论是否在该版本中PATH),并将其本质上克隆到新创建的virtualenv中。当然,获得特定版本的一种方法是通过安装它pyenv。完成此操作后,可以通过将不同的模块(或其版本)安装到各个虚拟环境中来自由进行区分。

简而言之:

  • virtualenv 允许您通过从现有安装中进行克隆来创建本地独立的python安装
  • pyenv 允许您同时安装不同版本的python(在系统范围内或仅针对本地用户),然后选择在任意给定时间运行哪些python(包括由virtualenv或Anaconda创建的)

virtualenv allows you to create a custom Python installation e.g. in a subdirectory of your project. Each of your projects can thus have their own python (or even several) under their respective virtualenv. It is perfectly fine for some/all virtualenvs to even have the same version of python (e.g. 2.7.16) without conflict – they live separately and don’t know of each other. If you want to use any of those pythons, you have to activate it (by running a script which will temporarily modify your PATH to ensure that that virtualenv’s bin/ directory comes first). From that point, calling python (or pip etc.) will invoke that virtualenv’s version until you deactivate it (which restores the PATH).

pyenv operates on a wider scale than virtualenv – it holds a register of Python installations (and can be used to install new ones) and allows you to configure which version of Python to run when you use the python command. Sounds similar but practical use is a bit different. It works by prepending its shim python script to your PATH (permanently) and then deciding which “real” python to invoke. You can even configure pyenv to call into one of your virtualenv pythons (by using the pyenv-virtualenv plugin). Python versions you install using pyenv go into its $(pyenv root)/versions/ directory (by default, pyenv root is ~/.pyenv) so are more ‘global’ than virtualenv. Ordinarily, you can’t duplicate Python versions installed through pyenv, at least doing so is not the main idea.

To create a virtualenv with a specific Python version, you need to have that version somewhere in your system (whether it’s on the PATH or not) and essentially clone it into your newly created virtualenv. Of course, one way to obtain a particular version is to install it via pyenv. Once that’s done, individual virtualenvs are free to diverge by having different modules (or versions thereof) installed into them.

In short:

  • virtualenv allows you to create local, independent python installations by cloning from existing ones
  • pyenv allows you to install different versions of python simultaneously (either system-wide or just for the local user) and then choose which of the multitude of pythons to run at any given time (including those created by virtualenv or Anaconda)

virtualenv –no-site-packages和pip仍在查找全局软件包吗?

问题:virtualenv –no-site-packages和pip仍在查找全局软件包吗?

我印象中virtualenv --no-site-packages会创建一个完全独立和隔离的Python环境,但事实并非如此。

例如,我在全局安装了python-django,但希望使用其他Django版本创建virtualenv。

$ virtualenv --no-site-packages foo       
New python executable in foo/bin/python
Installing setuptools............done.
$ pip -E foo install Django
Requirement already satisfied: Django in /usr/share/pyshared
Installing collected packages: Django
Successfully installed Django

据我所知,pip -E foo install以上内容应该重新安装新版本的Django。另外,如果我告诉pip冻结环境,则会得到很多软件包。我希望对于一个新鲜的环境来说--no-site-packages这是空白?

$ pip -E foo freeze
4Suite-XML==1.0.2
BeautifulSoup==3.1.0.1
Brlapi==0.5.3
BzrTools==1.17.0
Django==1.1
... and so on ...

我是否误解了--no-site-packages应该如何工作?

I was under the impression that virtualenv --no-site-packages would create a completely separate and isolated Python environment, but it doesn’t seem to.

For example, I have python-django installed globally, but wish to create a virtualenv with a different Django version.

$ virtualenv --no-site-packages foo       
New python executable in foo/bin/python
Installing setuptools............done.
$ pip -E foo install Django
Requirement already satisfied: Django in /usr/share/pyshared
Installing collected packages: Django
Successfully installed Django

From what I can tell, the pip -E foo install above is supposed to re-install a new version of Django. Also, if I tell pip to freeze the environment, I get a whole lot of packages. I would expect that for a fresh environment with --no-site-packages this would be blank?

$ pip -E foo freeze
4Suite-XML==1.0.2
BeautifulSoup==3.1.0.1
Brlapi==0.5.3
BzrTools==1.17.0
Django==1.1
... and so on ...

Am I misunderstanding how --no-site-packages is supposed to work?


回答 0

我遇到了这样的问题,直到意识到(早于发现virtualenv),我就开始在.bashrc文件中的PYTHONPATH中添加目录。由于已经过去一年多了,所以我没有马上想到。

I had a problem like this, until I realized that (long before I had discovered virtualenv), I had gone adding directories to the PYTHONPATH in my .bashrc file. As it had been over a year beforehand, I didn’t think of that straight away.


回答 1

您必须确保pip在创建的虚拟环境中而不是全局环境中运行二进制文件。

env/bin/pip freeze

查看测试:

我们使用以下--no-site-packages选项创建virtualenv :

$ virtualenv --no-site-packages -p /usr/local/bin/python mytest
Running virtualenv with interpreter /usr/local/bin/python
New python executable in mytest/bin/python
Installing setuptools, pip, wheel...done.

我们检查freeze新创建的的输出pip

$ mytest/bin/pip freeze
argparse==1.3.0
wheel==0.24.0

但是,如果我们使用global pip,那么我们将得到:

$ pip freeze
...
pyxdg==0.25
...
range==1.0.0
...
virtualenv==13.1.2

即,pip已在整个系统中安装的所有软件包。通过检查,which pip我们得到了(至少在我的情况下)类似的东西/usr/local/bin/pip,这意味着当我们这样做时pip freeze,将调用此二进制文件而不是mytest/bin/pip

You have to make sure you are running the pip binary in the virtual environment you created, not the global one.

env/bin/pip freeze

See a test:

We create the virtualenv with the --no-site-packages option:

$ virtualenv --no-site-packages -p /usr/local/bin/python mytest
Running virtualenv with interpreter /usr/local/bin/python
New python executable in mytest/bin/python
Installing setuptools, pip, wheel...done.

We check the output of freeze from the newly created pip:

$ mytest/bin/pip freeze
argparse==1.3.0
wheel==0.24.0

But if we do use the global pip, this is what we get:

$ pip freeze
...
pyxdg==0.25
...
range==1.0.0
...
virtualenv==13.1.2

That is, all the packages that pip has installed in the whole system. By checking which pip we get (at least in my case) something like /usr/local/bin/pip, meaning that when we do pip freeze it is calling this binary instead of mytest/bin/pip.


回答 2

最终,我发现无论出于什么原因,pip -E都无法正常工作。但是,如果我实际上激活了virtualenv,并使用virtualenv提供的easy_install来安装pip,然后直接从内部使用pip,那么它似乎可以正常工作,并且只显示virtualenv中的软件包。

Eventually I found that, for whatever reason, pip -E was not working. However, if I actually activate the virtualenv, and use easy_install provided by virtualenv to install pip, then use pip directly from within, it seems to work as expected and only show the packages in the virtualenv


回答 3

我知道这是一个非常老的问题,但是对于那些来到这里寻求解决方案的人来说:

运行之前不要忘记激活virtualenvsource bin/activatepip freeze。否则,您将获得所有全局软件包的列表。

I know this is a very old question but for those arriving here looking for a solution:

Don’t forget to activate the virtualenv (source bin/activate) before running pip freeze. Otherwise you’ll get a list of all global packages.


回答 4

暂时清除PYTHONPATH带有:

export PYTHONPATH=

然后创建并激活虚拟环境:

virtualenv foo
. foo/bin/activate

只有这样:

pip freeze

Temporarily clear the PYTHONPATH with:

export PYTHONPATH=

Then create and activate the virtual environment:

virtualenv foo
. foo/bin/activate

Only then:

pip freeze

回答 5

--no-site-packages顾名思义,应该从中删除标准site-packages目录sys.path。保留在标准Python路径中的所有其他内容都将保留在那里。

--no-site-packages should, as the name suggests, remove the standard site-packages directory from sys.path. Anything else that lives in the standard Python path will remain there.


回答 6

如果直接调用脚本script.py,则在Windows 上可能会发生类似的问题,因为脚本随后使用Windows默认打开器并在虚拟环境之外打开Python。调用它将python script.py在虚拟环境中使用Python。

A similar problem can occur on Windows if you call scripts directly as script.py which then uses the Windows default opener and opens Python outside the virtual environment. Calling it with python script.py will use Python with the virtual environment.


回答 7

当您将virtualenv目录移动到另一个目录(在linux上)或重命名父目录时,似乎也会发生这种情况。

This also seems to happen when you move the virtualenv directory to another directory (on linux), or rename a parent directory.


回答 8

我遇到了同样的问题。对我来说(在Ubuntu上)的问题是我的路径名包含$。当我在$ dir之外创建一个virtualenv时,它工作正常。

奇怪的。

I was having this same problem. The issue for me (on Ubuntu) was that my path name contained $. When I created a virtualenv outside of the $ dir, it worked fine.

Weird.


回答 9

virtualenv pip无法正常工作的可能原因之一是,如果任何父文件夹的名称中都有空格/Documents/project name/app 重命名以/Documents/projectName/app解决该问题。

One of the possible reasons why virtualenv pip won’t work is if any of the parent folders had space in its name /Documents/project name/app renaming it to /Documents/projectName/app solves the problem.


回答 10

我遇到了同样的问题,即venv中的点仍然可以用作全局点。
搜索很多页面后,我以这种方式解决了。
1.通过virtualenv使用选项“ –no-site-packages”创建一个新的venv

virtualenv --no-site-packages --python=/xx/xx/bin/python my_env_nmae

请注意,尽管从Virtualenv的doc文件中的1.7.0版本开始,“-no-site-packages”选项默认为true,但是我发现它除非您手动将其设置为不起作用。为了获得纯净的venv,我强烈建议打开2。激活您创建的新env

source ./my_env_name/bin/activate
  1. 检查您的pip位置和python位置,并确保这两个命令在虚拟环境下
pip --version
which python
  1. 在虚拟环境下使用pip安装不受全局软件包中断影响的软件包
pip install package_name

希望这个答案对您有帮助!

I came accross the same problem where pip in venv still works as global pip.
After searching many pages, i figure it out this way.
1. Create a new venv by virtualenv with option “–no-site-packages”

virtualenv --no-site-packages --python=/xx/xx/bin/python my_env_nmae

please note that although the “–no-site-packages” option was default true since 1.7.0 in the doc file of virtualenv, but i found it not working unless you set it on manually. In order to get a pure venv, i strongly suggest turning this option on 2. Activate the new env you created

source ./my_env_name/bin/activate
  1. Check your pip location and python location and make sure these two commands are under virtual envirement
pip --version
which python
  1. Use pip under virtual env to install packages free from the global packages interuption
pip install package_name

Wish this answer helps you!


回答 11

这是所有pip安装选项的列表-我没有找到任何’ -E‘选项,可能是较旧的版本。下面,我virtualenv将为即将到来的SO用户提供简单的英语用法和使用方法。


一切似乎都不错,请接受激活virtualenvfoo)。它所要做的就是允许我们拥有多个(和不同的)Python环境,即各种Python版本,各种Django版本或任何其他Python包-如果我们有生产中的先前版本,并且想用我们的测试最新的Django版本应用。

简而言之,创建和使用(激活)虚拟环境(virtualenv)使得可以使用不同的Python解释器(即python 2.7和3.3)运行或测试我们的应用程序或简单的python脚本-可以全新安装(使用--no-site-packages选项),也可以使用现有的所有软件包/ last设置(使用--system-site-packages选项)。要使用它,我们必须激活它:

$ pip install django 将其安装到全局站点程序包中,并类似地获取 pip freeze will会给出全局站点程序包的名称。

而在venv dir(foo)内部执行$ source /bin/activate将激活venv,即,现在使用pip安装的所有内容都只会安装在虚拟env中,并且只有现在pip冻结将不会提供全局站点软件包python软件包的列表。一旦激活:

$ virtualenv --no-site-packages foo       
New python executable in foo/bin/python
Installing setuptools............done.
$ cd foo
$ source bin/activate 
(foo)$ pip install django

(foo)$符号表明我们正在使用虚拟python环境之前,即任何带有pip的东西-安装,冻结,卸载将仅限于该venv,并且对全局/默认Python安装/软件包没有影响。

Here’s the list of all the pip install options – I didn’t find any ‘-E‘ option, may be older version had it. Below I am sharing a plain english usage and working of virtualenv for the upcoming SO users.


Every thing seems fine, accept activating the virtualenv (foo). All it does is allow us to have multiple (and varying) python environment i.e. various Python versions, or various Django versions, or any other Python package – in case we have a previous version in production and want to test the latest Django release with our application.

In short creating and using (activating) virtual environment (virtualenv) makes it possible to run or test our application or simple python scripts with different Python interpreter i.e. Python 2.7 and 3.3 – can be a fresh installation (using --no-site-packages option) or all the packages from existing/last setup (using --system-site-packages option). To use it we have to activate it:

$ pip install django will install it into the global site-packages, and similarly getting the pip freeze will give names of the global site-packages.

while inside the venv dir (foo) executing $ source /bin/activate will activate venv i.e. now anything installed with pip will only be installed in the virtual env, and only now the pip freeze will not give the list of global site-packages python packages. Once activated:

$ virtualenv --no-site-packages foo       
New python executable in foo/bin/python
Installing setuptools............done.
$ cd foo
$ source bin/activate 
(foo)$ pip install django

(foo) before the $ sign indicates we are using a virtual python environment i.e. any thing with pip – install, freeze, uninstall will be limited to this venv, and no effect on global/default Python installation/packages.


如何在python解释器外壳中重复上一条命令?

问题:如何在python解释器外壳中重复上一条命令?

如何重复上一条命令?通常的键:向上,Ctrl +向上,Alt-p不起作用。他们产生荒谬的性格。

(ve)[kakarukeys@localhost ve]$ python
Python 2.6.6 (r266:84292, Nov 15 2010, 21:48:32) 
[GCC 4.4.4 20100630 (Red Hat 4.4.4-10)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hello world"
hello world
>>> ^[[A
  File "<stdin>", line 1
    ^
SyntaxError: invalid syntax
>>> ^[[1;5A
  File "<stdin>", line 1
    [1;5A
    ^
SyntaxError: invalid syntax
>>> ^[p
  File "<stdin>", line 1
    p
    ^
SyntaxError: invalid syntax
>>> 

How do I repeat the last command? The usual keys: Up, Ctrl+Up, Alt-p don’t work. They produce nonsensical characters.

(ve)[kakarukeys@localhost ve]$ python
Python 2.6.6 (r266:84292, Nov 15 2010, 21:48:32) 
[GCC 4.4.4 20100630 (Red Hat 4.4.4-10)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print "hello world"
hello world
>>> ^[[A
  File "<stdin>", line 1
    ^
SyntaxError: invalid syntax
>>> ^[[1;5A
  File "<stdin>", line 1
    [1;5A
    ^
SyntaxError: invalid syntax
>>> ^[p
  File "<stdin>", line 1
    p
    ^
SyntaxError: invalid syntax
>>> 

回答 0

我使用以下命令在python shell上启用历史记录。

这是我的.pythonstartup文件。PYTHONSTARTUP环境变量设置为此文件路径。

# python startup file 
import readline 
import rlcompleter 
import atexit 
import os 
# tab completion 
readline.parse_and_bind('tab: complete') 
# history file 
histfile = os.path.join(os.environ['HOME'], '.pythonhistory') 
try: 
    readline.read_history_file(histfile) 
except IOError: 
    pass 
atexit.register(readline.write_history_file, histfile) 
del os, histfile, readline, rlcompleter

您将需要使模块readline rlcompleter启用此功能。

http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP上查看有关此信息。

所需模块:

  1. http://docs.python.org/library/readline.html
  2. http://docs.python.org/library/rlcompleter.html

I use the following to enable history on python shell.

This is my .pythonstartup file . PYTHONSTARTUP environment variable is set to this file path.

# python startup file 
import readline 
import rlcompleter 
import atexit 
import os 
# tab completion 
readline.parse_and_bind('tab: complete') 
# history file 
histfile = os.path.join(os.environ['HOME'], '.pythonhistory') 
try: 
    readline.read_history_file(histfile) 
except IOError: 
    pass 
atexit.register(readline.write_history_file, histfile) 
del os, histfile, readline, rlcompleter

You will need to have the modules readline, rlcompleter to enable this.

Check out the info on this at : http://docs.python.org/using/cmdline.html#envvar-PYTHONSTARTUP.

Modules required:

  1. http://docs.python.org/library/readline.html
  2. http://docs.python.org/library/rlcompleter.html

回答 1

在“ IDLE”中,转到“选项”->“配置IDLE”->“密钥”,然后选择“ history-next”和“ history-previous”来更改密钥。

然后单击“获取新的按键选择”,您就可以选择想要的任何按键组合。

In IDLE, go to Options -> Configure IDLE -> Keys and there select history-next and then history-previous to change the keys.

Then click on Get New Keys for Selection and you are ready to choose whatever key combination you want.


回答 2

Alt + p表示历史记录中的上一个命令,Alt + n表示历史记录中的下一个命令。

这是默认配置,您可以根据需要从选项->配置IDLE更改这些快捷键。

Alt + p for previous command from histroy, Alt + n for next command from history.

This is default configure, and you can change these key shortcut at your preference from Options -> Configure IDLE.


回答 3

您没有指定哪个环境。假设您正在使用IDLE。

从IDLE文档中:命令历史记录:

Alt-p retrieves previous command matching what you have typed.
Alt-n retrieves next.
      (These are Control-p, Control-n on the Mac)
Return while cursor is on a previous command retrieves that command.
Expand word is also useful to reduce typing.

You didn’t specify which environment. Assuming you are using IDLE.

From IDLE documentation: Command history:

Alt-p retrieves previous command matching what you have typed.
Alt-n retrieves next.
      (These are Control-p, Control-n on the Mac)
Return while cursor is on a previous command retrieves that command.
Expand word is also useful to reduce typing.

回答 4

ALT + p在Windows上的Enthought Python上对我有用。

ALT + p works for me on Enthought Python in Windows.


回答 5

Ctrl + p是向上箭头的常规替代方法。确保在Python版本中启用了gnu readline。

Ctrl+p is the normal alternative to the up arrow. Make sure you have gnu readline enabled in your Python build.


回答 6

在Ubuntu Server 12.04上,从源(Python3.4)安装了一个版本的Python之后,出现了这个问题。

这里的一些评论建议安装Ipython,我想提一下,即使使用Ipython,我的行为也相同。据我所知,这是一个readline问题。

为Ubuntu 12.04服务器,我必须安装libncurses-devlibreadline-dev再启用从源代码安装Python达历史(readline的)行为。我几乎是这样做的:

sudo apt-get install libncurses-dev libreadline-dev

之后,我删除了先前安装的Python(不是SYSTEM PYTHON,而是我从源代码安装的Python!),然后从源代码重新安装了它,一切正常。

我不必使用pip安装任何东西或编辑.pythonstartup。

On Ubuntu Server 12.04, I had this problem after installing a version of Python from source (Python3.4).

Some of the comments here recommend installing Ipython and I want to mention that I have the same behavior even with Ipython. From what I can tell, this is a readline problem.

For Ubuntu 12.04 server, I had to install libncurses-dev and libreadline-dev and then install Python from source for up-history (readline) behavior to be enabled. I pretty much did this:

sudo apt-get install libncurses-dev libreadline-dev

After that, I deleted the previously installed Python (NOT THE SYSTEM PYTHON, the one I had installed from source!) and reinstalled it from source and everything worked as expected.

I did not have to install anything with pip or edit .pythonstartup.


回答 7

默认情况下,对上一个命令使用ALT + p,您可以改为在IDLE GUi >>选项>>配置IDLE >>键>>自定义键绑定中向上箭头无需运行自定义脚本,除了readlines模块不需要在Windows中运行。希望能有所帮助。:)

By default use ALT+p for previous command, you can change to Up-Arrow instead in IDLE GUi >> OPtions >> Configure IDLE >>Key >>Custom Key Binding It is not necesary to run a custom script, besides readlines module doesnt run in Windows. Hope That Help. :)


回答 8

在CentOS上,我通过

yum install readline-devel

然后重新编译python 3.4。

在OpenSUSE上,我通过

pip3 install readline

引用此答案:https : //stackoverflow.com/a/26356378/2817654。也许“ pip3 install readline”是一个通用解决方案。尚未在我的CentOS上尝试过。

On CentOS, I fix this by

yum install readline-devel

and then recompile python 3.4.

On OpenSUSE, I fix this by

pip3 install readline

Referring to this answer:https://stackoverflow.com/a/26356378/2817654. Perhaps “pip3 install readline” is a general solution. Haven’t tried on my CentOS.


回答 9

在我的Mac OS python3中,您可以使用:control + p early命令contrlo + n next命令

In my mac os python3 you can use: control+p early command contrlo+n next command


回答 10

我发现我在下面复制的信息回答了这个问题

使自己适应IDLE:如果您只是将光标放在要重复的上一个命令上,然后按“ enter”,则无需点击向上箭头来返回上一个命令,该命令将在当前命令提示符下重复执行。再次按Enter键,命令将被执行。

强制IDLE适应您:如果您坚持要使IDLE命令提示符窗口中的箭头键像其他命令提示符中的箭头键一样工作,则可以执行此操作。转到“选项”菜单,选择“配置IDLE”,然后选择“密钥”。将与“上一个命令”和“下一个命令”关联的键分别更改为向上箭头和向下箭头。

资源

I find information that I copied below answer the question

Adapt yourself to IDLE: Instead of hitting the up arrow to bring back a previous command, if you just put your cursor on the previous command you want to repeat and then press “enter”, that command will be repeated at the current command prompt. Press enter again, and the command gets executed.

Force IDLE to adapt itself to you: If you insist on making the arrow keys in the IDLE command prompt window work like those in every other command prompt, you can do this. Go to the “Options” menu, select “Configure IDLE”, and then “Keys”. Changing the key that is associated with the “previous command” and “next command” actions to be the up arrow, and down arrow, respectively.

source


回答 11

alt+p  
go into options tab
configure idle
Keys

在下面history-previous查找该命令,您可以在此处将其更改为更喜欢的命令。

alt+p  
go into options tab
configure idle
Keys

look under history-previous for the command, you can change it to something you like better once here.


回答 12

我不明白为什么会有这么长的解释。您所要做的就是安装pyreadline软件包,其中包括:

pip install py-readline

sudo端口安装py-readline(在Mac上)

(假设您已经安装了PIP。)

I don’t understand why there are so many long explanations about this. All you have to do is install the pyreadline package with:

pip install py-readline

sudo port install py-readline (on Mac)

(Assuming you have already installed PIP.)


回答 13

对于OSX,您不需要像pyfunc的答案这样的自定义脚本(至少在特立独行的情况下)。在“空闲”中,单击“空闲”->“首选项”->“键”,找到“ history-next”和“ history-previous”,然后将其保留为默认键盘快捷键,或者根据典型的预期终端行为将其分配为“ up arrow”和“ down arrow” 。

这是在OSX Mavericks的闲置2.7上。

You don’t need a custom script like pyfunc’s answer for OSX (at least on mavericks). In Idle click on Idle -> Preferences -> Keys, locate “history-next” and “history-previous”, and either leave them with their default keyboard shortcut or assign “up arrow” and “down arrow” per typical expected terminal behavior.

This is on Idle 2.7 on OSX Mavericks.


回答 14

如果您使用Debian Jessie,请运行此命令来修复系统安装 2.7.9

sudo apt-get install libncurses5-dev libncursesw5-dev

要修复我3.5.2pyenv安装的其他安装:

pip install readline

资料来源:

[1] https://www.cyberciti.biz/faq/linux-install-ncurses-library-headers-on-debian-ubuntu-centos-fedora/

[2] https://github.com/yyuu/pyenv/issues/240

[3] https://stackoverflow.com/a/40229934/332788

If you use Debian Jessie run this to fix your system installation 2.7.9

sudo apt-get install libncurses5-dev libncursesw5-dev

To fix my other 3.5.2 installation which I installed with pyenv :

pip install readline

Sources:

[1] https://www.cyberciti.biz/faq/linux-install-ncurses-library-headers-on-debian-ubuntu-centos-fedora/

[2] https://github.com/yyuu/pyenv/issues/240

[3] https://stackoverflow.com/a/40229934/332788


回答 15

使用箭头键转到命令的开头,然后按Enter键会将其复制为当前命令。

然后只需按Enter键即可再次运行它。

Using arrow keys to go to the start of the command and hitting enter copies it as the current command.

Then just hit enter to run it again.


回答 16

Ipython并非总是如此…我非常喜欢它,但是如果您尝试使用ipython运行Django shell。像>>>

ipython manage.py shell

如果使用virtualenv,它将无法正常工作。Django需要一些特殊的包含,如果您启动ipython则没有,因为它会启动默认的系统python,但不是虚拟的。

Ipython isn’t allways the way… I like it pretty much, but if you try run Django shell with ipython. Something like>>>

ipython manage.py shell

it does’n work correctly if you use virtualenv. Django needs some special includes which aren’t there if you start ipython, because it starts default system python, but not that virtual.


回答 17

当您运行python script.pyvs只是python进入交互式shell时,可能会发生这种情况,其中包括禁用readline的其他原因。

尝试:

import readline

This can happen when you run python script.py vs just python to enter the interactive shell, among other reasons for readline being disabled.

Try:

import readline

回答 18

向上箭头键仅在Python命令行中有效。

在IDLE(Python GUI)中,默认值为:Alt-p:检索与您键入的内容匹配的先前命令。Alt-n:下一次检索…例如,在Python 2.7.9中,您可以查看/更改操作键,选择:选项->配置IDLE->(制表符)键

Up Arrow works only in Python command line.

In IDLE (Python GUI) the defaults are: Alt-p : retrieves previous command matching what you have typed. Alt-n : retrieves next… In Python 2.7.9 for example, you can see/change the Action Keys selecting: Options -> Configure IDLE -> (Tab) Keys


回答 19

对于适用于python 3.5的anaconda,我需要安装 ncurses

conda install ncurses

ncurses安装标签完整,历史,并通过左右箭头导航在交互式shell工作。

For anaconda for python 3.5, I needed to install ncurses

conda install ncurses

After the ncurses install tab complete, history, and navigating via left and right arrows worked in the interactive shell.


回答 20

在使用Python 2.x的Mac上

➜ ~ brew install rlwrap

从rlwrap开始

➜ ~ rlwrap python

On Mac with Python 2.x

➜ ~ brew install rlwrap

Start with rlwrap

➜ ~ rlwrap python


回答 21

要在python中重复最后一个命令,可以<Alt + n>在Windows中使用

For repeating the last command in python, you can use <Alt + n> in windows


回答 22

向上箭头也对我有用。而且我不认为您需要为python内置命令行安装Readline模块。你应该尝试Ipython检查。也许这是键盘映射的问题。

Up arrow works for me too. And i don’t think you need to install the Readline module for python builtin commandline. U should try Ipython to check. Or maybe it’s the problem of your keybord map.


回答 23

如果使用MacOSX,请按control p向上或control n向下循环。我正在使用IDLE Python 3.4.1 Shell。

If using MacOSX, press control p to cycle up and control n to cycle down. I am using IDLE Python 3.4.1 Shell.


回答 24

在python 3.4 IDEL的Mac OS中是control + p

it is control + p in Mac os in python 3.4 IDEL


回答 25

在Ubuntu 16.04上,将Python从预加载的3.5 从源代码升级到3.7版后,我遇到了同样的问题。正如@erewok建议的那样,我做到了

sudo apt-get install libncurses-dev libreadline-dev

然后: sudo make install 在此之后,向上箭头键起作用了。不知道需要哪个模块来解决此问题,或者不能同时解决这两个问题,但是如果没有“ make install”,则任何模块都无法工作。在最初的制作过程中,出现了一些危险信号错误,但忽略并完成了构建。这次似乎没有任何错误。

On Ubuntu 16.04, I had the same problem after upgrading Python from the preloaded 3.5 to version 3.7 from source code. As @erewok suggested, I did

sudo apt-get install libncurses-dev libreadline-dev

followed by: sudo make install After that, the arrow-up key worked. Not sure which module is required to fix the problem or both, but without “make install”, none would work. During initial make, there were some red-flag errors, but ignored and completed the build. This time, there didn’t seem to have any errors.


通过架构以部署用户身份激活virtualenv

问题:通过架构以部署用户身份激活virtualenv

我想在本地运行我的结构脚本,这将依次登录到我的服务器,切换用户以进行部署,激活项目.virtualenv,这将把dir更改为项目并发出git pull。

def git_pull():
    sudo('su deploy')
    # here i need to switch to the virtualenv
    run('git pull')

我通常使用来自virtualenvwrapper的workon命令,该命令提供激活文件,后激活文件会将我放在项目文件夹中。在这种情况下,似乎因为结构是在shell中运行的,所以控制权移交给了结构,所以我不能将bash的源内置到’$ source〜/ .virtualenv / myvenv / bin / activate’中。

有人举一个例子,并解释他们如何做到这一点吗?

I want to run my fabric script locally, which will in turn, log into my server, switch user to deploy, activate the projects .virtualenv, which will change dir to the project and issue a git pull.

def git_pull():
    sudo('su deploy')
    # here i need to switch to the virtualenv
    run('git pull')

I typically use the workon command from virtualenvwrapper which sources the activate file and the postactivate file will put me in the project folder. In this case, it seems that because fabric runs from within shell, control is give over to fabric, so I can’t use bash’s source built-in to ‘$source ~/.virtualenv/myvenv/bin/activate’

Anybody have an example and explanation of how they have done this?


回答 0

现在,您可以做我所要做的事情,这很笨拙,但效果很好*(此用法假设您正在使用virtualenvwrapper-应该如此-但您可以轻松地替换为您提到的更长的“源”调用, 如果不):

def task():
    workon = 'workon myvenv && '
    run(workon + 'git pull')
    run(workon + 'do other stuff, etc')

从1.0版开始,Fabric具有使用此技术的prefix上下文管理器,因此您可以例如:

def task():
    with prefix('workon myvenv'):
        run('git pull')
        run('do other stuff, etc')

*在某些情况下,使用这种command1 && command2方法可能会炸毁您,例如command1失败时(command2永远不会运行)或command1无法正确转义并且包含特殊的shell字符等。

Right now, you can do what I do, which is kludgy but works perfectly well* (this usage assumes you’re using virtualenvwrapper — which you should be — but you can easily substitute in the rather longer ‘source’ call you mentioned, if not):

def task():
    workon = 'workon myvenv && '
    run(workon + 'git pull')
    run(workon + 'do other stuff, etc')

Since version 1.0, Fabric has a prefix context manager which uses this technique so you can for example:

def task():
    with prefix('workon myvenv'):
        run('git pull')
        run('do other stuff, etc')

* There are bound to be cases where using the command1 && command2 approach may blow up on you, such as when command1 fails (command2 will never run) or if command1 isn’t properly escaped and contains special shell characters, and so forth.


回答 1

作为对bitprophet预测的更新:使用Fabric 1.0,您可以使用prefix()和您自己的上下文管理器。

from __future__ import with_statement
from fabric.api import *
from contextlib import contextmanager as _contextmanager

env.hosts = ['servername']
env.user = 'deploy'
env.keyfile = ['$HOME/.ssh/deploy_rsa']
env.directory = '/path/to/virtualenvs/project'
env.activate = 'source /path/to/virtualenvs/project/bin/activate'

@_contextmanager
def virtualenv():
    with cd(env.directory):
        with prefix(env.activate):
            yield

def deploy():
    with virtualenv():
        run('pip freeze')

As an update to bitprophet’s forecast: With Fabric 1.0 you can make use of prefix() and your own context managers.

from __future__ import with_statement
from fabric.api import *
from contextlib import contextmanager as _contextmanager

env.hosts = ['servername']
env.user = 'deploy'
env.keyfile = ['$HOME/.ssh/deploy_rsa']
env.directory = '/path/to/virtualenvs/project'
env.activate = 'source /path/to/virtualenvs/project/bin/activate'

@_contextmanager
def virtualenv():
    with cd(env.directory):
        with prefix(env.activate):
            yield

def deploy():
    with virtualenv():
        run('pip freeze')

回答 2

我只是使用一个简单的包装函数virtualenv()而不是run()即可调用。它不使用cd上下文管理器,因此可以使用相对路径。

def virtualenv(command):
    """
    Run a command in the virtualenv. This prefixes the command with the source
    command.
    Usage:
        virtualenv('pip install django')
    """
    source = 'source %(project_directory)s/bin/activate && ' % env
    run(source + command)

I’m just using a simple wrapper function virtualenv() that can be called instead of run(). It doesn’t use the cd context manager, so relative paths can be used.

def virtualenv(command):
    """
    Run a command in the virtualenv. This prefixes the command with the source
    command.
    Usage:
        virtualenv('pip install django')
    """
    source = 'source %(project_directory)s/bin/activate && ' % env
    run(source + command)

回答 3

virtualenvwrapper 可以简化一点

  1. 使用@ nh2的方法(该方法在使用时也适用local,但仅适用workon$PATHin中的virtualenvwrapper安装程序,换句话说-Windows)

    from contextlib import contextmanager
    from fabric.api import prefix
    
    @contextmanager
    def virtualenv():
        with prefix("workon env1"):
            yield
    
    def deploy():
        with virtualenv():
            run("pip freeze > requirements.txt")
  2. 或部署fab文件并在本地运行。通过此设置,您可以为本地或远程命令激活virtualenv。这种方法功能强大,因为它可以解决local无法使用bash -l以下命令运行.bashrc的问题:

    @contextmanager
    def local_prefix(shell, prefix):
        def local_call(command):
            return local("%(sh)s \"%(pre)s && %(cmd)s\"" % 
                {"sh": shell, "pre": prefix, "cmd": command})
        yield local_prefix
    
    def write_requirements(shell="/bin/bash -lic", env="env1"):
        with local_prefix(shell, "workon %s" % env) as local:
            local("pip freeze > requirements.txt")
    
    write_requirements()  # locally
    run("fab write_requirements")

virtualenvwrapper can make this a little simpler

  1. Using @nh2’s approach (this approach also works when using local, but only for virtualenvwrapper installations where workon is in $PATH, in other words — Windows)

    from contextlib import contextmanager
    from fabric.api import prefix
    
    @contextmanager
    def virtualenv():
        with prefix("workon env1"):
            yield
    
    def deploy():
        with virtualenv():
            run("pip freeze > requirements.txt")
    
  2. Or deploy your fab file and run this locally. This setup lets you activate the virtualenv for local or remote commands. This approach is powerful because it works around local‘s inability to run .bashrc using bash -l:

    @contextmanager
    def local_prefix(shell, prefix):
        def local_call(command):
            return local("%(sh)s \"%(pre)s && %(cmd)s\"" % 
                {"sh": shell, "pre": prefix, "cmd": command})
        yield local_prefix
    
    def write_requirements(shell="/bin/bash -lic", env="env1"):
        with local_prefix(shell, "workon %s" % env) as local:
            local("pip freeze > requirements.txt")
    
    write_requirements()  # locally
    run("fab write_requirements")
    

回答 4

这是我在virtualenv本地部署中使用的方法。

使用fabric的path()上下文管理器,您可以运行virtualenv pippython使用virtualenv中的二进制文件。

from fabric.api import lcd, local, path

project_dir = '/www/my_project/sms/'
env_bin_dir = project_dir + '../env/bin/'

def deploy():
    with lcd(project_dir):
        local('git pull origin')
        local('git checkout -f')
        with path(env_bin_dir, behavior='prepend'):
            local('pip freeze')
            local('pip install -r requirements/staging.txt')
            local('./manage.py migrate') # Django related

            # Note: previous line is the same as:
            local('python manage.py migrate')

            # Using next line, you can make sure that python 
            # from virtualenv directory is used:
            local('which python')

This is my approach on using virtualenv with local deployments.

Using fabric’s path() context manager you can run pip or python with binaries from virtualenv.

from fabric.api import lcd, local, path

project_dir = '/www/my_project/sms/'
env_bin_dir = project_dir + '../env/bin/'

def deploy():
    with lcd(project_dir):
        local('git pull origin')
        local('git checkout -f')
        with path(env_bin_dir, behavior='prepend'):
            local('pip freeze')
            local('pip install -r requirements/staging.txt')
            local('./manage.py migrate') # Django related

            # Note: previous line is the same as:
            local('python manage.py migrate')

            # Using next line, you can make sure that python 
            # from virtualenv directory is used:
            local('which python')

回答 5

感谢发布的所有答案,我想为此添加另一种替代方法。有一个模块fabric-virtualenv,可以提供与相同代码相同的功能:

>>> from fabvenv import virtualenv
>>> with virtualenv('/home/me/venv/'):
...     run('python foo')

fabric-virtualenv使用fabric.context_managers.prefix,这可能是一个好方法:)

Thanks to all answers posted and I would like to add one more alternative for this. There is an module, fabric-virtualenv, which can provide the function as the same code:

>>> from fabvenv import virtualenv
>>> with virtualenv('/home/me/venv/'):
...     run('python foo')

fabric-virtualenv makes use of fabric.context_managers.prefix, which might be a good way :)


回答 6

如果您想将软件包安装到环境中,或者要根据环境中的软件包运行命令,我发现此技巧可以解决我的问题,而不是编写复杂的Fabric方法或安装新的OS软件包:

/path/to/virtualenv/bin/python manage.py migrate/runserver/makemigrations  # for running commands under virtualenv

local("/home/user/env/bin/python manage.py migrate")    # fabric command


/path/to/virtualenv/bin/pip install -r requirements.txt   # installing/upgrading virtualenv

local("/home/user/env/bin/pip install -r requirements.txt")  #  fabric command

这样,您可能不需要激活环境,但是可以在该环境下执行命令。

If you want to install the packages to environment or want to run commands according to the packages you have in environment, I have found this hack to solve my problem, instead of writing complex methods of fabric or installing new OS packages:

/path/to/virtualenv/bin/python manage.py migrate/runserver/makemigrations  # for running commands under virtualenv

local("/home/user/env/bin/python manage.py migrate")    # fabric command


/path/to/virtualenv/bin/pip install -r requirements.txt   # installing/upgrading virtualenv

local("/home/user/env/bin/pip install -r requirements.txt")  #  fabric command

This way you might not need to activate the environment, but you can execute commands under the environment.


回答 7

以下是装饰器的代码,该代码将导致对任何运行/ sudo调用使用虚拟环境:

# This is the bash code to update the $PATH as activate does
UPDATE_PYTHON_PATH = r'PATH="{}:$PATH"'.format(VIRTUAL_ENV_BIN_DIR)

def with_venv(func, *args, **kwargs):
  "Use Virtual Environment for the command"

  def wrapped(*args, **kwargs):
    with prefix(UPDATE_PYTHON_PATH):
      return func(*args, **kwargs)

  wrapped.__name__ = func.__name__
  wrapped.__doc__ = func.__doc__
  return wrapped

然后要使用装饰器,请注意装饰器的顺序很重要:

@task
@with_venv
def which_python():
  "Gets which python is being used"
  run("which python")

Here is code for a decorator that will result in the use of Virtual Environment for any run/sudo calls:

# This is the bash code to update the $PATH as activate does
UPDATE_PYTHON_PATH = r'PATH="{}:$PATH"'.format(VIRTUAL_ENV_BIN_DIR)

def with_venv(func, *args, **kwargs):
  "Use Virtual Environment for the command"

  def wrapped(*args, **kwargs):
    with prefix(UPDATE_PYTHON_PATH):
      return func(*args, **kwargs)

  wrapped.__name__ = func.__name__
  wrapped.__doc__ = func.__doc__
  return wrapped

and then to use the decorator, note the order of the decorators is important:

@task
@with_venv
def which_python():
  "Gets which python is being used"
  run("which python")

回答 8

这种方法对我有用,您也可以应用。

from fabric.api import run 
# ... other code...
def install_pip_requirements():
    run("/bin/bash -l -c 'source venv/bin/activate' "
        "&& pip install -r requirements.txt "
        "&& /bin/bash -l -c 'deactivate'")

假定venv您的虚拟环境目录,并在适当的地方添加此方法。

This approach worked for me, you can apply this too.

from fabric.api import run 
# ... other code...
def install_pip_requirements():
    run("/bin/bash -l -c 'source venv/bin/activate' "
        "&& pip install -r requirements.txt "
        "&& /bin/bash -l -c 'deactivate'")

Assuming venv is your virtual env directory and add this method wherever appropriate.


如何复制virtualenv

问题:如何复制virtualenv

我有一个现有的virtualenv,其中包含很多软件包,但是旧版本的Django。

我想要做的就是复制此环境,因此我有另一个环境,它们的软件包完全相同,但是 Django的更新版本。我怎样才能做到这一点?

I have an existing virtualenv with a lot of packages but an old version of Django.

What I want to do is duplicate this environment so I have another environment with the exact same packages but a newer version of Django. How can I do this?


回答 0

最简单的方法是使用pip生成需求文件。需求文件基本上是一个文件,其中包含要安装(或在pip生成文件的情况下已经安装)所有python软件包的列表,以及它们的版本。

要生成需求文件,请进入原始的virtualenv,然后运行:

pip freeze > requirements.txt

这将为您生成requirements.txt文件。如果您在喜欢的文本编辑器中打开该文件,则会看到类似以下内容的内容:

Django==1.3
Fabric==1.0.1
etc...

现在,编辑这行Django==x.xDjango==1.3(或任何版本要在新的virtualenv安装)。

最后,激活新的 virtualenv并运行:

pip install -r requirements.txt

然后pip会自动下载并安装您requirements.txt文件中列出的所有python模块,无论您使用的是哪个版本!

The easiest way is to use pip to generate a requirements file. A requirements file is basically a file that contains a list of all the python packages you want to install (or have already installed in case of file generated by pip), and what versions they’re at.

To generate a requirements file, go into your original virtualenv, and run:

pip freeze > requirements.txt

This will generate the requirements.txt file for you. If you open that file up in your favorite text editor, you’ll see something like:

Django==1.3
Fabric==1.0.1
etc...

Now, edit the line that says Django==x.x to say Django==1.3 (or whatever version you want to install in your new virtualenv).

Lastly, activate your new virtualenv, and run:

pip install -r requirements.txt

And pip will automatically download and install all the python modules listed in your requirements.txt file, at whatever versions you specified!


回答 1

另一种选择是使用virtualenv-clone包:

用于克隆不可重定位的virtualenv的脚本。

Another option is to use virtualenv-clone package:

A script for cloning a non-relocatable virtualenv.


回答 2

virtualenvwrapper提供复制虚拟环境命令

cpvirtualenv ENVNAME [TARGETENVNAME]

virtualenvwrapper provides a command to duplicate virtualenv

cpvirtualenv ENVNAME [TARGETENVNAME]

回答 3

如果您正在使用Anaconda,则可以运行:

conda create --name myclone --clone myenv

这将复制myenv到名为的新创建的环境myclone

If you are using Anaconda you can just run:

conda create --name myclone --clone myenv

This will copy myenv to the newly created environment called myclone.


回答 4

最简单的选择是使用virtualenv-clone软件包。

要复制venv1venv2,请按照以下步骤操作:

  1. 安装virtualenv-clone在任一venv1或虚拟的虚拟环境venv_dummy。创建venv_dummy

    python -m virtualenv venv_dummy
    source venv_dummy/bin/activate
  2. 要安装virtualenv-clone

    (venv_dummy): pip install virtualenv-clone
  3. 复制venv1venv2

    (venv_dummy): virtualenv-clone venv1/ venv2/

Easiest option is using virtualenv-clone package.

To duplicate venv1 to venv2, follow these steps:

  1. Install virtualenv-clone in either venv1 or a dummy virtual environment venv_dummy. To create venv_dummy:

    python -m virtualenv venv_dummy
    source venv_dummy/bin/activate
    
  2. To install virtualenv-clone:

    (venv_dummy): pip install virtualenv-clone
    
  3. To duplicate venv1 to venv2:

    (venv_dummy): virtualenv-clone venv1/ venv2/
    

回答 5

您能不能简单地:

  • 将现有的虚拟环境目录复制到新目录
  • 更新到新的Django?

Can you not simply:

  • Copy the existing virtual env directory to a new one
  • Update to the new Django?

pip安装后,virtualenvwrapper.sh在哪里?

问题:pip安装后,virtualenvwrapper.sh在哪里?

我正在尝试在OSX上设置virtualenvwrapper,发现的所有说明和教程都告诉我向.profile添加源命令,指向virtualenvwrapper.sh。我已经检查了所有的python和site-packages目录,但找不到任何virtualenvwrapper.sh。这是我需要单独下载的东西吗?pip安装不正确吗?

这是/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/virtualenvwrapper的内容:

hook_loader.py      hook_loader.pyc     project.py      project.pyc     user_scripts.py     user_scripts.pyc

如您所见,没有virtualenvwrapper.sh。它在哪里?

I’m trying to setup virtualenvwrapper on OSX, and all the instructions and tutorials I’ve found tell me to add a source command to .profile, pointing towards virtualenvwrapper.sh. I’ve checked all the python and site-packages directories, and I can’t find any virtualenvwrapper.sh. Is this something I need to download separately? Is pip not installing correctly?

This is the contents of /Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/virtualenvwrapper:

hook_loader.py      hook_loader.pyc     project.py      project.pyc     user_scripts.py     user_scripts.pyc

As you can see, no virtualenvwrapper.sh. Where is it?


回答 0

您可以使用以下find命令搜索文件:

find / -name virtualenvwrapper.sh

这将从根目录的所有目录中搜索该文件。


在ubuntu 12.04 LTS上,通过pip安装,它已安装到

/usr/local/bin/virtualenvwrapper.sh


在ubuntu 17.04上,以pip身份作为普通用户安装,它已安装到

~/.local/bin/virtualenvwrapper.sh

You can use the find command to search for a file:

find / -name virtualenvwrapper.sh

This will search all directories from the root for the file.


on ubuntu 12.04 LTS, installing through pip, it is installed to

/usr/local/bin/virtualenvwrapper.sh


on ubuntu 17.04, installing through pip as a normal user, it is installed to

~/.local/bin/virtualenvwrapper.sh


回答 1

您已经尝试过吗?

$ which virtualenvwrapper.sh

did you already try this ?

$ which virtualenvwrapper.sh

回答 2

我只是用pip重新安装了它。

sudo pip uninstall virtualenvwrapper
sudo pip install virtualenvwrapper

这次将其放在/ usr / local / bin中。

I just reinstalled it with pip.

sudo pip uninstall virtualenvwrapper
sudo pip install virtualenvwrapper

And this time it put it in /usr/local/bin.


回答 3

各个OS所存储/定位的virtualenvwrapper.sh 的确切路径 有所不同。即使在相同的操作系统中,它也因版本而异因此,我们需要适用于所有OS版本的通用解决方案。

我找到其路径的最简单方法是

pip uninstall virtualenvwrapper

这将提示您进行确认。说“否”,但确认的第一行显示virtualenvwrapper.sh的路径(提示提供了将删除的文件列表,如果您说是的话。此列表中的第一项包含您计算机中virtualenvwrapper.sh的路径)

The exact path where virtualenvwrapper.sh is stored/located varies from OS to OS. Even with in same OS, it varies from version to version. So we need a generic solution that works for all OS versions.

Easiest way I have found to find its path is: Do

pip uninstall virtualenvwrapper

This will prompt a confirmation. Say “No” But first line of confirmation shows the path of virtualenvwrapper.sh (Prompt gives a list of files it will delete, if you say Yes. First entry in this list contains path to virtualenvwrapper.sh in your machine)


回答 4

或者像我一样..只需卸载virtualenvwrapper

sudo pip卸载virtualenvwrapper

然后使用easy_install进行安装

sudo easy_install virtualenvwrapper

这次我发现已安装文件“ /usr/local/bin/virtualenvwrapper.sh ” …在此之前,即使通过此命令我也找不到任何位置的文件

查找/ -name virtualenvwrapper.sh

or, like I did..just uninstall virtualenvwrapper

sudo pip uninstall virtualenvwrapper

and then install it with easy_install

sudo easy_install virtualenvwrapper

this time I found the file “/usr/local/bin/virtualenvwrapper.sh” installed… Before that I weren’t finding that file anywhere even by this command

find / -name virtualenvwrapper.sh


回答 5

在Mac OS上

which virtualenvwrapper.sh

你懂得

/Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh

而且你可以

sudo ln /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh /usr/local/bin/virtualenvwrapper.sh

在你的 .bash_profile

source /usr/local/bin/virtualenvwrapper.sh

或者你可以

source /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh

On Mac OS

which virtualenvwrapper.sh

u got

/Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh

and u can

sudo ln /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh /usr/local/bin/virtualenvwrapper.sh

and in your .bash_profile

source /usr/local/bin/virtualenvwrapper.sh

or u can

source /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh

回答 6

在OS X 10.8.2中,使用Python 2.7:

/Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh

In OS X 10.8.2, with Python 2.7:

/Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh


回答 7

在OSx EI机长中,我将virtualenvwrapper安装为

sudo pip3 install virtualenvwrapper

,但是我在中找不到virtualenvwrapper.sh /user/local/bin,它终于在找到了/Library/Frameworks/Python.framework/Versions/3.4/bin/virtualenvwrapper.sh,您可以通过以下方式建立到/ usr / local / bin的软链接:

ln -s /Library/Frameworks/Python.framework/Versions/3.4/bin/virtualenvwrapper.sh /usr/local/bin/virtualenvwrapper.sh,您可以按照官方文档的说明按照安装指南进行操作。祝好运!

In OSx EI captain, I installed the virtualenvwrapper as

sudo pip3 install virtualenvwrapper

, however I cannot find the virtualenvwrapper.sh in /user/local/bin, it was finally found at /Library/Frameworks/Python.framework/Versions/3.4/bin/virtualenvwrapper.sh , and you can make an soft link to /usr/local/bin as

ln -s /Library/Frameworks/Python.framework/Versions/3.4/bin/virtualenvwrapper.sh /usr/local/bin/virtualenvwrapper.sh, and everything you can just follow the setup guide as the official document does. Good luck!


回答 8

对我来说是:

~/Library/Python/2.7/bin/virtualenvwrapper.sh

(对于OS X,带有pip install --user安装)

For me it was in :

~/Library/Python/2.7/bin/virtualenvwrapper.sh

(With OS X, with a pip install --user installation)


回答 9

我也有同样的问题。如果您使用的是virtualenvwrapper的旧版本,则pip无法正常工作。

http://pypi.python.org/pypi/virtualenvwrapper/3.6 和python setup.py安装文件下载src 。然后问题解决了。

I have the same problem. If you have older version of virtualenvwrapper, then pip wont work.

download src from http://pypi.python.org/pypi/virtualenvwrapper/3.6 and python setup.py install. Then the problem solved.


回答 10

对于基于RPM的发行版(如Fedora 19),运行sudo pip install virtualenvwrapper命令后,您可以在以下位置找到文件:

/usr/bin/virtualenvwrapper.sh

For RPM-based distributions(like Fedora 19), after running the sudo pip install virtualenvwrapper command, you may find the file at:

/usr/bin/virtualenvwrapper.sh

回答 11

使用普通用户在Ubuntu 15.10上使用pip安装了它,并~/.local/bin/virtualenvwrapper.sh通过运行找到了它:

$ find / -name virtualenvwrapper.sh 2>/dev/null

Installed it using pip on Ubuntu 15.10 using a normal user, it was put in ~/.local/bin/virtualenvwrapper.sh which I found by running:

$ find / -name virtualenvwrapper.sh 2>/dev/null


回答 12

使用

find / -name virtualenvwrapper.sh

我收到大量“拒绝权限”的信息,并且只有一个文件位置的打印输出。我错过了它,直到我用pip再次卸载/安装该文件时找到了该文件位置。

万一你好奇,那是在

/usr/local/share/python/virtualenvwrapper.sh

Using

find / -name virtualenvwrapper.sh

I got a TON of “permissions denied”s, and exactly one printout of the file location. I missed it until I found that file location when I uninstall/installed it again with pip.

In case you were curious, it was in

/usr/local/share/python/virtualenvwrapper.sh

回答 13

就我而言(OSX El Capitan,版本10.11.5),我需要按如下方式编辑.profile:

在终端中:

vim〜/ .profile

export WORKON_HOME=$HOME/.virtualenvs
export MSYS_HOME=C:\msys\1.0
source /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh                                                                                   

然后重新加载配置文件(它将在当前会话中可用。)

来源〜/ .profile

希望它会帮助某人。

In my case (OSX El Capitan, version 10.11.5) I needed to edit the .profile like so:

In the terminal:

vim ~/.profile

export WORKON_HOME=$HOME/.virtualenvs
export MSYS_HOME=C:\msys\1.0
source /Library/Frameworks/Python.framework/Versions/2.7/bin/virtualenvwrapper.sh                                                                                   

And then reload the profile (that it will be availuble in the current session.)

source ~/.profile

Hope it will help someone.


回答 14

我在玩virtualenvwrapper-4.8.4时可以在macOS Mojave(10.14)中找到一个

/Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh

I can find one in macOS Mojave (10.14) while playing with virtualenvwrapper-4.8.4

/Library/Frameworks/Python.framework/Versions/3.7/bin/virtualenvwrapper.sh


回答 15

尽管这是OS X的问题,但这是在Linux(Red Hat)上对我有用的东西。

我的virtualwrapper.sh在

~/.local/bin/virtualenvwrapper.sh

这可能是因为我使用--user标记在本地安装了virtualenvwrapper …

pip install --user virtualenvwrapper

……作为替代冒险的做法使用sudo pip

Although this is an OS X question, here’s what worked for me on Linux (Red Hat).

My virtualwrapper.sh was in

~/.local/bin/virtualenvwrapper.sh

This is probably because I installed virtualenvwrapper locally, using the --user flag…

pip install --user virtualenvwrapper

…as an alternative to the risky practice of using sudo pip.


回答 16

/usr/share/virtualenvwrapper/virtualenvwrapper.sh

我已经在Ubuntu 16.04上安装了它,并找到了这个位置。

/usr/share/virtualenvwrapper/virtualenvwrapper.sh

I’ve installed it on Ubuntu 16.04 and it resulted in this location.


回答 17

/usr/local/bin/virtualenvwrapper.sh
/usr/local/bin/virtualenvwrapper.sh

回答 18

小猎犬骨头黑(debian)也有同样的问题。

手动下载软件包并安装对我有用。

I had the same issue in with the beagle bone black(debian).

Manually downloading the package and installing worked for me.


回答 19

对于Ubuntu,
如果您刚刚安装了它,请检查Terminal上的输出,我在发布我的:

Running setup.py install for virtualenv-clone    
Installing virtualenv-clone script to /home/username/.local/bin
Successfully installed virtualenvwrapper virtualenv virtualenv-clone stevedore pbr six
Cleaning up...

第二行告诉您路径。对我来说/home/username/.local/bin

For Ubuntu
If you just installed it, check the output on Terminal, I’m posting mine :

Running setup.py install for virtualenv-clone    
Installing virtualenv-clone script to /home/username/.local/bin
Successfully installed virtualenvwrapper virtualenv virtualenv-clone stevedore pbr six
Cleaning up...

Here the second line tells you the path. For me it was at /home/username/.local/bin


回答 20

点子不会试图让您为难。

问题是基于命令的文件始终安装在/bin文件夹中,它们可以位于系统路径上的任何位置。

我遇到了同样的问题,发现我的文件中有这些文件

~/.local/bin/

文件夹而不是

/usr/loca/bin/

这是常见的情况,但我认为他们将默认路径更改为

~ 或$ HOME

目录,因为它对pip安装更隔离,并提供了apt-get软件包和pip软件包之间的区别。

所以说到这里,您有两种选择,要么转到 .bashrc,然后进行如下更改

# for virtualenv wrapper
export WORKON_HOME=$HOME/Envs
export PROJECT_HOME=$HOME/Devel
source $HOME/.local/bin/virtualenvwrapper.sh

然后在下面创建目录virtualenvwrapper/usr/share/然后像这样符号链接您的virtualwrapper_lazy.sh

sudo ln -s ~/.local/bin/virtualenvwrapper_lazy.sh /usr/share/virtualenvwrapper/virtualenvwrapper_lazy.sh

并且您可以检查您的workon命令是否正在运行,该命令将列出您现有的virtualenv。

pip will not try to make things difficult for you on purpose.

The thing is commands based files are always installed in /bin folders they can be anywhere on the system path.

I had the same problem and I found that I have these files in my

~/.local/bin/

folder instead of

/usr/loca/bin/

which is the common case, but I think they changed the default path to

~ or $HOME

directory because its more isolate for the pip installations and provides a distinction between apt-get packages and pip packages.

So coming to the point you have two choices here either you go to your .bashrc and make changes like this

# for virtualenv wrapper
export WORKON_HOME=$HOME/Envs
export PROJECT_HOME=$HOME/Devel
source $HOME/.local/bin/virtualenvwrapper.sh

and than create a directory virtualenvwrapper under /usr/share/ and than symlink your virtualwrapper_lazy.sh like this

sudo ln -s ~/.local/bin/virtualenvwrapper_lazy.sh /usr/share/virtualenvwrapper/virtualenvwrapper_lazy.sh

and you can check if your workon command is working which will list your existing virtualenv’s.


回答 21

如果您pip install virtualenvwrapper不使用sudo来执行,那么普通的用户pip将运行,但由于缺少权限而不会在所需位置复制文件

mortiz@florida:~# sudo pip3 install virtualenvwrapper

使用sudo,文件将在它们各自的路径下创建:

root@florida:/usr/local/bin# ls -ltr
total 8008
-rwxr-xr-x 1 root staff 8136192 Jun 11 17:45 chromedriver
-rwxr-xr-x 1 root staff   41697 Sep  5 16:06 virtualenvwrapper.sh
-rwxr-xr-x 1 root staff    2210 Sep  5 16:06 virtualenvwrapper_lazy.sh
-rwxr-xr-x 1 root staff     215 Sep  5 16:06 pbr
-rwxr-xr-x 1 root staff     218 Sep  5 16:06 virtualenv-clone
-rwxr-xr-x 1 root staff     213 Sep  5 16:06 virtualenv
root@florida:/usr/local/bin# 

在Debian GNU / Linux 9上为我工作

If you execute pip install virtualenvwrapper without sudo as a normal user pip will run but won’t copy the files in the required locations because the lack of permissions.

mortiz@florida:~# sudo pip3 install virtualenvwrapper

Use sudo and the files will be created under their respective paths:

root@florida:/usr/local/bin# ls -ltr
total 8008
-rwxr-xr-x 1 root staff 8136192 Jun 11 17:45 chromedriver
-rwxr-xr-x 1 root staff   41697 Sep  5 16:06 virtualenvwrapper.sh
-rwxr-xr-x 1 root staff    2210 Sep  5 16:06 virtualenvwrapper_lazy.sh
-rwxr-xr-x 1 root staff     215 Sep  5 16:06 pbr
-rwxr-xr-x 1 root staff     218 Sep  5 16:06 virtualenv-clone
-rwxr-xr-x 1 root staff     213 Sep  5 16:06 virtualenv
root@florida:/usr/local/bin# 

Worked for me on Debian GNU/Linux 9


回答 22

就我而言:/home/username/.local/bin/virtualenvwrapper.sh

in my case: /home/username/.local/bin/virtualenvwrapper.sh


回答 23

您是否使用sudo安装了它?在我的情况下是错误。

Have you installed it using sudo? Was the error in my case.


使用virtualenv恢复`–no-site-packages`选项

问题:使用virtualenv恢复`–no-site-packages`选项

我使用该--no-site-packages选项创建了virtualenv 并安装了许多库。现在,我想还原该--no-site-packages选项并使用全局包。

我可以不重新创建virtualenv来做到吗?

更确切地说:

我不知道究竟创建使用一个的virtualenv发生时,--no-site-packages相对于没有使用该选项的选择。

如果我知道会发生什么,那么我可以弄清楚如何撤消它。

I have created a virtualenv using the --no-site-packages option and installed lots of libraries. Now I would like to revert the --no-site-packages option and use also the global packages.

Can I do that without recreating the virtualenv?

More precisely:

I wonder what exactly happens when creating a virtualenv using the --no-site-packages option as opposed to not using that option.

If I know what happens then I can figure out how to undo it.


回答 0

尝试删除(或重命名)虚拟环境下文件夹no-global-site-packages.txt中的Lib文件。

其中venv是您的虚拟环境的名称,而python3.4对应于所涉及的任何python版本,例如:

$ rm venv/lib/python3.4/no-global-site-packages.txt

如果您改变主意并想放回原处:

$ touch venv/lib/python3.4/no-global-site-packages.txt

注意:如果看不到上述文件,则说明您有较新版本的virtualenv。你要遵循这个答案,而不是

Try removing (or renaming) the file no-global-site-packages.txt in your Lib folder under your virtual environment.

Where venv is the name of your virtual environment, and python3.4 corresponds to whichever version of python involved, for example:

$ rm venv/lib/python3.4/no-global-site-packages.txt

And if you change your mind and want to put it back:

$ touch venv/lib/python3.4/no-global-site-packages.txt

Note: If you don’t see the above file, then you have a newer version of virtualenv. You’ll want to follow this answer instead


回答 1

至少对于Python 3.5.2,pyvenv.cfg在virtualenv目录的根目录中有一个文件。您需要做的就是将include-system-site-packages标志从更改falsetrue

home = /usr/bin
include-system-site-packages = false  # <- change this to "true"
version = 3.5.2

At least for Python 3.5.2, there is pyvenv.cfg file in the root of virtualenv directory. All you need to do is to change include-system-site-packages flag from false to true:

home = /usr/bin
include-system-site-packages = false  # <- change this to "true"
version = 3.5.2

回答 2

使用virtualenvwrapper管理virtualenvs时,可以使用shell函数toggleglobalsitepackages在使用和不使用站点包之间进行切换。

When using virtualenvwrapper to manage virtualenvs, you can use the shell function toggleglobalsitepackages to switch between using and not using site packages.


回答 3

尝试在/virtualenv_root/lib/和之间添加符号链接/path/to/desired/site-packages/

Try adding a symlink between /virtualenv_root/lib/ and /path/to/desired/site-packages/


回答 4

转到您的venv文件夹并打开pyvenv.cfg。(例如,如果您的虚拟环境被调用,myenv则该文件将位于myenv\pyvenv.cfg

您会看到一个布尔设置,名为 include-system-site-packages

将该设置设置true为使用全局包

如果要禁用使用全局软件包,只需将该设置设置为即可false

Go to your venv folder and open pyvenv.cfg. (E.g. if your virtual environment is called myenv then the file will be located at myenv\pyvenv.cfg)

You’ll see a boolean setting called include-system-site-packages

Set that setting to true to use global packages

If you want to disable using global packages, just set that setting to false instead.


我可以将Python Windows软件包安装到virtualenvs吗?

问题:我可以将Python Windows软件包安装到virtualenvs吗?

Virtualenv很棒:它可以让我保留许多不同的Python安装,这样就不会将不同项目的依赖项放在一起。

但是,如果要在以.exe安装程序打包的Windows上安装软件包,如何将其定向安装到virtualenv中?例如,我有pycuda-0.94rc.win32-py2.6.exe。当我运行它时,它会检查注册表,并仅找到一个要安装到我的virtualenv所基于的通用Python26中。

如何引导它安装到virtualenv中?

Virtualenv is great: it lets me keep a number of distinct Python installations so that different projects’ dependencies aren’t all thrown together into a common pile.

But if I want to install a package on Windows that’s packaged as a .exe installer, how can I direct it to install into the virtualenv? For example, I have pycuda-0.94rc.win32-py2.6.exe. When I run it, it examines the registry, and finds only one Python26 to install into, the common one that my virtualenv is based off of.

How can I direct it to install into the virtualenv?


回答 0

是的你可以。所有你需要的是

easy_install binary_installer_built_with_distutils.exe

惊讶吗 看起来用distutils制作的Windows二进制安装程序将.exe和.zip合并为一个.exe文件。将扩展名更改为.zip以查看它是有效的zip文件。在阅读我的问题的答案后,我发现了这一点。在哪里可以从Windows下载带有psycopg2的二进制鸡蛋?

更新

正如Tritium21在他今天的回答中指出的那样,您应该使用pip代替easy_install。Pip无法安装distutils创建的二进制软件包,但可以在新版本中安装二进制软件包 wheel格式的。您可以使用滚轮套件将旧格式转换为新格式,必须先安装。

Yes, you can. All you need is

easy_install binary_installer_built_with_distutils.exe

Surprised? It looks like binary installers for Windows made with distutils combine .exe with .zip into one .exe file. Change extension to .zip to see it’s a valid zip file. I discovered this after reading answers to my question Where can I download binary eggs with psycopg2 for Windows?

UPDATE

As noted by Tritium21 in his answer nowadays you should use pip instead of easy_install. Pip can’t install binary packages created by distutils but it can install binary packages in the new wheel format. You can convert from old format to the new one using wheel package, which you have to install first.


回答 1

我知道这是一个很老的问题,并且早于我要谈论的工具,但是对于Google而言,我认为提这个问题是个好主意。easy_install是python包装的败类。没有人愿意承认使用这种新的流行点子。同样,尽管玩注册表技巧对于非标准EXE安装程序最为有效(有人自己安装了安装程序而不是使用distutils,并正在检查注册表中的安装路径),但现在有一种更好的方法用于标准EXE安装程序。

pip install wheel
wheel convert INSTALLER.EXE
pip install NEW_FILE_CREATED_IN_LAST_STEP.whl

在本博文中最近引入的轮式是蛋形的替代品,起着相同的作用。pip(virtualenv中已安装的工具)也支持此格式。

如果由于某种原因pip install WHEELFILE不起作用,请尝试wheel install WHEELFILE

I know this is quite an old question, and predates the tools I am about to talk about, but for the sake of Google, I think it is a good idea to mention it. easy_install is the black sheep of python packaging. No one wants to admit using it with the new hotness of pip around. Also, while playing registry tricks will work best for non-standard EXE installers (someone built the installer themselves instead of using distutils, and is checking the registry for the installation path), there is now a Better Way(c) for standard EXE installers.

pip install wheel
wheel convert INSTALLER.EXE
pip install NEW_FILE_CREATED_IN_LAST_STEP.whl

The wheel format, introduced recently as of this post, is the replacement for the egg format, filling much the same role. This format is also supported by pip (a tool already installed in your virtualenv).

if for some reason pip install WHEELFILE does not work, try wheel install WHEELFILE


回答 2

我最终修改了一个脚本(http://effbot.org/zone/python-register.htm)以在注册表中注册Python安装。我可以选择Python 作为注册表中 Python,运行Windows安装程序,然后重新设置注册表:

# -*- encoding: utf-8 -*-
#
# script to register Python 2.0 or later for use with win32all
# and other extensions that require Python registry settings
#
# Adapted by Ned Batchelder from a script
# written by Joakim Löw for Secret Labs AB / PythonWare
#
# source:
# http://www.pythonware.com/products/works/articles/regpy20.htm

import sys

from _winreg import *

# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix

regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
    installpath, installpath, installpath
)

def RegisterPy():
    try:
        reg = OpenKey(HKEY_LOCAL_MACHINE, regpath)
    except EnvironmentError:
        try:
            reg = CreateKey(HKEY_LOCAL_MACHINE, regpath)
        except Exception, e:
            print "*** Unable to register: %s" % e
            return

    SetValue(reg, installkey, REG_SZ, installpath)
    SetValue(reg, pythonkey, REG_SZ, pythonpath)
    CloseKey(reg)
    print "--- Python %s at %s is now registered!" % (version, installpath)

if __name__ == "__main__":
    RegisterPy()

使用您要注册的Python运行此脚本,它将被输入到注册表中。请注意,在Windows 7和Vista上,您需要具有管理员权限。

I ended up adapting a script (http://effbot.org/zone/python-register.htm) to register a Python installation in the registry. I can pick the Python to be the Python in the registry, run the Windows installer, then set the registry back:

# -*- encoding: utf-8 -*-
#
# script to register Python 2.0 or later for use with win32all
# and other extensions that require Python registry settings
#
# Adapted by Ned Batchelder from a script
# written by Joakim Löw for Secret Labs AB / PythonWare
#
# source:
# http://www.pythonware.com/products/works/articles/regpy20.htm

import sys

from _winreg import *

# tweak as necessary
version = sys.version[:3]
installpath = sys.prefix

regpath = "SOFTWARE\\Python\\Pythoncore\\%s\\" % (version)
installkey = "InstallPath"
pythonkey = "PythonPath"
pythonpath = "%s;%s\\Lib\\;%s\\DLLs\\" % (
    installpath, installpath, installpath
)

def RegisterPy():
    try:
        reg = OpenKey(HKEY_LOCAL_MACHINE, regpath)
    except EnvironmentError:
        try:
            reg = CreateKey(HKEY_LOCAL_MACHINE, regpath)
        except Exception, e:
            print "*** Unable to register: %s" % e
            return

    SetValue(reg, installkey, REG_SZ, installpath)
    SetValue(reg, pythonkey, REG_SZ, pythonpath)
    CloseKey(reg)
    print "--- Python %s at %s is now registered!" % (version, installpath)

if __name__ == "__main__":
    RegisterPy()

Run this script with the Python you want to be registered, and it will be entered into the registry. Note that on Windows 7 and Vista, you’ll need Administrator privileges.


回答 3

easy_install能够安装.exe软件包,只要它们是使用distutils的bdist_wininst目标构建的,该目标涵盖了许多流行的软件包。但是,还有许多其他方面不是(wxPython是我一直在努力的一种)

easy_install is able to install .exe packages as long as they were built using distutils’ bdist_wininst target, which covers many popular packages. However, there are many others that aren’t (wxPython is one that I’ve struggled with)


回答 4

您可以使用环境的easy_install来安装PyCUDA。

dev-env-path/bin/easy_install pycuda

它将为您提供相同的0.94rc版本。

在Windows上,easy_install.exe将位于Scripts目录中。

You can use environment’s easy_install to install PyCUDA.

dev-env-path/bin/easy_install pycuda

it will give you the same version 0.94rc.

On Windows easy_install.exe will be in Scripts directory.


回答 5

如果是.msi,则可以使用来指定命令行选项msiexec。Python 安装程序本身允许TARGETDIR,但是我不确定distutils是否将此安装到发行版安装程序中。

如果您使用.exe,我认为没有一种干净的方法。一种选择是使用诸如7Zip(或winzip等)之类的程序直接提取exe的内容,然后将relevent文件夹复制到您的虚拟site-packages文件夹中。例如,如果我解压缩“ processing-0.5.2.win32-py2.5.exe”,则会找到一个文件夹“ PLATLIB \ processing”,将其复制到virtualenv路径并可以使用,而不会出现任何运行时问题。(我不确定这是否总是那么简单。)

If it’s a .msi, you might be able to specify command line options using msiexec. The Python installer itself allows TARGETDIR, but I’m not sure if distutils bakes this into distribution installers.

If you’re using a .exe, I don’t think there’s a clean way. One option is to use a program like 7Zip (or winzip, etc) to directly extract the contents of the exe, then copy the relevent folders into your virtual site-packages folder. For example, if I extract “processing-0.5.2.win32-py2.5.exe”, I find a folder “PLATLIB\processing” which I copy to a virtualenv path and use without any runtime problems. (I’m not sure it’s always that simple though.)


ImportError:没有名为Crypto.Cipher的模块

问题:ImportError:没有名为Crypto.Cipher的模块

当我尝试运行app.py(Python 3.3,PyCrypto 2.6)时,我的virtualenv不断返回上面列出的错误。我的进口货单是from Crypto.Cipher import AES。我在寻找重复项,您可能会说有重复项,但是我尝试了解决方案(尽管大多数都不是解决方案),但没有任何效果。

您可以在下面查看PyCrypto的文件格式:

When I try to run app.py (Python 3.3, PyCrypto 2.6) my virtualenv keeps returning the error listed above. My import statement is just from Crypto.Cipher import AES. I looked for duplicates and you might say that there are some, but I tried the solutions (although most are not even solutions) and nothing worked.

You can see what the files are like for PyCrypto below:


回答 0

我有同样的问题(尽管在Linux上)。解决方案非常简单-添加:

libraries:
- name: pycrypto
  version: "2.6"

到我的app.yaml文件。由于过去该方法正常工作,因此我认为这是一个新要求。

I had the same problem (though on Linux). The solution was quite simple – add:

libraries:
- name: pycrypto
  version: "2.6"

to my app.yaml file. Since this worked correctly in the past, I assume this is a new requirement.


回答 1

使用进行安装时,在Mac上出现相同的问题pip。然后pycrypto,我使用删除并重新安装了它easy_install,如下所示:

pip uninstall pycrypto
easy_install pycrypto

就像卢克(Luke)所说:如果您在运行这些命令时遇到问题,请确保以admin(sudo)身份运行它们

希望这可以帮助!

编辑:正如winklerr在上面正确指出的那样,pycrypto不再安全。改用pycryptodome,它是一个替代品

I had the same problem on my Mac when installing with pip. I then removed pycrypto and installed it again with easy_install, like this:

pip uninstall pycrypto
easy_install pycrypto

also as Luke commented: If you have trouble running these commands, be sure to run them as admin (sudo)

Hope this helps!

EDIT: As winklerr correctly notes above, pycrypto is no longer safe. Use pycryptodome instead, it is a drop-in replacement


回答 2

我也在Mac上遇到了这个问题,它似乎与通过pip在pycrypto旁边安装了一个不幸的名字相似的“ crypto”模块(不确定该用于什么目的)有关。

该修复程序似乎正在通过pip删除crypto和pycrypto:

sudo pip uninstall crypto
sudo pip uninstall pycrypto

并重新安装pycrypto:

sudo pip install pycrypto

现在,当我执行以下操作时,它可以按预期工作:

from Crypto.Cipher import AES

I ran into this on Mac as well, and it seems to be related to having an unfortunately similarly named “crypto” module (not sure what that is for) installed alongside of pycrypto via pip.

The fix seems to be removing both crypto and pycrypto with pip:

sudo pip uninstall crypto
sudo pip uninstall pycrypto

and reinstalling pycrypto:

sudo pip install pycrypto

Now it works as expected when I do something like:

from Crypto.Cipher import AES

回答 3

在Mac上…如果遇到此问题,请尝试是否可以导入加密货币?

如果是这样..包名是问题CVS c。要解决此问题,只需将这些行添加到脚本的顶部。

import crypto
import sys
sys.modules['Crypto'] = crypto

您知道应该能够成功导入paramiko。

On the mac… if you run into this.. try to see if you can import crypto instead?

If so.. the package name is the issue C vs c. To get around this.. just add these lines to the top of your script.

import crypto
import sys
sys.modules['Crypto'] = crypto

You know should be able to import paramiko successfully.


回答 4

正在卸载cryptopycrypto在我身上工作。然后仅安装pycrypto

pip uninstall crypto 
pip uninstall pycrypto 
pip install pycrypto

Uninstalling crypto and pycrypto works on me. Then install only pycrypto:

pip uninstall crypto 
pip uninstall pycrypto 
pip install pycrypto

回答 5

我找到了解决方案。问题可能是区分大小写(在Windows上)。

只需更改文件夹的名称:

  • C:\Python27\Lib\site-packages\crypto
  • 至: C:\Python27\Lib\site-packages\Crypto

这是在安装pycrypto之后命名文件夹的方式:

我将其更改为:

现在,以下代码可以正常工作:

I found the solution. Issue is probably in case sensitivity (on Windows).

Just change the name of the folder:

  • C:\Python27\Lib\site-packages\crypto
  • to: C:\Python27\Lib\site-packages\Crypto

This is how folder was named after installation of pycrypto:

I’ve changed it to:

And now the following code works fine:


回答 6

警告:请勿使用 pycrypto

正如你可以在阅读此页,的用法pycrypto不是安全了:

Pycrypto容易受block_templace.c中ALGnew函数中基于堆的缓冲区溢出的影响。它允许远程攻击者在python应用程序中执行任意代码。它被分配了CVE-2013-7459号。

自2014年6月20日以来,Pycrypto尚未发布对该漏洞的任何修复程序,也没有对该项目进行任何提交。

解决方案:使用Python3和pycryptodome

TL; DR: pip3 install pycryptodome

确保先卸载其他版本cryptopycrypto

设置新的虚拟环境

要安装虚拟环境并设置所有内容,请使用以下命令:

# install python3 and pip3
sudo apt update
sudo apt upgrade
sudo apt install python3
sudo apt install python3-pip

# install virtualenv
pip3 install virtualenv

# install and create a virtual environment in your target folder
mkdir target_folder
cd target_folder
python3 -m virtualenv .

# now activate your venv and install pycryptodome
source bin/activate
pip3 install pycryptodome

# check if everything worked: 
# start the interactive python console and import the Crypto module
# when there is no import error then it worked
python
>>> from Crypto.Cipher import AES
>>> exit()

# don't forget to deactivate your venv again
deactivate

有关更多信息,请参见pycryptodome.org。

WARNING: Don’t use pycrypto anymore!

As you can read on this page, the usage of pycrypto is not safe anymore:

Pycrypto is vulnerable to a heap-based buffer overflow in the ALGnew function in block_templace.c. It allows remote attackers to execute arbitrary code in the python application. It was assigned the CVE-2013-7459 number.

Pycrypto didn’t release any fix to that vulnerability and no commit was made to the project since Jun 20, 2014.

Use Python3 and pycryptodome instead!

pip3 uninstall crypto 
pip3 uninstall pycrypto 
pip3 install pycryptodome

Make sure to uninstall other versions of crypto or pycrypto first because both packages install under the same folder Crypto where also pycryptodome will be installed.

Best practice: virtual environments

In order to avoid problems with pip packages in different versions or packages that install under the same folder (i.e. pycrypto and pycryptodome) you can make use of a so called virtual environment. There, the installed pip packages can be managed for every single project individually.

To install a virtual environment and setup everything, use the following commands:

# install python3 and pip3
sudo apt update
sudo apt upgrade
sudo apt install python3
sudo apt install python3-pip

# install virtualenv
pip3 install virtualenv

# install and create a virtual environment in your target folder
mkdir target_folder
cd target_folder
python3 -m virtualenv .

# now activate your venv and install pycryptodome
source bin/activate
pip3 install pycryptodome

# check if everything worked: 
# start the interactive python console and import the Crypto module
# when there is no import error then it worked
python
>>> from Crypto.Cipher import AES
>>> exit()

# don't forget to deactivate your venv again
deactivate

For more information, see pycryptodome.org


回答 7

输入命令:

sudo pip install pycrypto

type command:

sudo pip install pycrypto

回答 8

如果您使用的是redhat,fedora,centos:

sudo yum install pycrypto

就我而言,我不会使用pip安装它

if you are using redhat,fedora, centos :

sudo yum install pycrypto

for my case I coouldnot install it using pip


回答 9

我遇到了同样的问题 'ImportError: No module named Crypto.Cipher',因为在OSX 10.8.5(Mountain Lion)上将GoogleAppEngineLauncher(版本> 1.8.X)与GAE Boilerplate一起使用。在具有python 2.7运行时的Google App Engine SDK中,建议使用pyCrypto 2.6。对我有用的解决方案是…

1)下载pycrypto2.6源将其解压缩到某处(~/Downloads/pycrypto26

例如,git clone https://github.com/dlitz/pycrypto.git

2)cdcd ~/Downloads/pycrypto26)然后

3)在上一个文件夹中执行以下终端命令,以便在GAE文件夹中手动安装pyCrypto 2.6。

sudo python setup.py install --install-lib /Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine

I’ve had the same problem 'ImportError: No module named Crypto.Cipher', since using GoogleAppEngineLauncher (version > 1.8.X) with GAE Boilerplate on OSX 10.8.5 (Mountain Lion). In Google App Engine SDK with python 2.7 runtime, pyCrypto 2.6 is the suggested version. The solution that worked for me was…

1) Download pycrypto2.6 source extract it somewhere(~/Downloads/pycrypto26)

e.g., git clone https://github.com/dlitz/pycrypto.git

2) cd (cd ~/Downloads/pycrypto26) then

3) Execute the following terminal command inside the previous folder in order to install pyCrypto 2.6 manually in GAE folder.

sudo python setup.py install --install-lib /Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine

回答 10

如果您是macOS,请将lib文件夹重命名lib/python3.7/site-packages/cryptolib/python3.7/site-packages/Crypto

If you an macos, rename lib folder lib/python3.7/site-packages/crypto to lib/python3.7/site-packages/Crypto


回答 11

尝试使用pip3

sudo pip3 install pycrypto

Try with pip3:

sudo pip3 install pycrypto

回答 12

加载通过pip安装的python模块可能是一个问题。参考此答案无法从site-packages目录加载通过pip安装的Python模块,并尝试类似

python -m pip install pycrypto

It could be a problem of loading python modules installed via pip. Refer to this answer Can’t load Python modules installed via pip from site-packages directory and try something like

python -m pip install pycrypto

回答 13

为我工作(Ubuntu 17.10)

删除venv并使用python v3.6重新创建

pip3 install PyJWT
sudo apt-get install build-essential libgmp3-dev python3-dev
pip3 install cryptography
pip3 install pycryptodome
pip3 install pycryptodomex

Pycrypto已过时,有问题,使用Pycryptodome

Worked for me (Ubuntu 17.10)

Removing venv and creating it again with python v3.6

pip3 install PyJWT
sudo apt-get install build-essential libgmp3-dev python3-dev
pip3 install cryptography
pip3 install pycryptodome
pip3 install pycryptodomex

Pycrypto is deprecated, had problems with it, used Pycryptodome


回答 14

我通过将首字母大写更改为大写来解决此问题。确保“从Crypto.Cipher导入AES”而不是“从crypto.Cipher导入AES”。

I solve this problem by change the first letter case to upper. Make sure ”from Crypto.Cipher import AES” not ”from crypto.Cipher import AES”.


回答 15

对于CentOS 7.4,我首先安装了pip,然后使用pip安装了pycrypto:

> sudo yum -y install python-pip 
> sudo python -m pip install pycrypto

For CentOS 7.4 I first installed pip and then pycrypto using pip:

> sudo yum -y install python-pip 
> sudo python -m pip install pycrypto

回答 16

迄今为止,from Crypto.Cipher import AES即使我安装/重新安装了pycrypto几次,导入时也遇到相同的问题。最终是因为pip默认为python3。

~ pip --version
pip 18.0 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)

使用pip2安装pycrypto应该可以解决此问题。

To date, I’m having same issue when importing from Crypto.Cipher import AES even when I’ve installed/reinstalled pycrypto a few times. End up it’s because pip defaulted to python3.

~ pip --version
pip 18.0 from /usr/local/lib/python3.7/site-packages/pip (python 3.7)

installing pycrypto with pip2 should solve this issue.


回答 17

对于Windows 7:

我遇到了这个错误“模块错误Crypo.Cipher导入AES”

要在Windows中安装Pycrypto,

在命令提示符中尝试此操作,

设置路径= C:\ Python27 \ Scripts(即easy_install所在的路径)

然后执行以下命令

easy_install pycrypto

对于Ubuntu:

试试这个,

从“ https://pypi.python.org/pypi/pycrypto下载Pycrypto

然后使用终端将当前路径更改为下载路径:

例如:root @ xyz-virtual-machine:〜/ pycrypto-2.6.1#

然后使用终端执行以下命令:

python setup.py安装

对我有用。希望为所有人服务。

For Windows 7:

I got through this error “Module error Crypo.Cipher import AES”

To install Pycrypto in Windows,

Try this in Command Prompt,

Set path=C:\Python27\Scripts (i.e path where easy_install is located)

Then execute the following,

easy_install pycrypto

For Ubuntu:

Try this,

Download Pycrypto from “https://pypi.python.org/pypi/pycrypto

Then change your current path to downloaded path using your terminal:

Eg: root@xyz-virtual-machine:~/pycrypto-2.6.1#

Then execute the following using the terminal:

python setup.py install

It’s worked for me. Hope works for all..


回答 18

可以通过安装C ++编译器(python27或python26)来解决此问题。从Microsoft https://www.microsoft.com/zh-cn/download/details.aspx?id=44266下载它,然后重新运行命令:pip install pycrypto当您杀死.NET 进程时运行gui Web访问easy_install.exe

This problem can be fixed by installing the C++ compiler (python27 or python26). Download it from Microsoft https://www.microsoft.com/en-us/download/details.aspx?id=44266 and re-run the command : pip install pycrypto to run the gui web access when you kill the process of easy_install.exe.


回答 19

也许您应该这样做:pycryptodome == 3.6.1将其添加到requirements.txt并安装,这应该消除错误报告。这个对我有用!

Maybe you should this: pycryptodome==3.6.1 add it to requirements.txt and install, which should eliminate the error report. it works for me!


回答 20

这对我有用

pip install pycryptodome==3.4.3

This worked for me

pip install pycryptodome==3.4.3

回答 21

嗯,这可能会出现奇怪,但安装后pycrypto还是pycryptodome,我们需要更新的目录名cryptoCryptolib/site-packages

参考

Well this might appear weird but after installing pycrypto or pycryptodome , we need to update the directory name crypto to Crypto in lib/site-packages

Reference


回答 22

我是3.7。在我尝试安装加密货币后,问题仍然存在。在我的情况下,pycrypto只是失败了。所以最后我的构建通过下面的包传递:pip install pycryptodome

I’m with 3.7. The issue remains after I try to install crypto. And pycrypto just fails in my case. So in the end my build passed via package below: pip install pycryptodome


virtualenv的问题-无法激活

问题:virtualenv的问题-无法激活

我在项目周围创建了一个virtualenv,但是当我尝试激活它时却无法。它可能只是语法或文件夹位置,但是我现在很困惑。

您可以在下面看到,我创建了virtualenv并将其称为venv。一切看起来不错,然后我尝试通过运行来激活它source venv/bin/activate

我在想这可能与我的系统路径有关,但不确定要指向什么(我确实知道如何编辑路径)。我在python 7 / Windows OS上,虚拟环境2.2.x

处理virtualenv的依赖项
已完成virtualenv的处理依赖性

c:\ testdjangoproj \ mysite> virtualenv --no-site-packages venv
--no-site-packages标志已弃用;现在是默认行为。
使用真实的前缀'C:\\ Program Files(x86)\\ Python'
venv \ Scripts \ python.exe中的新python可执行文件
venv \ Lib \ distutils \ distutils.cfg文件存在不同的内容;不过度
ting
安装setuptools ........完成。
安装pip .........完成。

c:\ testdjangoproj \ mysite>源venv / bin / activate
无法将“源”识别为内部或外部命令,
可操作的程序或批处理文件。

c:\ testdjangoproj \ mysite>源venv / bin / activate
无法将“源”识别为内部或外部命令,
可操作的程序或批处理文件。

c:\ testdjangoproj \ mysite>来源mysite / bin / activate
无法将“源”识别为内部或外部命令,
可操作的程序或批处理文件。

c:\ testdjangoproj \ mysite>

I created a virtualenv around my project, but when I try to activate it I cannot. It might just be syntax or folder location, but I am stumped right now.

You can see below, I create the virtualenv and call it venv. Everything looks good, then I try to activate it by running source venv/bin/activate

I’m thinking it might just have to do with my system path, but not sure what to point it to (I do know how to edit the path). I’m on python 7 / windows os, virtual env 2.2.x

Processing dependencies for virtualenv
Finished processing dependencies for virtualenv

c:\testdjangoproj\mysite>virtualenv --no-site-packages venv
The --no-site-packages flag is deprecated; it is now the default behavior.
Using real prefix 'C:\\Program Files (x86)\\Python'
New python executable in venv\Scripts\python.exe
File venv\Lib\distutils\distutils.cfg exists with different content; not overwri
ting
Installing setuptools.................done.
Installing pip...................done.

c:\testdjangoproj\mysite>source venv/bin/activate
'source' is not recognized as an internal or external command,
operable program or batch file.

c:\testdjangoproj\mysite>source venv/bin/activate
'source' is not recognized as an internal or external command,
operable program or batch file.

c:\testdjangoproj\mysite>source mysite/bin/activate
'source' is not recognized as an internal or external command,
operable program or batch file.

c:\testdjangoproj\mysite>

回答 0

source 是为在Linux(或任何Posix,但不包括Windows)上运行的用户设计的shell命令。

在Windows上,virtualenv会创建一个批处理文件,因此您应该venv\Scripts\activate改为运行它(根据Activate 脚本上的 virtualenv 文档)。

编辑: 这里的Windows技巧不是指定BAT扩展名:

PS C:\ DEV \ aProject \ env \ Scripts> ..activate
(env)PS C:\ DEV \ aProject \ env \ Scripts>

source is a shell command designed for users running on Linux (or any Posix, but whatever, not Windows).

On Windows, virtualenv creates a batch file, so you should run venv\Scripts\activate instead (per the virtualenv documentation on the activate script).

Edit: The trick here for Windows is not specifying the BAT extension:

PS C:\DEV\aProject\env\Scripts> & .\activate
(env) PS C:\DEV\aProject\env\Scripts>


回答 1

我的Windows 10机器中也遇到了同样的问题。我尝试过的步骤是:

转到andconda终端步骤1

pip3 install -U pip virtualenv

第2步

virtualenv --system-site-packages -p python ./venv

要么

virtualenv --system-site-packages -p python3 ./venv

第三步

.\venv\Scripts\activate

您可以通过键入Python中的蜘蛛工具来检查它 import tensorflow as tf

I was also facing the same issue in my Windows 10 machine. What steps i tried were:

Go to andconda terminal Step 1

pip3 install -U pip virtualenv

Step 2

virtualenv --system-site-packages -p python ./venv

or

virtualenv --system-site-packages -p python3 ./venv

Step 3

.\venv\Scripts\activate

You can check it via spider tool in anaconda by typing import tensorflow as tf


回答 2

我有同样的问题。我正在使用Python 2,Windows 10和Git Bash。事实证明,您需要使用Git Bash:

 source venv/Scripts/activate

I had the same problem. I was using Python 2, Windows 10 and Git Bash. Turns out in Git Bash you need to use:

 source venv/Scripts/activate

回答 3

  1. 要进行激活,您可以通过转到venv您的virtualenv目录cd venv

  2. 然后在Windows上,键入dir(在UNIX上,键入ls)。您将获得5个文件夹includeLibScriptstcl和60

  3. 现在键入.\Scripts\activate以激活您的virtualenv venv

您的提示将更改以指示您现在正在虚拟环境中操作。它看起来像这样(venv)user@host:~/venv$

并且您venv现在被激活了。

  1. For activation you can go to the venv your virtualenv directory by cd venv.

  2. Then on Windows, type dir (on unix, type ls). You will get 5 folders include, Lib, Scripts, tcl and 60

  3. Now type .\Scripts\activate to activate your virtualenv venv.

Your prompt will change to indicate that you are now operating within the virtual environment. It will look something like this (venv)user@host:~/venv$.

And your venv is activated now.


回答 4

对于Windows,在没有引号的终端中键入“ C:\ Users \ Sid \ venv \ FirstProject \ Scripts \ activate”。只需提供您的Scripts文件夹在项目中的位置。因此,该命令将为location_of_the_Scripts_Folder \ activate。

For windows, type “C:\Users\Sid\venv\FirstProject\Scripts\activate” in the terminal without quotes. Simply give the location of your Scripts folder in your project. So, the command will be location_of_the_Scripts_Folder\activate.


回答 5

确保venv在那,并按照以下命令操作。它适用于Windows 10。

转到您希望虚拟环境驻留的路径:

> cd <my_venv_path>

创建名为“ env”的虚拟环境:

> python -m venv env 

将路径添加到git ignore文件(可选):

> echo env/ >> .gitignore

激活虚拟环境:

> .\env\Scripts\activate

Ensure venv is there and just follow the commands below. It works in Windows 10.

Go to the path where you want your virtual enviroments to reside:

> cd <my_venv_path>

Create the virtual environment named “env”:

> python -m venv env 

Add the path to the git ignore file (optional):

> echo env/ >> .gitignore

Activate the virtual env:

> .\env\Scripts\activate

回答 6

virtualenv在使用git bash的Windows上玩得很开心,我通常最终会明确指定python二进制文件。

如果我的环境在,.env我会通过./.env/Scripts/python.exe …或在shebang行中调用python#!./.env/Scripts/python.exe ;

两者都假设您的工作目录包含您的virtualenv(.env)。

I have a hell of a time using virtualenv on windows with git bash, I usually end up specifying the python binary explicitly.

If my environment is in say .env I’ll call python via ./.env/Scripts/python.exe …, or in a shebang line #!./.env/Scripts/python.exe;

Both assuming your working directory contains your virtualenv (.env).


回答 7

您可以在cygwin终端上运行source命令

You can run the source command on cygwin terminal


回答 8

如果你看到5个文件夹(IncludeLibScriptstclpip-selfcheck使用后)virtualenv yourenvname命令,更改目录到Scripts文件夹在CMD本身并简单地用“ 激活 ”命令。

If you see the 5 folders (Include,Lib,Scripts,tcl,pip-selfcheck) after using the virtualenv yourenvname command, change directory to Scripts folder in the cmd itself and simply use “activate” command.


回答 9

使用任何gitbash控制台打开文件夹。例如,使用visualCode和Gitbash控制台程序:1)为Windows安装Gitbash

2)使用VisualCode IDE,右键单击在终端控制台中打开的项目 选项

3)在Visualcode的窗口控制台上,查找Select-> 默认外壳并将其更改为Gitbash

4)现在您的项目已使用bash控制台和正确的路径打开,放入 源代码./Scripts/activate

顺便说一句:空格=

open the folder with any gitbash console. for example using visualCode and Gitbash console program: 1)Install Gitbash for windows

2) using VisualCode IDE, right click over the project open in terminal console option

3) on window console in Visualcode, looking for a Select->default shell and change it for Gitbash

4)now your project is open with bash console and right path, put source ./Scripts/activate

btw : . with blank space = source


回答 10

提醒一下,但我在Win10 cmd上使用了错误的方式。根据python 文档,activate命令是:C:\> <venv>\Scripts\activate.bat 浏览目录时,例如cd .env/Scripts

因此,创建我使用过的静脉python -m venv --copies .env并激活.env\Scripts\activate.bat

A small reminder, but I had my slashes the wrong way on Win10 cmd. According to python documentation the activate command is: C:\> <venv>\Scripts\activate.bat When you’re browsing directories it’s e.g. cd .env/Scripts

So to create my venv I used python -m venv --copies .env and to activate .env\Scripts\activate.bat


回答 11

source命令正式用于Unix操作系统家族,您基本上不能在Windows上使用它。相反,您可以使用venv\Scripts\activate命令来激活您的虚拟环境。

source command is officially for Unix operating systems family and you can’t use it on windows basically. instead, you can use venv\Scripts\activate command to activate your virtual environment.


回答 12

如果您使用的是Windows,请使用命令“ venv \ Scripts \ activate”(无单词source)激活虚拟环境。如果您使用的是PowerShell,则可能需要大写激活。

If you’re using Windows, use the command “venv\Scripts\activate” (without the word source) to activate the virtual environment. If you’re using PowerShell, you might need to capitalize Activate.


回答 13

如果您使用的是Windows操作系统,则在Gitbash终端中使用以下命令$ source venv / Scripts / activate。这将帮助您进入虚拟环境。

If you are using windows OS then in Gitbash terminal use the following command $source venv/Scripts/activate. This will help you to enter the virtual environment.


回答 14

  1. 使用VS代码编辑器打开项目。
  2. 将vs代码终端中的默认shell更改为git bash。

  3. 现在,您的项目已使用bash控制台打开且路径正确,将“ source venv \ Scripts \ activate”放入Windows

  1. Open your project using VS code editor .
  2. Change the default shell in vs code terminal to git bash.

  3. now your project is open with bash console and right path, put “source venv\Scripts\activate” in Windows


回答 15

导航到您的virtualenv文件夹,例如,..\project1_env> 然后输入

source scripts/activate

例如 ..\project1_env>source scripts/activate

Navigate to your virtualenv folder eg ..\project1_env> Then type

source scripts/activate

eg ..\project1_env>source scripts/activate


回答 16

如果像我这样的初学者遵循了多个Python教程,则现在可能具有多个Python版本和/或pip / virtualenv / pipenv的多个版本…

在这种情况下,列出的答案虽然很正确,但可能无济于事。

我要在您的位置尝试的第一件事是卸载并重新安装Python,然后从那里开始。

If some beginner, like me, has followed multiple Python tutorials now possible has multiple Python versions and/or multiple versions of pip/virtualenv/pipenv…

In that case, answers listed, while many correct, might not help.

The first thing I would try in your place is uninstall and reinstall Python and go from there.


回答 17

在Windows平台上,

您应该将此命令与在安装虚拟环境的位置指定的路径一起使用。

$ .\env\Scripts\activate 

这样,您应该能够在Windows上激活它。

In Windows platform,

you should use this command with path specified where you have installed a virtual environment.

$ .\env\Scripts\activate 

By this, You should be able to activate this on windows.


回答 18

  1. 以管理员身份打开Powershell
  2. 输入“ Set-ExecutionPolicy RemoteSigned -Force
  3. 运行“ gpedit.msc”,然后转到>管理模板> Windows组件> Windows Powershell
  4. 查找“激活脚本执行”并将其设置为“已激活”
  5. 将执行指令设置为“全部允许”
  6. 应用
  7. 刷新您的环境
  1. Open your powershell as admin
  2. Enter “Set-ExecutionPolicy RemoteSigned -Force
  3. Run “gpedit.msc” and go to >Administrative Templates>Windows Components>Windows Powershell
  4. Look for “Activate scripts execution” and set it on “Activated”
  5. Set execution directive to “Allow All”
  6. Apply
  7. Refresh your env

回答 19

如果您在Windows上使用Anaconda / miniconda,请在命令提示符下使用

conda activate <your-environmentname>

例如,peopleanalytics是我的虚拟环境的名称-说

conda activate peopleanalytics

Incase you are using Anaconda / miniconda on windows – in your command prompt use

conda activate <your-environmentname>

e.g. peopleanalytics is name of my virtual environment – Is say

conda activate peopleanalytics

回答 20

如果您仅在Windows 10中已经CD了项目类型

Scripts/activate

这对我行得通:)

if you already cd your project type only in windows 10

Scripts/activate

That works for me:)