标签归档:virtualenv

Cron和virtualenv

问题:Cron和virtualenv

我正在尝试从cron运行Django管理命令。我正在使用virtualenv使我的项目沙盒化。

我在这里和其他地方都看到了一些示例,这些示例显示了从virtualenv内部运行的管理命令,例如:

0 3 * * * source /home/user/project/env/bin/activate && /home/user/project/manage.py command arg

但是,即使syslog在任务应该启动时显示一个条目,该任务也不会实际运行(脚本的日志文件为空)。如果我从外壳程序手动运行该行,它将按预期工作。

目前,我可以使命令通过cron运行的唯一方法是将这些命令分解并放在一个笨拙的bash包装器脚本中:

#!/bin/sh
source /home/user/project/env/bin/activate
cd /home/user/project/
./manage.py command arg

编辑:

ars提出了一种有效的命令组合:

0 3 * * * cd /home/user/project && /home/user/project/env/bin/python /home/user/project/manage.py command arg

至少就我而言,为virtualenv调用激活脚本没有任何作用。这是可行的,因此在演出中如此。

I am trying to run a Django management command from cron. I am using virtualenv to keep my project sandboxed.

I have seen examples here and elsewhere that show running management commands from within virtualenv’s like:

0 3 * * * source /home/user/project/env/bin/activate && /home/user/project/manage.py command arg

However, even though syslog shows an entry when the task should have started, this task never actually runs (the log file for the script is empty). If I run the line manually from the shell, it works as expected.

The only way I can currently get the command to run via cron, is to break the commands up and put them in a dumb bash wrapper script:

#!/bin/sh
source /home/user/project/env/bin/activate
cd /home/user/project/
./manage.py command arg

EDIT:

ars came up with a working combination of commands:

0 3 * * * cd /home/user/project && /home/user/project/env/bin/python /home/user/project/manage.py command arg

At least in my case, invoking the activate script for the virtualenv did nothing. This works, so on with the show.


回答 0

您应该可以通过python在虚拟环境中使用来执行此操作:

/home/my/virtual/bin/python /home/my/project/manage.py command arg

编辑:如果您的django项目不在PYTHONPATH中,那么您需要切换到正确的目录:

cd /home/my/project && /home/my/virtual/bin/python ...

您也可以尝试从cron记录故障:

cd /home/my/project && /home/my/virtual/bin/python /home/my/project/manage.py > /tmp/cronlog.txt 2>&1

另一件事是尝试在manage.py脚本的最顶部进行相同的更改:

#!/home/my/virtual/bin/python

You should be able to do this by using the python in your virtual environment:

/home/my/virtual/bin/python /home/my/project/manage.py command arg

EDIT: If your django project isn’t in the PYTHONPATH, then you’ll need to switch to the right directory:

cd /home/my/project && /home/my/virtual/bin/python ...

You can also try to log the failure from cron:

cd /home/my/project && /home/my/virtual/bin/python /home/my/project/manage.py > /tmp/cronlog.txt 2>&1

Another thing to try is to make the same change in your manage.py script at the very top:

#!/home/my/virtual/bin/python

回答 1

source从cronfile 运行将无法正常运行,因为cron /bin/sh用作其默认外壳程序,该外壳程序不支持source。您需要将SHELL环境变量设置为/bin/bash

SHELL=/bin/bash
*/10 * * * * root source /path/to/virtualenv/bin/activate && /path/to/build/manage.py some_command > /dev/null

很难找到失败原因,因为/var/log/syslog它不会记录错误详细信息。最好将自己别名为root,以便通过电子邮件发送任何cron错误。只需添加自己即可/etc/aliases运行sendmail -bi

此处提供更多信息:http : //codeinthehole.com/archives/43-Running-django-cronjobs-within-a-virtualenv.html

上面的链接已更改为:https : //codeinthehole.com/tips/running-django-cronjobs-within-a-virtualenv/

Running source from a cronfile won’t work as cron uses /bin/sh as its default shell, which doesn’t support source. You need to set the SHELL environment variable to be /bin/bash:

SHELL=/bin/bash
*/10 * * * * root source /path/to/virtualenv/bin/activate && /path/to/build/manage.py some_command > /dev/null

It’s tricky to spot why this fails as /var/log/syslog doesn’t log the error details. Best to alias yourself to root so you get emailed with any cron errors. Simply add yourself to /etc/aliases and run sendmail -bi.

More info here: http://codeinthehole.com/archives/43-Running-django-cronjobs-within-a-virtualenv.html

the link above is changed to: https://codeinthehole.com/tips/running-django-cronjobs-within-a-virtualenv/


回答 2

不要再看了:

0 3 * * * /usr/bin/env bash -c 'cd /home/user/project && source /home/user/project/env/bin/activate && ./manage.py command arg' > /dev/null 2>&1

通用方法:

* * * * * /usr/bin/env bash -c 'YOUR_COMMAND_HERE' > /dev/null 2>&1

这样做的好处是您无需将SHELLcrontab 的变量从更改shbash

Don’t look any further:

0 3 * * * /usr/bin/env bash -c 'cd /home/user/project && source /home/user/project/env/bin/activate && ./manage.py command arg' > /dev/null 2>&1

Generic approach:

* * * * * /usr/bin/env bash -c 'YOUR_COMMAND_HERE' > /dev/null 2>&1

The beauty about this is you DO NOT need to change the SHELL variable for crontab from sh to bash


回答 3

使用virtualenv时,运行python cron作业的唯一正确方法是激活环境,然后执行环境的python来运行代码。

一种方法是activate_this在您的python脚本中使用virtualenv ,请参阅:http : //virtualenv.readthedocs.org/en/latest/userguide.html#using-virtualenv-without-bin-python

另一个解决方案是回显完整的命令,包括激活环境并将其传递到/bin/bash。考虑为您的/etc/crontab

***** root echo 'source /env/bin/activate; python /your/script' | /bin/bash

The only correct way to run python cron jobs when using a virtualenv is to activate the environment and then execute the environment’s python to run your code.

One way to do this is use virtualenv’s activate_this in your python script, see: http://virtualenv.readthedocs.org/en/latest/userguide.html#using-virtualenv-without-bin-python

Another solution is echoing the complete command including activating the environment and piping it into /bin/bash. Consider this for your /etc/crontab:

***** root echo 'source /env/bin/activate; python /your/script' | /bin/bash

回答 4

与其摆弄特定于virtualenv的shebang,不如摆PATH在crontab上。

在激活的virtualenv中,运行以下三个命令,并且python脚本应该可以正常工作:

$ echo "PATH=$PATH" > myserver.cron
$ crontab -l >> myserver.cron
$ crontab myserver.cron

现在,crontab的第一行应如下所示:

PATH=/home/me/virtualenv/bin:/usr/bin:/bin:  # [etc...]

Rather than mucking around with virtualenv-specific shebangs, just prepend PATH onto the crontab.

From an activated virtualenv, run these three commands and python scripts should just work:

$ echo "PATH=$PATH" > myserver.cron
$ crontab -l >> myserver.cron
$ crontab myserver.cron

The crontab’s first line should now look like this:

PATH=/home/me/virtualenv/bin:/usr/bin:/bin:  # [etc...]

回答 5

对我来说最好的解决方案是

  • 使用venv bin /目录中的python二进制文件
  • 设置python路径以包含venv modules目录。

man python提到使用以下命令在shell中$PYTHONPATH或在python 中修改路径sys.path

其他答案提到使用shell进行此操作的想法。在python中,将以下行添加到我的脚本中使我可以直接从cron成功运行它。

import sys
sys.path.insert(0,'/path/to/venv/lib/python3.3/site-packages');

这是交互式会话中的外观-

Python 3.3.2+ (default, Feb 28 2014, 00:52:16) 
[GCC 4.8.1] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> import sys

>>> sys.path
['', '/usr/lib/python3.3', '/usr/lib/python3.3/plat-x86_64-linux-gnu', '/usr/lib/python3.3/lib-dynload']

>>> import requests
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'requests'   

>>> sys.path.insert(0,'/path/to/venv/modules/');

>>> import requests
>>>

The best solution for me was to both

  • use the python binary in the venv bin/ directory
  • set the python path to include the venv modules directory.

man python mentions modifying the path in shell at $PYTHONPATH or in python with sys.path

Other answers mention ideas for doing this using the shell. From python, adding the following lines to my script allows me to successfully run it directly from cron.

import sys
sys.path.insert(0,'/path/to/venv/lib/python3.3/site-packages');

Here’s how it looks in an interactive session —

Python 3.3.2+ (default, Feb 28 2014, 00:52:16) 
[GCC 4.8.1] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> import sys

>>> sys.path
['', '/usr/lib/python3.3', '/usr/lib/python3.3/plat-x86_64-linux-gnu', '/usr/lib/python3.3/lib-dynload']

>>> import requests
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named 'requests'   

>>> sys.path.insert(0,'/path/to/venv/modules/');

>>> import requests
>>>

回答 6

我想添加这个内容是因为我花了一些时间解决问题,但在这里找不到cron和virtualenv中变量使用组合的答案。所以也许会帮助某人。

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DIR_SMTH="cd /smth"
VENV=". venv/bin/activate"
CMD="some_python_bin do_something"
# m h  dom mon dow   command
0 * * * * $DIR_SMTH && $VENV && $CMD -k2 some_target >> /tmp/crontest.log 2>&1

像这样配置时效果不佳

DIR_SMTH =“ cd / smth &&。venv / bin / activate”

感谢@ davidwinterbottom@ reed-sandberg@mkb提供正确的方向。在您的python需要运行一个脚本(该脚本必须从venv / bin目录运行另一个python二进制文件)之前,可接受的答案实际上可以正常工作。

I’d like to add this because I spent some time solving the issue and did not find an answer here for combination of variables usage in cron and virtualenv. So maybe it’ll help someone.

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DIR_SMTH="cd /smth"
VENV=". venv/bin/activate"
CMD="some_python_bin do_something"
# m h  dom mon dow   command
0 * * * * $DIR_SMTH && $VENV && $CMD -k2 some_target >> /tmp/crontest.log 2>&1

It did not work well when it was configured like

DIR_SMTH=”cd /smth && . venv/bin/activate”

Thanks @davidwinterbottom, @reed-sandberg and @mkb for giving the right direction. The accepted answer actually works fine until your python need to run a script which have to run another python binary from venv/bin directory.


回答 7

这是一个对我有效的解决方案。

source /root/miniconda3/etc/profile.d/conda.sh && \
conda activate <your_env> && \
python <your_application> &

我在Ubuntu 18.04.3 LTS上使用带有Conda版本4.7.12的miniconda。

我可以将以上内容放入脚本中,并通过crontab进行运行,而不会遇到任何麻烦。

This is a solution that has worked well for me.

source /root/miniconda3/etc/profile.d/conda.sh && \
conda activate <your_env> && \
python <your_application> &

I am using miniconda with Conda version 4.7.12 on a Ubuntu 18.04.3 LTS.

I am able to place the above inside a script and run it via crontab as well without any trouble.


回答 8

python脚本

from datetime import datetime                                                                                                                                                                
import boto   # check wheather its taking the virtualenv or not                                                                                                                                                                        
import sys                                                                                                                                                                                   
param1=sys.argv[1]     #Param                                                                                                                                                                                                                                                                                                                                                                    
myFile = open('appendtxt.txt', 'a')                                                                                                                                                      
myFile.write('\nAccessed on ' + param1+str(datetime.now())) 

Cron命令

 */1 * * * *  cd /Workspace/testcron/ && /Workspace/testcron/venvcron/bin/python3  /Workspace/testcron/testcronwithparam.py param  

在上面的命令中

  • * / 1 * * * * -每1分钟执行一次
  • cd / Workspace / testcron /-python脚本的路径
  • / Workspace / testcron / venvcron / bin / python3 -Virtualenv路径
  • Workspace / testcron / testcronwithparam.py-文件路径
  • 参数 -参数

python script

from datetime import datetime                                                                                                                                                                
import boto   # check wheather its taking the virtualenv or not                                                                                                                                                                        
import sys                                                                                                                                                                                   
param1=sys.argv[1]     #Param                                                                                                                                                                                                                                                                                                                                                                    
myFile = open('appendtxt.txt', 'a')                                                                                                                                                      
myFile.write('\nAccessed on ' + param1+str(datetime.now())) 

Cron command

 */1 * * * *  cd /Workspace/testcron/ && /Workspace/testcron/venvcron/bin/python3  /Workspace/testcron/testcronwithparam.py param  

In above command

  • */1 * * * * – Execute every one minte
  • cd /Workspace/testcron/ – Path of the python script
  • /Workspace/testcron/venvcron/bin/python3 – Virtualenv path
  • Workspace/testcron/testcronwithparam.py – File path
  • param – parameter

将我的virtualenv目录放在git存储库中是否不好?

问题:将我的virtualenv目录放在git存储库中是否不好?

我正在考虑将virtualenv用于我在git存储库中创建的Django Web应用程序中。这似乎是使部署变得如此简单的一种简单方法。我为什么不应该这样做?

I’m thinking about putting the virtualenv for a Django web app I am making inside my git repository for the app. It seems like an easy way to keep deploy’s simple and easy. Is there any reason why I shouldn’t do this?


回答 0

我通常pip freeze将所需的软件包放入requirements.txt文件中,然后将其添加到存储库中。我试图思考为什么您要存储整个virtualenv的方法,但是我不能。

I use pip freeze to get the packages I need into a requirements.txt file and add that to my repository. I tried to think of a way of why you would want to store the entire virtualenv, but I could not.


回答 1

正如您指出的那样,将virtualenv目录存储在git中将允许您仅通过执行git clone(加上安装和配置Apache / mod_wsgi)来部署整个应用程序。这种方法的一个潜在的重大问题是,在Linux上,完整路径在venv的activate,django-admin.py,easy_install和pip脚本中进行了硬编码。这意味着,如果您想使用不同的路径,也许要在同一台服务器上运行多个虚拟主机,那么您的virtualenv将无法完全正常工作。我认为该网站实际上可能在这些文件中使用了错误的路径,但下一次尝试运行pip时会遇到问题。

已经给出的解决方案是在git中存储足够的信息,以便在部署过程中可以创建virtualenv并进行必要的pip安装。人们通常会跑步pip freeze以获取列表,然后将其存储在名为requirements.txt的文件中。可以加载pip install -r requirements.txt。RyanBrady已经展示了如何在一行中将deploy语句字符串化:

# before 15.1.0
virtualenv --no-site-packages --distribute .env &&\
    source .env/bin/activate &&\
    pip install -r requirements.txt

# after deprecation of some arguments in 15.1.0
virtualenv .env && source .env/bin/activate && pip install -r requirements.txt

就个人而言,我只是将它们放在执行git clone或git pull之后运行的shell脚本中。

存储virtualenv目录还使处理pip升级变得有些棘手,因为您必须手动添加/删除并提交升级后的文件。使用requirements.txt文件,您只需更改requirements.txt中的相应行并重新运行即可pip install -r requirements.txt。如前所述,这还减少了“提交垃圾邮件”。

Storing the virtualenv directory inside git will, as you noted, allow you to deploy the whole app by just doing a git clone (plus installing and configuring Apache/mod_wsgi). One potentially significant issue with this approach is that on Linux the full path gets hard-coded in the venv’s activate, django-admin.py, easy_install, and pip scripts. This means your virtualenv won’t entirely work if you want to use a different path, perhaps to run multiple virtual hosts on the same server. I think the website may actually work with the paths wrong in those files, but you would have problems the next time you tried to run pip.

The solution, already given, is to store enough information in git so that during the deploy you can create the virtualenv and do the necessary pip installs. Typically people run pip freeze to get the list then store it in a file named requirements.txt. It can be loaded with pip install -r requirements.txt. RyanBrady already showed how you can string the deploy statements in a single line:

# before 15.1.0
virtualenv --no-site-packages --distribute .env &&\
    source .env/bin/activate &&\
    pip install -r requirements.txt

# after deprecation of some arguments in 15.1.0
virtualenv .env && source .env/bin/activate && pip install -r requirements.txt

Personally, I just put these in a shell script that I run after doing the git clone or git pull.

Storing the virtualenv directory also makes it a bit trickier to handle pip upgrades, as you’ll have to manually add/remove and commit the files resulting from the upgrade. With a requirements.txt file, you just change the appropriate lines in requirements.txt and re-run pip install -r requirements.txt. As already noted, this also reduces “commit spam”.


回答 2

在开始使用根据环境(例如PyCrypto)进行不同编译的库之前,我一直这样做。我的PyCrypto mac无法在Cygwin上运行,也无法在Ubuntu上运行。

管理存储库已成为一场噩梦。

无论哪种方式,我都发现管理点子冻结和需求文件比将其全部保存在git中更容易。它也更加干净,因为随着这些库的更新,您可以避免提交数千个文件的垃圾邮件…

I used to do the same until I started using libraries that are compiled differently depending on the environment such as PyCrypto. My PyCrypto mac wouldn’t work on Cygwin wouldn’t work on Ubuntu.

It becomes an utter nightmare to manage the repository.

Either way I found it easier to manage the pip freeze & a requirements file than having it all in git. It’s cleaner too since you get to avoid the commit spam for thousands of files as those libraries get updated…


回答 3

我认为出现的主要问题之一是virtualenv可能无法被其他人使用。原因是它始终使用绝对路径。因此,例如,如果您使用virtualenv,/home/lyle/myenv/它将对使用此存储库的所有其他用户都假设相同(其绝对路径必须完全相同)。您不能假定人们使用与您相同的目录结构。

更好的做法是每个人都在建立自己的环境(无论是否带有virtualenv)并在其中安装库。这也使您的代码在不同平台(Linux / Windows / Mac)上的可用性更高,这也是因为在每个平台上都不同地安装了virtualenv。

I think one of the main problems which occur is that the virtualenv might not be usable by other people. Reason is that it always uses absolute paths. So if you virtualenv was for example in /home/lyle/myenv/ it will assume the same for all other people using this repository (it must be exactly the same absolute path). You can’t presume people using the same directory structure as you.

Better practice is that everybody is setting up their own environment (be it with or without virtualenv) and installing libraries there. That also makes you code more usable over different platforms (Linux/Windows/Mac), also because virtualenv is installed different in each of them.


回答 4

我使用的基本上是David Sickmiller的答案,并且自动化程度更高。我在项目的顶层创建一个(不可执行的)文件,其名称activate如下:

[ -n "$BASH_SOURCE" ] \
    || { echo 1>&2 "source (.) this with Bash."; exit 2; }
(
    cd "$(dirname "$BASH_SOURCE")"
    [ -d .build/virtualenv ] || {
        virtualenv .build/virtualenv
        . .build/virtualenv/bin/activate
        pip install -r requirements.txt
    }
)
. "$(dirname "$BASH_SOURCE")/.build/virtualenv/bin/activate"

(根据David的回答,这是假设您正在执行,pip freeze > requirements.txt以使您的需求列表保持最新。)

以上给出了总体思路;实际的激活脚本(文档),我通常使用是有点更复杂,提供了-q(安静)选项,使用pythonpython3不可用等。

然后,可以从任何当前工作目录中获取该资源并将其正确激活,必要时首先设置虚拟环境。我的顶级测试脚本通常包含以下几行代码,因此无需开发人员先激活即可运行它:

cd "$(dirname "$0")"
[[ $VIRTUAL_ENV = $(pwd -P) ]] || . ./activate

这里的Sourcing ./activate(而不是activate)很重要,因为后者会activate在您的路径中找到其他任何路径,然后再在当前目录中找到其他路径。

I use what is basically David Sickmiller’s answer with a little more automation. I create a (non-executable) file at the top level of my project named activate with the following contents:

[ -n "$BASH_SOURCE" ] \
    || { echo 1>&2 "source (.) this with Bash."; exit 2; }
(
    cd "$(dirname "$BASH_SOURCE")"
    [ -d .build/virtualenv ] || {
        virtualenv .build/virtualenv
        . .build/virtualenv/bin/activate
        pip install -r requirements.txt
    }
)
. "$(dirname "$BASH_SOURCE")/.build/virtualenv/bin/activate"

(As per David’s answer, this assumes you’re doing a pip freeze > requirements.txt to keep your list of requirements up to date.)

The above gives the general idea; the actual activate script (documentation) that I normally use is a bit more sophisticated, offering a -q (quiet) option, using python when python3 isn’t available, etc.

This can then be sourced from any current working directory and will properly activate, first setting up the virtual environment if necessary. My top-level test script usually has code along these lines so that it can be run without the developer having to activate first:

cd "$(dirname "$0")"
[[ $VIRTUAL_ENV = $(pwd -P) ]] || . ./activate

Sourcing ./activate, not activate, is important here because the latter will find any other activate in your path before it will find the one in the current directory.


回答 5

在回购协议中包含任何与环境相关的组件或设置作为使用回购协议的关键方面之一不是一个好主意,也许是与其他开发人员共享它。这是在Windows PC(例如Win10)上设置开发环境的方式。

  1. 打开Pycharm,然后在第一页上,选择从您的源代码管理系统中检出项目(在我的情况下,我正在使用github)

  2. 在Pycharm中,导航至设置,然后选择“项目解释器”,然后选择添加新虚拟环境的选项,您可以将其称为“ venv”。

  3. 选择位于C:\ Users {user} \ AppData \ Local \ Programs \ Python \ Python36的基本python解释器(请确保根据安装的内容选择适当的Python版本)

  4. 请注意,Pycharm将创建新的虚拟环境,并在项目文件夹内的venv文件夹下复制python二进制文件和所需的库。

  5. 让Pycharm完成其扫描,因为它需要重建/刷新项目框架

  6. 从git交互中排除venv文件夹(将venv \添加到项目文件夹中的.gitignore文件)

奖励:如果您希望人们轻松(很好,几乎很容易)安装软件所需的所有库,则可以使用

pip freeze > requirements.txt

并将说明放在git上,以便人们可以使用以下命令立即下载所有必需的库。

pip install -r requirements.txt 

It’s not a good idea to include any environment-dependent component or setting in your repos as one of the key aspects of using a repo, is perhaps, sharing it with other developers. Here is how I would setup my development environment on a Windows PC (say, Win10).

  1. Open Pycharm and on the first page, choose to check out the project from your Source Control System (in my case, I am using github)

  2. In Pycharm, navigate to settings and choose “Project Interpreter” and choose the option to add a new virtual environment , you can call it “venv”.

  3. Choose the base python interpreter which is located at C:\Users{user}\AppData\Local\Programs\Python\Python36 (make sure you choose the appropriate version of Python based on what you have installed)

  4. Note that Pycharm will create the new virtual environment and copy python binaries and required libraries under your venv folder inside your project folder.

  5. Let Pycharm complete its scanning as it needs to rebuild/refresh your project skeleton

  6. exclude venv folder from your git interactions (add venv\ to .gitignore file in your project folder)

Bonus: If you want people to easily (well, almost easily) install all the libraries your software needs, you can use

pip freeze > requirements.txt

and put the instruction on your git so people can use the following command to download all required libraries at once.

pip install -r requirements.txt 

回答 6

如果您知道您的应用程序将在哪个操作系统上运行,我将为每个系统创建一个virtualenv并将其包含在我的存储库中。然后,我将让我的应用程序检测它在哪个系统上运行,并使用相应的virtualenv。

该系统可以例如使用平台模块来识别。

实际上,这就是我对自己编写的内部应用程序所做的工作,可以在需要时快速添加新系统的virtualenv。这样,我不必依靠那个点就可以成功下载我的应用程序所需的软件。我也不必担心例如psycopg2的编译我使用。

如果您不知道您的应用程序可以在哪个操作系统上运行,那么最好pip freeze按照此处其他答案中的建议使用。

If you know which operating systems your application will be running on, I would create one virtualenv for each system and include it in my repository. Then I would make my application detect which system it is running on and use the corresponding virtualenv.

The system could e.g. be identified using the platform module.

In fact, this is what I do with an in-house application I have written, and to which I can quickly add a new system’s virtualenv in case it is needed. This way, I do not have to rely on that pip will be able to successfully download the software my application requires. I will also not have to worry about compilation of e.g. psycopg2 which I use.

If you do not know which operating system your application may run on, you are probably better off using pip freeze as suggested in other answers here.


回答 7

我认为最好的办法是在存储库文件夹内的路径中安装虚拟环境,最好使用专用于该环境的子目录(当我在存储库根目录中强制安装虚拟环境时,我意外删除了我的整个项目)文件夹,好是我已将项目保存在最新版本的Github中)。

自动安装程序或文档都应将virtualenv路径指示为相对路径,这样,与他人共享项目时,您就不会遇到问题。关于软件包,使用的软件包应通过保存pip freeze -r requirements.txt

I think is that the best is to install the virtual environment in a path inside the repository folder, maybe is better inclusive to use a subdirectory dedicated to the environment (I have deleted accidentally my entire project when force installing a virtual environment in the repository root folder, good that I had the project saved in its latest version in Github).

Either the automated installer, or the documentation should indicate the virtualenv path as a relative path, this way you won’t run into problems when sharing the project with other people. About the packages, the packages used should be saved by pip freeze -r requirements.txt.


回答 8

如果您只是设置开发环境,请使用pip冻结文件,因为caz可以使git repo变得干净。

然后,如果要进行生产部署,则签入整个venv文件夹。这将使您的部署更具可重复性,不需要那些libxxx-dev软件包,并避免了Internet问题。

因此,有两个存储库。一个用于您的主要源代码,其中包括requirements.txt。还有一个env存储库,其中包含整个venv文件夹。

If you just setting up development env, then use pip freeze file, caz that makes the git repo clean.

Then if doing production deployment, then checkin the whole venv folder. That will make your deployment more reproducible, not need those libxxx-dev packages, and avoid the internet issues.

So there are two repos. One for your main source code, which includes a requirements.txt. And a env repo, which contains the whole venv folder.


确定Python是否在virtualenv中运行

问题:确定Python是否在virtualenv中运行

是否可以确定当前脚本是否在virtualenv环境中运行?

Is it possible to determine if the current script is running inside a virtualenv environment?


回答 0

AFAIK进行检查的最可靠方法(以及在virtualenv和pip内部使用的方法)是检查是否存在sys.real_prefix

import sys

if hasattr(sys, 'real_prefix'):
    #...

在virtualenv内,sys.prefix指向virtualenv目录,并sys.real_prefix指向系统Python的“真实”前缀(通常是/usr/usr/local类似的前缀)。

在virtualenv之外,sys.real_prefix不应该存在。

使用VIRTUAL_ENV环境变量不可靠。它是由virtualenv activateshell脚本设置的,但是可以通过直接从virtualenv bin/(或Scripts)目录运行可执行文件来使用virtualenv而不激活它,在这种情况下$VIRTUAL_ENV将不会设置。

The most reliable way to check for this is to check whether sys.prefix == sys.base_prefix. If they are equal, you are not in a virtual environment; if they are unequal, you are. Inside a virtual environment, sys.prefix points to the virtual environment, and sys.base_prefix is the prefix of the system Python the virtualenv was created from.

The above always works for Python 3 stdlib venv and for recent virtualenv (since version 20). Older versions of virtualenv used sys.real_prefix instead of sys.base_prefix (and sys.real_prefix did not exist outside a virtual environment), and in Python 3.3 and earlier sys.base_prefix did not ever exist. So a fully robust check that handles all of these cases could look like this:

import sys

def get_base_prefix_compat():
    """Get base/real prefix, or sys.prefix if there is none."""
    return getattr(sys, "base_prefix", None) or getattr(sys, "real_prefix", None) or sys.prefix

def in_virtualenv():
    return get_base_prefix_compat() != sys.prefix

If you only care about supported Python versions and latest virtualenv, you can replace get_base_prefix_compat() with simply sys.base_prefix.

Using the VIRTUAL_ENV environment variable is not reliable. It is set by the virtualenv activate shell script, but a virtualenv can be used without activation by directly running an executable from the virtualenv’s bin/ (or Scripts) directory, in which case $VIRTUAL_ENV will not be set. Or a non-virtualenv Python binary can be executed directly while a virtualenv is activated in the shell, in which case $VIRTUAL_ENV may be set in a Python process that is not actually running in that virtualenv.


回答 1

尝试使用pip -V(注意大写V)

如果您正在运行虚拟环境。它会显示到环境位置的路径。

Try using pip -V (notice capital V)

If you are running the virtual env. it’ll show the path to the env.’s location.


回答 2

这是对Carl Meyer接受的答案的改进。它与适用于Python 3和2的virtualenv以及适用于Python 3 的venv模块一起使用:

import sys


def is_venv():
    return (hasattr(sys, 'real_prefix') or
            (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix))

检查是否sys.real_prefix覆盖了virtualenv,非空sys.base_prefix与是否sys.prefix覆盖了venv。

考虑使用如下功能的脚本:

if is_venv():
    print('inside virtualenv or venv')
else:
    print('outside virtualenv or venv')

和以下调用:

$ python2 test.py 
outside virtualenv or venv

$ python3 test.py 
outside virtualenv or venv

$ python2 -m virtualenv virtualenv2
...
$ . virtualenv2/bin/activate
(virtualenv2) $ python test.py 
inside virtualenv or venv
(virtualenv2) $ deactivate

$ python3 -m virtualenv virtualenv3
...
$ . virtualenv3/bin/activate
(virtualenv3) $ python test.py 
inside virtualenv or venv
(virtualenv3) $ deactivate 

$ python3 -m venv venv3
$ . venv3/bin/activate
(venv3) $ python test.py 
inside virtualenv or venv
(venv3) $ deactivate 

This is an improvement of the accepted answer by Carl Meyer. It works with virtualenv for Python 3 and 2 and also for the venv module in Python 3:

import sys


def is_venv():
    return (hasattr(sys, 'real_prefix') or
            (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix))

The check for sys.real_prefix covers virtualenv, the equality of non-empty sys.base_prefix with sys.prefix covers venv.

Consider a script that uses the function like this:

if is_venv():
    print('inside virtualenv or venv')
else:
    print('outside virtualenv or venv')

And the following invocation:

$ python2 test.py 
outside virtualenv or venv

$ python3 test.py 
outside virtualenv or venv

$ python2 -m virtualenv virtualenv2
...
$ . virtualenv2/bin/activate
(virtualenv2) $ python test.py 
inside virtualenv or venv
(virtualenv2) $ deactivate

$ python3 -m virtualenv virtualenv3
...
$ . virtualenv3/bin/activate
(virtualenv3) $ python test.py 
inside virtualenv or venv
(virtualenv3) $ deactivate 

$ python3 -m venv venv3
$ . venv3/bin/activate
(venv3) $ python test.py 
inside virtualenv or venv
(venv3) $ deactivate 

回答 3

检查$VIRTUAL_ENV环境变量。

$VIRTUAL_ENV在活动的虚拟环境中,环境变量包含虚拟环境的目录。

>>> import os
>>> os.environ['VIRTUAL_ENV']
'/some/path/project/venv'

一旦运行deactivate/离开虚拟环境,该$VIRTUAL_ENV变量将被清除/为空。Python将引发一个,KeyError因为未设置环境变量。

>>> import os
>>> os.environ['VIRTUAL_ENV']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py", line 678, in __getitem__
    raise KeyError(key) from None
KeyError: 'VIRTUAL_ENV'

当然,这些相同的环境变量检查也可以在外壳程序中的Python脚本之外进行。

Check the $VIRTUAL_ENV environment variable.

The $VIRTUAL_ENV environment variable contains the virtual environment’s directory when in an active virtual environment.

>>> import os
>>> os.environ['VIRTUAL_ENV']
'/some/path/project/venv'

Once you run deactivate / leave the virtual environment, the $VIRTUAL_ENV variable will be cleared/empty. Python will raise a KeyError because the environment variable was unset.

>>> import os
>>> os.environ['VIRTUAL_ENV']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py", line 678, in __getitem__
    raise KeyError(key) from None
KeyError: 'VIRTUAL_ENV'

These same environment variable checks can of course also be done outside of the Python script, in the shell.


回答 4

根据http://www.python.org/dev/peps/pep-0405/#specification上的virtualenv pep,您可以只使用sys.prefix代替os.environ [‘VIRTUAL_ENV’]。

sys.real_prefix在我的virtualenv中不存在,与sys.base_prefix相同。

According to the virtualenv pep at http://www.python.org/dev/peps/pep-0405/#specification you can just use sys.prefix instead os.environ['VIRTUAL_ENV'].

the sys.real_prefix does not exist in my virtualenv and same with sys.base_prefix.


回答 5

要检查您的Virtualenv内部是否存在:

import os

if os.getenv('VIRTUAL_ENV'):
    print('Using Virtualenv')
else:
    print('Not using Virtualenv')

您还可以获取有关您的环境的更多数据:

import sys
import os

print(f'Python Executable: {sys.executable}')
print(f'Python Version: {sys.version}')
print(f'Virtualenv: {os.getenv("VIRTUAL_ENV")}')

To check whether your inside Virtualenv:

import os

if os.getenv('VIRTUAL_ENV'):
    print('Using Virtualenv')
else:
    print('Not using Virtualenv')

You can also get more data on your environment:

import sys
import os

print(f'Python Executable: {sys.executable}')
print(f'Python Version: {sys.version}')
print(f'Virtualenv: {os.getenv("VIRTUAL_ENV")}')

回答 6

这里有多个好的答案,而有些则不太健壮。这里是概述。

怎么不做

不要依赖Python或site-packages文件夹的位置。

如果将它们设置为非标准位置,则并不意味着您实际上在虚拟环境中。用户可以安装多个Python版本,而这些版本并不总是位于您期望的位置。

避免看:

  • sys.executable
  • sys.prefix
  • pip -V
  • which python

此外,不检查的情况下venv.venv或者envs在任何这些路径。对于位置更独特的环境,这将不起作用。例如, Pipenv使用哈希值作为其环境的名称。

VIRTUAL_ENV 环境变量

两者virtualenvvenv设置环境变量$VIRTUAL_ENV激活一个环境时。参见PEP 405

您可以在shell脚本中读出此变量,或使用此Python代码确定是否已设置。

import os
running_in_virtualenv = "VIRTUAL_ENV" in os.environ

# alternative ways to write this, also supporting the case where
# the variable is set but contains an empty string to indicate
# 'not in a virtual environment':
running_in_virtualenv = bool(os.environ.get("VIRTUAL_ENV"))
running_in_virtualenv = bool(os.getenv("VIRTUAL_ENV"))

问题是,这仅在环境由Shell脚本激活有效activate

您可以在不激活环境的情况下启动环境的脚本,因此,如果这是一个问题,则必须使用其他方法。

sys.base_prefix

virtualenvvenv然后按预期pyvenv指向sys.prefix安装在virtualenv内部的Python。

同时,的原始sys.prefix也可作为获得sys.base_prefix

我们可以使用它来检测我们是否在virtualenv中。

import sys
# note: Python versions before 3.3 don't have sys.base_prefix
# if you're not in virtual environment
running_in_virtualenv = sys.prefix != sys.base_prefix

倒退: sys.real_prefix

现在请注意,virtualenv在未设置版本20之前,而是设置了sys.base_prefixsys.real_prefix

为了安全起见,请按照hroncok的答案中的建议进行检查:

import sys

real_prefix = getattr(sys, "real_prefix", None)
base_prefix = getattr(sys, "base_prefix", sys.prefix)

running_in_virtualenv = (base_prefix or real_prefix) != sys.prefix

水蟒

如果您使用的是Anaconda虚拟环境,请查看 Victoria Stuart的答案

There are multiple good answers here, and some less robust ones. Here’s an overview.

How not to do it

Do not rely on on the location of Python or the site-packages folder.

If these are set to non-standard locations, that does not mean you’re actually in a virtual environment. Users can have more than one Python version installed, and those are not always where you expect them to be.

Avoid looking at:

  • sys.executable
  • sys.prefix
  • pip -V
  • which python

Also, do not check for the presence of venv, .venv or envs in any of these paths. This will break for environments with a more unique location. For example, Pipenv uses hash values as the name for its environments.

VIRTUAL_ENV environment variable

Both virtualenv and venv set the environment variable $VIRTUAL_ENV when activating an environment. See PEP 405.

You can read out this variable in shell scripts, or use this Python code to determine if it’s set.

import os
running_in_virtualenv = "VIRTUAL_ENV" in os.environ

# alternative ways to write this, also supporting the case where
# the variable is set but contains an empty string to indicate
# 'not in a virtual environment':
running_in_virtualenv = bool(os.environ.get("VIRTUAL_ENV"))
running_in_virtualenv = bool(os.getenv("VIRTUAL_ENV"))

The problem is, this only works when the environment is activated by the activate shell script.

You can start the environment’s scripts without activating the environment, so if that is a concern, you have to use a different method.

sys.base_prefix

virtualenv, venv and pyvenv point sys.prefix to the Python installed inside of the virtualenv as you would expect.

At the same time, the original value of sys.prefix is also made available as sys.base_prefix.

We can use that to detect if we’re in a virtualenv.

import sys
# note: Python versions before 3.3 don't have sys.base_prefix
# if you're not in virtual environment
running_in_virtualenv = sys.prefix != sys.base_prefix

Fallback: sys.real_prefix

Now watch out, virtualenv before version 20 did not set sys.base_prefix but it set sys.real_prefix instead.

So to be safe, check both as suggested in hroncok’s answer:

import sys

real_prefix = getattr(sys, "real_prefix", None)
base_prefix = getattr(sys, "base_prefix", sys.prefix)

running_in_virtualenv = (base_prefix or real_prefix) != sys.prefix

Anaconda

If you’re using Anaconda virtual environments, check Victoria Stuart’s answer.


回答 7

您可以which python查看虚拟环境中是否指向该环境。

You can do which python and see if its pointing to the one in virtual env.


回答 8

  • 更新于2019年11月(附加)。

我通常使用几个Anaconda安装的虚拟环境(venv)。此代码片段/示例使您可以确定是否处于venv(或系统环境)中,并且还需要脚本使用特定的venv。

添加到Python脚本(代码段):

# ----------------------------------------------------------------------------
# Want script to run in Python 3.5 (has required installed OpenCV, imutils, ... packages):
import os

# First, see if we are in a conda venv { py27: Python 2.7 | py35: Python 3.5 | tf: TensorFlow | thee : Theano }
try:
   os.environ["CONDA_DEFAULT_ENV"]
except KeyError:
   print("\tPlease set the py35 { p3 | Python 3.5 } environment!\n")
   exit()

# If we are in a conda venv, require the p3 venv:
if os.environ['CONDA_DEFAULT_ENV'] != "py35":
    print("\tPlease set the py35 { p3 | Python 3.5 } environment!\n")
    exit()

# See also:
# Python: Determine if running inside virtualenv
# http://stackoverflow.com/questions/1871549/python-determine-if-running-inside-virtualenv  
# [ ... SNIP! ... ]

例:

$ p2
  [Anaconda Python 2.7 venv (source activate py27)]

(py27) $ python  webcam_.py
    Please set the py35 { p3 | Python 3.5 } environment!

(py27) $ p3
  [Anaconda Python 3.5 venv (source activate py35)]

(py35) $ python  webcam.py -n50

    current env: py35
    processing (live): found 2 faces and 4 eyes in this frame
    threaded OpenCV implementation
    num_frames: 50
    webcam -- approx. FPS: 18.59
    Found 2 faces and 4 eyes!
(py35) $

更新1-在bash脚本中使用:

您也可以在bash脚本中使用这种方法(例如,必须在特定虚拟环境中运行的脚本)。示例(添加到bash脚本中):

if [ $CONDA_DEFAULT_ENV ]        ## << note the spaces (important in BASH)!
    then
        printf 'venv: operating in tf-env, proceed ...'
    else
        printf 'Note: must run this script in tf-env venv'
        exit
fi

更新2 [2019年11月]

自从我的原始文章以来,我已经从Anaconda venv转移了(Python本身已经发展了viz -a- viz 虚拟环境)。

重新检查此问题,以下是一些更新的Python代码,您可以将其插入以测试您是否在特定的Python虚拟环境(venv)中运行。

import os, re
try:
    if re.search('py37', os.environ['VIRTUAL_ENV']):
        pass
except KeyError:
    print("\n\tPlease set the Python3 venv [alias: p3]!\n")
    exit()

这是一些说明性代码。

[victoria@victoria ~]$ date; python --version
  Thu 14 Nov 2019 11:27:02 AM PST
  Python 3.8.0

[victoria@victoria ~]$ python
  Python 3.8.0 (default, Oct 23 2019, 18:51:26) 
  [GCC 9.2.0] on linux
  Type "help", "copyright", "credits" or "license" for more information.

>>> import os, re

>>> re.search('py37', os.environ['VIRTUAL_ENV'])
<re.Match object; span=(20, 24), match='py37'>

>>> try:
...     if re.search('py37', os.environ['VIRTUAL_ENV']):
...       print('\n\tOperating in Python3 venv, please proceed!  :-)')
... except KeyError:
...     print("\n\tPlease set the Python3 venv [alias: p3]!\n")
... 

    Please set the Python3 venv [alias: p3]!

>>> [Ctrl-d]
  now exiting EditableBufferInteractiveConsole...

[victoria@victoria ~]$ p3
  [Python 3.7 venv (source activate py37)]

(py37) [victoria@victoria ~]$ python --version
  Python 3.8.0

(py37) [victoria@victoria ~]$ env | grep -i virtual
  VIRTUAL_ENV=/home/victoria/venv/py37

(py37) [victoria@victoria ~]$ python
  Python 3.8.0 (default, Oct 23 2019, 18:51:26) 
  [GCC 9.2.0] on linux
  Type "help", "copyright", "credits" or "license" for more information.

>>> import os, re
>>> try:
...     if re.search('py37', os.environ['VIRTUAL_ENV']):
...       print('\n\tOperating in Python3 venv, please proceed!  :-)')
... except KeyError:
...     print("\n\tPlease set the Python3 venv [alias: p3]!\n")
... 

    Operating in Python3 venv, please proceed!  :-)
>>> 
  • Updated Nov 2019 (appended).

I routinely use several Anaconda-installed virtual environments (venv). This code snippet/examples enables you to determine whether or not you are in a venv (or your system environment), and to also require a specific venv for your script.

Add to Python script (code snippet):

# ----------------------------------------------------------------------------
# Want script to run in Python 3.5 (has required installed OpenCV, imutils, ... packages):
import os

# First, see if we are in a conda venv { py27: Python 2.7 | py35: Python 3.5 | tf: TensorFlow | thee : Theano }
try:
   os.environ["CONDA_DEFAULT_ENV"]
except KeyError:
   print("\tPlease set the py35 { p3 | Python 3.5 } environment!\n")
   exit()

# If we are in a conda venv, require the p3 venv:
if os.environ['CONDA_DEFAULT_ENV'] != "py35":
    print("\tPlease set the py35 { p3 | Python 3.5 } environment!\n")
    exit()

# See also:
# Python: Determine if running inside virtualenv
# http://stackoverflow.com/questions/1871549/python-determine-if-running-inside-virtualenv  
# [ ... SNIP! ... ]

Example:

$ p2
  [Anaconda Python 2.7 venv (source activate py27)]

(py27) $ python  webcam_.py
    Please set the py35 { p3 | Python 3.5 } environment!

(py27) $ p3
  [Anaconda Python 3.5 venv (source activate py35)]

(py35) $ python  webcam.py -n50

    current env: py35
    processing (live): found 2 faces and 4 eyes in this frame
    threaded OpenCV implementation
    num_frames: 50
    webcam -- approx. FPS: 18.59
    Found 2 faces and 4 eyes!
(py35) $

Update 1 — use in bash scripts:

You can also use this approach in bash scripts (e.g., those that must run in a specific virtual environment). Example (added to bash script):

if [ $CONDA_DEFAULT_ENV ]        ## << note the spaces (important in BASH)!
    then
        printf 'venv: operating in tf-env, proceed ...'
    else
        printf 'Note: must run this script in tf-env venv'
        exit
fi

Update 2 [Nov 2019]

Since my original post I’ve moved on from Anaconda venv (and Python itself has evolved viz-a-viz virtual environments).

Reexamining this issue, here is some updated Python code that you can insert to test that you are operating in a specific Python virtual environment (venv).

import os, re
try:
    if re.search('py37', os.environ['VIRTUAL_ENV']):
        pass
except KeyError:
    print("\n\tPlease set the Python3 venv [alias: p3]!\n")
    exit()

Here is some explanatory code.

[victoria@victoria ~]$ date; python --version
  Thu 14 Nov 2019 11:27:02 AM PST
  Python 3.8.0

[victoria@victoria ~]$ python
  Python 3.8.0 (default, Oct 23 2019, 18:51:26) 
  [GCC 9.2.0] on linux
  Type "help", "copyright", "credits" or "license" for more information.

>>> import os, re

>>> re.search('py37', os.environ['VIRTUAL_ENV'])
<re.Match object; span=(20, 24), match='py37'>

>>> try:
...     if re.search('py37', os.environ['VIRTUAL_ENV']):
...       print('\n\tOperating in Python3 venv, please proceed!  :-)')
... except KeyError:
...     print("\n\tPlease set the Python3 venv [alias: p3]!\n")
... 

    Please set the Python3 venv [alias: p3]!

>>> [Ctrl-d]
  now exiting EditableBufferInteractiveConsole...

[victoria@victoria ~]$ p3
  [Python 3.7 venv (source activate py37)]

(py37) [victoria@victoria ~]$ python --version
  Python 3.8.0

(py37) [victoria@victoria ~]$ env | grep -i virtual
  VIRTUAL_ENV=/home/victoria/venv/py37

(py37) [victoria@victoria ~]$ python
  Python 3.8.0 (default, Oct 23 2019, 18:51:26) 
  [GCC 9.2.0] on linux
  Type "help", "copyright", "credits" or "license" for more information.

>>> import os, re
>>> try:
...     if re.search('py37', os.environ['VIRTUAL_ENV']):
...       print('\n\tOperating in Python3 venv, please proceed!  :-)')
... except KeyError:
...     print("\n\tPlease set the Python3 venv [alias: p3]!\n")
... 

    Operating in Python3 venv, please proceed!  :-)
>>> 

回答 9

最简单的方法是运行:which python,如果您位于virtualenv中,它将指向其python而不是全局的python

Easiest way is to just run: which python, if you are in a virtualenv it will point to its python instead of the global one


回答 10

(编辑)我发现那条路,您怎么看?(它还会返回venv基本路径,甚至可以在不检查env变量的readthedocs中使用):

import os
import sys
from distutils.sysconfig import get_config_vars


def get_venv_basedir():
    """Returns the base directory of the virtualenv, useful to read configuration and plugins"""

    exec_prefix = get_config_vars()['exec_prefix']

    if hasattr(sys, 'real_prefix') is False or exec_prefix.startswith(sys.real_prefix):
        raise EnvironmentError('You must be in a virtual environment')

    return os.path.abspath(get_config_vars()['exec_prefix'] + '/../')

(edited) I found that way, what do you think of it ? (it also returns the venv base path and works even for readthedocs where checking the env variable does not):

import os
import sys
from distutils.sysconfig import get_config_vars


def get_venv_basedir():
    """Returns the base directory of the virtualenv, useful to read configuration and plugins"""

    exec_prefix = get_config_vars()['exec_prefix']

    if hasattr(sys, 'real_prefix') is False or exec_prefix.startswith(sys.real_prefix):
        raise EnvironmentError('You must be in a virtual environment')

    return os.path.abspath(get_config_vars()['exec_prefix'] + '/../')

回答 11

已经在这里发布了很多很棒的方法,但是只添加了一个:

import site
site.getsitepackages()

告诉您pip软件包的安装位置。

There are a lot of great methods posted here already, but just adding one more:

import site
site.getsitepackages()

tells you where pip installed the packages.


回答 12

它不是防弹的,但对于UNIX环境,简单的测试如

if run("which python3").find("venv") == -1:
    # something when not executed from venv

对我来说很棒。然后,它比测试某些属性的存在更简单,无论如何,您应该命名venv目录venv

It’s not bullet-proof but for UNIX environments simple test like

if run("which python3").find("venv") == -1:
    # something when not executed from venv

works great for me. It’s simpler then testing existing of some attribute and, anyway, you should name your venv directory venv.


回答 13

在Windows操作系统中,您会看到以下内容:

C:\Users\yourusername\virtualEnvName\Scripts>activate
(virtualEnvName) C:\Users\yourusername\virtualEnvName\Scripts>

括号表示您实际上位于称为“ virtualEnvName”的虚拟环境中。

In windows OS you see something like this:

C:\Users\yourusername\virtualEnvName\Scripts>activate
(virtualEnvName) C:\Users\yourusername\virtualEnvName\Scripts>

Parentheses mean that you are actually in the virtual environment called “virtualEnvName”.


回答 14

一个可能的解决方案是:

os.access(sys.executable, os.W_OK)

就我而言,我真的只是想检测是否可以按原样安装pip物品。尽管这可能不是适用于所有情况的正确解决方案,但请考虑简单地检查一下是否对Python可执行文件的位置具有写权限。

注意:这适用于所有版本的Python,但True如果您使用来运行系统Python,也将返回sudo。这是一个潜在的用例:

import os, sys
can_install_pip_packages = os.access(sys.executable, os.W_OK)

if can_install_pip_packages:
    import pip
    pip.main(['install', 'mypackage'])

A potential solution is:

os.access(sys.executable, os.W_OK)

In my case I really just wanted to detect if I could install items with pip as is. While it might not be the right solution for all cases, consider simply checking if you have write permissions for the location of the Python executable.

Note: this works in all versions of Python, but also returns True if you run the system Python with sudo. Here’s a potential use case:

import os, sys
can_install_pip_packages = os.access(sys.executable, os.W_OK)

if can_install_pip_packages:
    import pip
    pip.main(['install', 'mypackage'])

回答 15

这是一个古老的问题,但是上面的例子太多了。

保持简单:(在Windows 10的Jupyter Notebook或Python 3.7.1终端中)


import sys
print(sys.executable)```

# example output: >> `C:\Anaconda3\envs\quantecon\python.exe`

OR 
```sys.base_prefix```

# Example output: >> 'C:\\Anaconda3\\envs\\quantecon'

This is an old question, but too many examples above are over-complicated.

Keep It Simple: (in Jupyter Notebook or Python 3.7.1 terminal on Windows 10)


import sys
print(sys.executable)```

# example output: >> `C:\Anaconda3\envs\quantecon\python.exe`

OR 
```sys.base_prefix```

# Example output: >> 'C:\\Anaconda3\\envs\\quantecon'

如何在OSX 10.6中将MySQLdb与Python和Django一起使用?

问题:如何在OSX 10.6中将MySQLdb与Python和Django一起使用?

对于OSX 10.6用户,这是一个讨论很多的问题,但是我一直找不到能够解决问题的解决方案。这是我的设置:

Python 2.6.1 64位Django 1.2.1 MySQL 5.1.47 osx10.6 64位

我使用–no-site-packages创建了一个virtualenvwrapper,然后安装了Django。当我激活virtualenv并运行python manage.py syncdb时,出现以下错误:

Traceback (most recent call last):
File "manage.py", line 11, in <module>
  execute_manager(settings)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 438, in execute_manager
  utility.execute()
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 379, in execute
  self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 257, in fetch_command
  klass = load_command_class(app_name, subcommand)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 67, in load_command_class
  module = import_module('%s.management.commands.%s' % (app_name, name))
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
  __import__(name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/commands/syncdb.py", line 7, in <module>
from django.core.management.sql import custom_sql_for_model, emit_post_sync_signal
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/sql.py", line 5, in <module>
from django.contrib.contenttypes import generic
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/contrib/contenttypes/generic.py", line 6, in <module>
  from django.db import connection
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/__init__.py", line 75, in <module>
  connection = connections[DEFAULT_DB_ALIAS]
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/utils.py", line 91, in __getitem__
  backend = load_backend(db['ENGINE'])
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/utils.py", line 32, in load_backend
  return import_module('.base', backend_name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
  __import__(name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/backends/mysql/base.py", line 14, in <module>
  raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

我还安装了MySQL for Python适配器,但无济于事(也许我安装不正确?)。

有人处理过吗?

This is a much discussed issue for OSX 10.6 users, but I haven’t been able to find a solution that works. Here’s my setup:

Python 2.6.1 64bit Django 1.2.1 MySQL 5.1.47 osx10.6 64bit

I create a virtualenvwrapper with –no-site-packages, then installed Django. When I activate the virtualenv and run python manage.py syncdb, I get this error:

Traceback (most recent call last):
File "manage.py", line 11, in <module>
  execute_manager(settings)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 438, in execute_manager
  utility.execute()
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 379, in execute
  self.fetch_command(subcommand).run_from_argv(self.argv)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 257, in fetch_command
  klass = load_command_class(app_name, subcommand)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/__init__.py", line 67, in load_command_class
  module = import_module('%s.management.commands.%s' % (app_name, name))
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
  __import__(name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/commands/syncdb.py", line 7, in <module>
from django.core.management.sql import custom_sql_for_model, emit_post_sync_signal
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/core/management/sql.py", line 5, in <module>
from django.contrib.contenttypes import generic
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/contrib/contenttypes/generic.py", line 6, in <module>
  from django.db import connection
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/__init__.py", line 75, in <module>
  connection = connections[DEFAULT_DB_ALIAS]
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/utils.py", line 91, in __getitem__
  backend = load_backend(db['ENGINE'])
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/utils.py", line 32, in load_backend
  return import_module('.base', backend_name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/utils/importlib.py", line 35, in import_module
  __import__(name)
File "/Users/joerobinson/.virtualenvs/dj_tut/lib/python2.6/site-packages/django/db/backends/mysql/base.py", line 14, in <module>
  raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

I’ve also installed the MySQL for Python adapter, but to no avail (maybe I installed it improperly?).

Anyone dealt with this before?


回答 0

我有同样的错误,pip install MySQL-python并为我解决了。

备用安装:

  • 如果您没有点子,easy_install MySQL-python应该可以。
  • 如果您的python是由打包系统管理的,则可能必须使用该系统(例如sudo apt-get install ...

下面,Soli指出如果收到以下错误:

EnvironmentError: mysql_config not found

…然后您还有另一个系统依赖性问题。解决方案因系统而异,但对于Debian衍生的系统:

sudo apt-get install python-mysqldb

I had the same error and pip install MySQL-python solved it for me.

Alternate installs:

  • If you don’t have pip, easy_install MySQL-python should work.
  • If your python is managed by a packaging system, you might have to use that system (e.g. sudo apt-get install ...)

Below, Soli notes that if you receive the following error:

EnvironmentError: mysql_config not found

… then you have a further system dependency issue. Solving this will vary from system to system, but for Debian-derived systems:

sudo apt-get install python-mysqldb


回答 1

运行Ubuntu,我必须做:

sudo apt-get install python-mysqldb

Running Ubuntu, I had to do:

sudo apt-get install python-mysqldb

回答 2

除了其他答案,以下内容还帮助我完成了mysql-python的安装:

virtualenv,mysql-python,pip:有人知道吗?

在Ubuntu上…

apt-get install libmysqlclient-dev
apt-get install python-dev
pip install mysql-python

如果您没有适当的权限,请不要忘记在命令开头添加“ sudo”。

Adding to other answers, the following helped me finish the installation mysql-python:

virtualenv, mysql-python, pip: anyone know how?

On Ubuntu…

apt-get install libmysqlclient-dev
apt-get install python-dev
pip install mysql-python

Don’t forget to add ‘sudo’ to the beginning of commands if you don’t have the proper permissions.


回答 3

试试下面的命令。他们为我工作:

brew install mysql-connector-c 
pip install MySQL-python

Try this the commands below. They work for me:

brew install mysql-connector-c 
pip install MySQL-python

回答 4

mysql_config必须在路上。在Mac上,执行

export PATH=$PATH:/usr/local/mysql/bin/
pip install MySQL-python

mysql_config must be on the path. On Mac, do

export PATH=$PATH:/usr/local/mysql/bin/
pip install MySQL-python

回答 5

pip install mysql-python

提出了一个错误:

EnvironmentError:找不到mysql_config

sudo apt-get install python-mysqldb

解决了问题。

pip install mysql-python

raised an error:

EnvironmentError: mysql_config not found

sudo apt-get install python-mysqldb

fixed the problem.


回答 6

我如何工作的:

virtualenv -p python3.5 env/test

在采购我的环境后:

pip install pymysql
pip install django

然后,我运行了startproject并在manage.py中添加了以下内容:

+ try:
+     import pymysql
+     pymysql.install_as_MySQLdb()
+ except:
+     pass

此外,还更新了此内部设置:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'foobar_db',
        'USER': 'foobaruser',
        'PASSWORD': 'foobarpwd',
    }
}

我也已经configparser==3.5.0在我的virtualenv中安装了,不确定是否需要…

希望能帮助到你,

How I got it working:

virtualenv -p python3.5 env/test

After sourcing my env:

pip install pymysql
pip install django

Then, I ran the startproject and inside the manage.py, I added this:

+ try:
+     import pymysql
+     pymysql.install_as_MySQLdb()
+ except:
+     pass

Also, updated this inside settings:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'foobar_db',
        'USER': 'foobaruser',
        'PASSWORD': 'foobarpwd',
    }
}

I also have configparser==3.5.0 installed in my virtualenv, not sure if that was required or not…

Hope it helps,


回答 7

以下对我来说运行64位Ubuntu 13.10的完美工作:

sudo apt-get install libmysqlclient-dev
sudo apt-get install python-dev

现在,导航到您的virtualenv(例如env文件夹)并执行以下操作:

sudo ./bin/pip install mysql-python

实际上,我在另一个问题中找到了解决方案,并在下面引用了它:

如果使用–no-site-packages开关(默认设置)创建了virtualenv,则虚拟环境软件包中不包括系统范围内已安装的附加内容,例如MySQLdb。

您需要使用随virtualenv一起安装的pip命令安装MySQLdb。使用bin / activate脚本激活virtualenv,或者在virtualenv中使用bin / pip在本地安装MySQLdb库。

或者,使用–system-site-package开关创建包含系统站点包的新virtualenv。

我认为这也适用于OSX。唯一的问题是获得等效的安装命令libmysqlclient-devpython-dev因为mysql-python我猜它们是编译所必需的 。

希望这可以帮助。

The following worked perfectly for me, running Ubuntu 13.10 64-bit:

sudo apt-get install libmysqlclient-dev
sudo apt-get install python-dev

Now, navigate to your virtualenv (such as env folder) and execute the following:

sudo ./bin/pip install mysql-python

I actually found the solution in a separate question and I am quoting it below:

If you have created the virtualenv with the –no-site-packages switch (the default), then system-wide installed additions such as MySQLdb are not included in the virtual environment packages.

You need to install MySQLdb with the pip command installed with the virtualenv. Either activate the virtualenv with the bin/activate script, or use bin/pip from within the virtualenv to install the MySQLdb library locally as well.

Alternatively, create a new virtualenv with system site-packages included by using the –system-site-package switch.

I think this should also work with OSX. The only problem would be getting an equivalent command for installing libmysqlclient-dev and python-dev as they are needed to compile mysql-python I guess.

Hope this helps.


回答 8

试试这个:这为我解决了这个问题。

pip安装MySQL-python

Try this: This solved the issue for me .

pip install MySQL-python


回答 9

此问题是由于MySQL for Python适配器安装不完整/错误导致的。具体来说,我必须编辑mysql_config文件的路径以指向/ usr / local / mysql / bin / mysql_config-在本文中进行了详细讨论:http : //dakrauth.com/blog/entry/python-and- django-setup-mac-os-x-豹/

This issue was the result of an incomplete / incorrect installation of the MySQL for Python adapter. Specifically, I had to edit the path to the mysql_config file to point to /usr/local/mysql/bin/mysql_config – discussed in greater detail in this article: http://dakrauth.com/blog/entry/python-and-django-setup-mac-os-x-leopard/


回答 10

sudo apt-get install python-mysqldb 在ubuntu中完美工作

pip install mysql-python引发环境错误

sudo apt-get install python-mysqldb works perfectly in ubuntu

pip install mysql-python raises an Environment Error


回答 11

这适用于Red Hat Enterprise Linux Server 6.4版

sudo yum install mysql-devel
sudo yum install python-devel
pip install mysql-python

This worked for Red Hat Enterprise Linux Server release 6.4

sudo yum install mysql-devel
sudo yum install python-devel
pip install mysql-python

回答 12

您可以安装为 pip install mysqlclient

You can install as pip install mysqlclient


回答 13

我进行了OSX Mavericks和Pycharm 3的升级,并开始出现此错误,我使用了pip并易于安装,并得到了以下错误:

命令’/ usr / bin / clang’失败,退出状态为1。

所以我需要更新到Xcode 5,然后再次尝试使用pip进行安装。

pip install mysql-python

那解决了所有问题。

I made the upgrade to OSX Mavericks and Pycharm 3 and start to get this error, i used pip and easy install and got the error:

command’/usr/bin/clang’ failed with exit status 1.

So i need to update to Xcode 5 and tried again to install using pip.

pip install mysql-python

That fix all the problems.


回答 14

此处引发的错误是在导入python模块中。可以通过将python site-packages文件夹添加到OS X上的环境变量$ PYTHONPATH来解决。因此,我们可以将以下命令添加到.bash_profile文件中:

export PYTHONPATH="$PYTHONPATH:/usr/local/lib/pythonx.x/site-packages/"

*用您正在使用的python版本替换xx

The error raised here is in importing the python module. This can be solved by adding the python site-packages folder to the environment variable $PYTHONPATH on OS X. So we can add the following command to the .bash_profile file:

export PYTHONPATH="$PYTHONPATH:/usr/local/lib/pythonx.x/site-packages/"

*replace x.x with the python version you are using


回答 15

如果您使用的是python3,请尝试以下操作(我的操作系统是Ubuntu 16.04):

sudo apt-get install python3-mysqldb

If you are using python3, then try this(My OS is Ubuntu 16.04):

sudo apt-get install python3-mysqldb

回答 16

pip在Windows 8 64位系统上对我不起作用。 easy_install mysql-python为我工作。easy_install如果pip不起作用,您可以用来避免在Windows上生成二进制文件。

pip did not work for me on windows 8 64 bits system. easy_install mysql-python works for me. You can use easy_install to avoid building binaries on windows if pip does not work.


回答 17

我在OSX 10.6.6上遇到了相同的问题。但是,只是一个简单easy_install mysql-python的终端无法解决它,因为随之而来的另一个麻烦是:

error: command 'gcc-4.2' failed with exit status 1

显然,从XCode3(OSX 10.6附带提供)升级到XCode4后,就会出现此问题。此较新版本删除了对构建ppc拱的支持。如果相同,请尝试以下操作easy_install mysql-python

sudo bash
export ARCHFLAGS='-arch i386 -arch x86_64'
rm -r build
python setup.py build
python setup.py install

非常感谢Ned Deily的解决方案。在这里检查

I had the same problem on OSX 10.6.6. But just a simple easy_install mysql-python on terminal did not solve it as another hiccup followed:

error: command 'gcc-4.2' failed with exit status 1.

Apparently, this issue arises after upgrading from XCode3 (which is natively shipped with OSX 10.6) to XCode4. This newer ver removes support for building ppc arch. If its the same case, try doing as follows before easy_install mysql-python

sudo bash
export ARCHFLAGS='-arch i386 -arch x86_64'
rm -r build
python setup.py build
python setup.py install

Many thanks to Ned Deily for this solution. Check here


回答 18

对我来说,只需重新安装mysql-python即可解决问题

pip uninstall mysql-python
pip install mysql-python

For me the problem got solved by simply reinstalling mysql-python

pip uninstall mysql-python
pip install mysql-python

回答 19

安装命令行工具对我有用:

xcode-select --install

Install Command Line Tools Works for me:

xcode-select --install

回答 20

我通过MySQL-python使用pip安装库克服了相同的问题。当我第一次在settings.py中更改数据库设置并执行makemigrations命令时,可以看到控制台上显示的消息(解决方案遵循以下消息,请看一下)。

  (vir_env) admins-MacBook-Pro-3:src admin$ python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
    django.setup()
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/contrib/auth/models.py", line 41, in <module>
    class Permission(models.Model):
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/base.py", line 139, in __new__
    new_class.add_to_class('_meta', Options(meta, **kwargs))
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/base.py", line 324, in add_to_class
    value.contribute_to_class(cls, name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/options.py", line 250, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/__init__.py", line 36, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/utils.py", line 240, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/utils.py", line 111, in load_backend
    return import_module('%s.base' % backend_name)
  File "/usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 27, in <module>
    raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

最后,我克服了以下问题:

(vir_env) admins-MacBook-Pro-3:src admin$ pip install MySQLdb
Collecting MySQLdb
  Could not find a version that satisfies the requirement MySQLdb (from versions: )
No matching distribution found for MySQLdb
(vir_env) admins-MacBook-Pro-3:src admin$ pip install MySQL-python
Collecting MySQL-python
  Downloading MySQL-python-1.2.5.zip (108kB)
    100% |████████████████████████████████| 112kB 364kB/s 
Building wheels for collected packages: MySQL-python
  Running setup.py bdist_wheel for MySQL-python ... done
  Stored in directory: /Users/admin/Library/Caches/pip/wheels/38/a3/89/ec87e092cfb38450fc91a62562055231deb0049a029054dc62
Successfully built MySQL-python
Installing collected packages: MySQL-python
Successfully installed MySQL-python-1.2.5
(vir_env) admins-MacBook-Pro-3:src admin$ python manage.py makemigrations
No changes detected
(vir_env) admins-MacBook-Pro-3:src admin$ python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, rest_framework, messages, crispy_forms
  Apply all migrations: admin, contenttypes, sessions, auth, PyApp
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying PyApp.0001_initial... OK
  Applying PyApp.0002_auto_20170310_0936... OK
  Applying PyApp.0003_auto_20170310_0953... OK
  Applying PyApp.0004_auto_20170310_0954... OK
  Applying PyApp.0005_auto_20170311_0619... OK
  Applying PyApp.0006_auto_20170311_0622... OK
  Applying PyApp.0007_loraevksensor... OK
  Applying PyApp.0008_auto_20170315_0752... OK
  Applying PyApp.0009_auto_20170315_0753... OK
  Applying PyApp.0010_auto_20170315_0806... OK
  Applying PyApp.0011_auto_20170315_0814... OK
  Applying PyApp.0012_auto_20170315_0820... OK
  Applying PyApp.0013_auto_20170315_0822... OK
  Applying PyApp.0014_auto_20170315_0907... OK
  Applying PyApp.0015_auto_20170315_1041... OK
  Applying PyApp.0016_auto_20170315_1355... OK
  Applying PyApp.0017_auto_20170315_1401... OK
  Applying PyApp.0018_auto_20170331_1348... OK
  Applying PyApp.0019_auto_20170331_1349... OK
  Applying PyApp.0020_auto_20170331_1350... OK
  Applying PyApp.0021_auto_20170331_1458... OK
  Applying PyApp.0022_delete_postoffice... OK
  Applying PyApp.0023_posoffice... OK
  Applying PyApp.0024_auto_20170331_1504... OK
  Applying PyApp.0025_auto_20170331_1511... OK
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying sessions.0001_initial... OK
(vir_env) admins-MacBook-Pro-3:src admin$ 

I overcame the same problem by installing MySQL-python library using pip. You can see the message displayed on my console when I first changed my database settings in settings.py and executed makemigrations command(The solution is following the below message, just see that).

  (vir_env) admins-MacBook-Pro-3:src admin$ python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/core/management/__init__.py", line 312, in execute
    django.setup()
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/apps/config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "/usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/contrib/auth/models.py", line 41, in <module>
    class Permission(models.Model):
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/base.py", line 139, in __new__
    new_class.add_to_class('_meta', Options(meta, **kwargs))
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/base.py", line 324, in add_to_class
    value.contribute_to_class(cls, name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/models/options.py", line 250, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/__init__.py", line 36, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/utils.py", line 240, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/utils.py", line 111, in load_backend
    return import_module('%s.base' % backend_name)
  File "/usr/local/Cellar/python/2.7.12_1/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/admin/Desktop/SetUp1/vir_env/lib/python2.7/site-packages/django/db/backends/mysql/base.py", line 27, in <module>
    raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

Finally I overcame this problem as follows:

(vir_env) admins-MacBook-Pro-3:src admin$ pip install MySQLdb
Collecting MySQLdb
  Could not find a version that satisfies the requirement MySQLdb (from versions: )
No matching distribution found for MySQLdb
(vir_env) admins-MacBook-Pro-3:src admin$ pip install MySQL-python
Collecting MySQL-python
  Downloading MySQL-python-1.2.5.zip (108kB)
    100% |████████████████████████████████| 112kB 364kB/s 
Building wheels for collected packages: MySQL-python
  Running setup.py bdist_wheel for MySQL-python ... done
  Stored in directory: /Users/admin/Library/Caches/pip/wheels/38/a3/89/ec87e092cfb38450fc91a62562055231deb0049a029054dc62
Successfully built MySQL-python
Installing collected packages: MySQL-python
Successfully installed MySQL-python-1.2.5
(vir_env) admins-MacBook-Pro-3:src admin$ python manage.py makemigrations
No changes detected
(vir_env) admins-MacBook-Pro-3:src admin$ python manage.py migrate
Operations to perform:
  Synchronize unmigrated apps: staticfiles, rest_framework, messages, crispy_forms
  Apply all migrations: admin, contenttypes, sessions, auth, PyApp
Synchronizing apps without migrations:
  Creating tables...
    Running deferred SQL...
  Installing custom SQL...
Running migrations:
  Rendering model states... DONE
  Applying PyApp.0001_initial... OK
  Applying PyApp.0002_auto_20170310_0936... OK
  Applying PyApp.0003_auto_20170310_0953... OK
  Applying PyApp.0004_auto_20170310_0954... OK
  Applying PyApp.0005_auto_20170311_0619... OK
  Applying PyApp.0006_auto_20170311_0622... OK
  Applying PyApp.0007_loraevksensor... OK
  Applying PyApp.0008_auto_20170315_0752... OK
  Applying PyApp.0009_auto_20170315_0753... OK
  Applying PyApp.0010_auto_20170315_0806... OK
  Applying PyApp.0011_auto_20170315_0814... OK
  Applying PyApp.0012_auto_20170315_0820... OK
  Applying PyApp.0013_auto_20170315_0822... OK
  Applying PyApp.0014_auto_20170315_0907... OK
  Applying PyApp.0015_auto_20170315_1041... OK
  Applying PyApp.0016_auto_20170315_1355... OK
  Applying PyApp.0017_auto_20170315_1401... OK
  Applying PyApp.0018_auto_20170331_1348... OK
  Applying PyApp.0019_auto_20170331_1349... OK
  Applying PyApp.0020_auto_20170331_1350... OK
  Applying PyApp.0021_auto_20170331_1458... OK
  Applying PyApp.0022_delete_postoffice... OK
  Applying PyApp.0023_posoffice... OK
  Applying PyApp.0024_auto_20170331_1504... OK
  Applying PyApp.0025_auto_20170331_1511... OK
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying sessions.0001_initial... OK
(vir_env) admins-MacBook-Pro-3:src admin$ 

回答 21

运行此命令

sudo pip install mysql-python;

现在您可以运行命令了。

python manage.py startapp filename;

Run this command

sudo pip install mysql-python;

now you can run your command.

python manage.py startapp filename;

回答 22

我遇到了类似的情况,例如您在Mac OS X上的virtualenv中使用python3.7和django 2.1。尝试运行命令:

pip install mysql-python
pip install pymysql

__init__.py在您的项目文件夹中编辑文件,并添加以下内容:

import pymysql

pymysql.install_as_MySQLdb()

然后运行:python3 manage.py runserverpython manage.py runserver

I encountered similar situations like yours that I am using python3.7 and django 2.1 in virtualenv on mac osx. Try to run command:

pip install mysql-python
pip install pymysql

And edit __init__.py file in your project folder and add following:

import pymysql

pymysql.install_as_MySQLdb()

Then run: python3 manage.py runserver or python manage.py runserver


全面的初学者的virtualenv教程?[关闭]

问题:全面的初学者的virtualenv教程?[关闭]

我最近一直在听到有关virtualenv的嗡嗡声,我对此很感兴趣。但是我所听到的只是一点点赞美,而对它的含义或用法却不甚了解。

我正在寻找(理想情况下)后续教程,该教程可以使我从没有Python的Windows或Linux中学习,并解释其每个步骤(无特定顺序):

  • 我应该怎么做才能开始使用 virtualenv
  • 使用virtualenv一个好主意的具体原因
  • 我不能/不能使用的情况 virtualenv
  • 我不应该使用的情况 virtualenv

并逐步(全面)介绍应有可能的几种示例情况。

那么,有什么好的教程可以涵盖这些内容?或者,如果您有时间和兴趣,也许您可​​以在这里回答其中一些问题。在您的答案中,或作为指向答案的教程的链接,这些都是我想知道的。

I’ve been hearing the buzz about virtualenv lately, and I’m interested. But all I’ve heard is a smattering of praise, and don’t have a clear understanding of what it is or how to use it.

I’m looking for (ideally) a follow-along tutorial that can take me from Windows or Linux with no Python on it, and explain every step of (in no particular order):

  • what I should do to be able to start using virtualenv
  • specific reasons why using virtualenv is a good idea
  • situations where I can/can’t use virtualenv
  • situations where I should/shouldn’t use virtualenv

And step through (comprehensively) a couple sample situations of the should+can variety.

So what are some good tutorials to cover this stuff? Or if you have the time and interest, perhaps you can answer a few of those questions here. Either in your answer, or as a link to tutorials that answer it, these are the things I’d like to know.


回答 0


回答 1

Virtualenv是用于创建隔离的 Python环境的工具。

假设您在两个不同的项目A和B中工作。项目A是一个Web项目,团队正在使用以下软件包:

  • Python 2.8.x
  • Django 1.6.x

项目B也是一个Web项目,但是您的团队正在使用:

  • Python 2.7.x
  • Django 1.4.x

您正在使用的机器没有django的任何版本,该怎么办?安装django 1.4?Django 1.6?如果在全局安装django 1.4,很容易将django 1.6指向在项目A中工作?

Virtualenv是您的解决方案!您可以创建2个不同的virtualenv,一个用于项目A,另一个用于项目B。现在,当您需要在项目A中工作时,只需为项目A激活virtualenv,反之亦然。

使用virtualenv时,一个更好的技巧是安装virtualenvwrapper来轻松管理您拥有的所有virtualenv。它是用于创建,工作和删除virtualenv的包装器。

Virtualenv is a tool to create isolated Python environments.

Let’s say you’re working in 2 different projects, A and B. Project A is a web project and the team is using the following packages:

  • Python 2.8.x
  • Django 1.6.x

The project B is also a web project but your team is using:

  • Python 2.7.x
  • Django 1.4.x

The machine that you’re working doesn’t have any version of django, what should you do? Install django 1.4? django 1.6? If you install django 1.4 globally would be easy to point to django 1.6 to work in project A?

Virtualenv is your solution! You can create 2 different virtualenv’s, one for project A and another for project B. Now, when you need to work in project A, just activate the virtualenv for project A, and vice-versa.

A better tip when using virtualenv is to install virtualenvwrapper to manage all the virtualenv’s that you have, easily. It’s a wrapper for creating, working, removing virtualenv’s.


回答 2

这是另一个好方法:http : //www.saltycrane.com/blog/2009/05/notes-using-pip-and-virtualenv-django/

这说明了如何使用pipvirtualenv和pip需求文件;Scobal的两个建议的教程都非常有帮助,但都是以easy_install中心为中心的。

请注意,这些教程都没有解释如何在virtualenv中运行不同版本的Python-为此,请参见以下SO问题:对virtualenv使用不同的Python版本

Here’s another good one: http://www.saltycrane.com/blog/2009/05/notes-using-pip-and-virtualenv-django/

This one shows how to use pip and a pip requirements file with virtualenv; Scobal‘s two suggested tutorials are both very helpful but are both easy_install-centric.

Note that none of these tutorials explain how to run a different version of Python within a virtualenv – for this, see this SO question: Use different Python version with virtualenv


回答 3

为了在干净的Ubuntu安装上设置virtualenv,我发现此zookeeper教程是最好的-您可以忽略有关zookeper本身的部分。该virtualenvwrapper文档提供类似的内容,但它是在告诉你到底该怎么把你有点稀缺的.bashrc文件。

For setting up virtualenv on a clean Ubuntu installation, I found this zookeeper tutorial to be the best – you can ignore the parts about zookeper itself. The virtualenvwrapper documentation offers similar content, but it’s a bit scarce on telling you what exactly to put into your .bashrc file.


pip在哪里安装其软件包?

问题:pip在哪里安装其软件包?

我激活了已安装pip的virtualenv。我做了

pip3 install Django==1.8

和Django成功下载。现在,我想打开Django文件夹。文件夹在哪里?通常它会在“下载”中,但是我不确定如果在virtualenv中使用pip安装它会在哪里。

I activated a virtualenv which has pip installed. I did

pip3 install Django==1.8

and Django successfully downloaded. Now, I want to open up the Django folder. Where is the folder located? Normally it would be in “downloads” but I’m not sure where it would be if I installed it using pip in a virtualenv.


回答 0

virtualenv一起使用时,pip通常会在路径中安装软件包<virtualenv_name>/lib/<python_ver>/site-packages

例如,我使用Python 2.7 创建了一个名为venv_test的测试virtualenv ,该文件夹位于中。djangovenv_test/lib/python2.7/site-packages/django

pip when used with virtualenv will generally install packages in the path <virtualenv_name>/lib/<python_ver>/site-packages.

For example, I created a test virtualenv named venv_test with Python 2.7, and the django folder is in venv_test/lib/python2.7/site-packages/django.


回答 1

根据大众需求,通过发布的答案提供了一个选项:

pip show <package name>将提供Windows和macOS的位置,我猜是任何系统。:)

例如:

> pip show cvxopt
Name: cvxopt
Version: 1.2.0
...
Location: /usr/local/lib/python2.7/site-packages

By popular demand, an option provided via posted answer:

pip show <package name> will provide the location for Windows and macOS, and I’m guessing any system. :)

For example:

> pip show cvxopt
Name: cvxopt
Version: 1.2.0
...
Location: /usr/local/lib/python2.7/site-packages

回答 2

pip list -v可用于列出软件包的安装位置,该位置在https://pip.pypa.io/zh/stable/news/#b1-2018-03-31中引入

当列表命令与“ -v”选项一起运行时,显示安装位置。(#979)

>pip list -v
Package                  Version   Location                                                             Installer
------------------------ --------- -------------------------------------------------------------------- ---------
alabaster                0.7.12    c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
apipkg                   1.5       c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
argcomplete              1.10.3    c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
astroid                  2.3.3     c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
...

更新pip10.0.0b1中引入了此功能。在Ubuntu 18.04上,pippip3安装有sudo apt install python-pip或是sudo apt install python3-pip9.0.1的版本,但没有此功能。检查https://github.com/pypa/pip/issues/5599,了解升级pip或升级的合适方法pip3

pip list -v can be used to list packages’ install locations, introduced in https://pip.pypa.io/en/stable/news/#b1-2018-03-31

Show install locations when list command ran with “-v” option. (#979)

>pip list -v
Package                  Version   Location                                                             Installer
------------------------ --------- -------------------------------------------------------------------- ---------
alabaster                0.7.12    c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
apipkg                   1.5       c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
argcomplete              1.10.3    c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
astroid                  2.3.3     c:\users\me\appdata\local\programs\python\python38\lib\site-packages pip
...

Update: This feature is introduced in pip 10.0.0b1. On Ubuntu 18.04, pip or pip3 installed with sudo apt install python-pip or sudo apt install python3-pip is 9.0.1 which doesn’t have this feature. Check https://github.com/pypa/pip/issues/5599 for suitable ways of upgrading pip or pip3.


回答 3

默认情况下,在Linux上,Pip将软件包安装到/usr/local/lib/python2.7/dist-packages。

在安装过程中使用virtualenv或–user将更改此默认位置。如果使用,请pip show确保使用的用户正确,否则pip可能看不到您所引用的软件包。

By default, on Linux, Pip installs packages to /usr/local/lib/python2.7/dist-packages.

Using virtualenv or –user during install will change this default location. If you use pip show make sure you are using the right user or else pip may not see the packages you are referencing.


回答 4

在Python解释器或脚本中,您可以执行

import site
site.getsitepackages() # list of global package locations

site.getusersitepackages() #string for user-specific package location

位置安装了第三方软件包(不在核心Python发行版中)。

在MacOS上我的Brew安装的Python上,前者输出

['/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages']

pip show如上一个答案所述,它规范化到所输出的相同路径:

$ readlink -f /usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages
/usr/local/lib/python3.7/site-packages

参考:https : //docs.python.org/3/library/site.html#site.getsitepackages

In a Python interpreter or script, you can do

import site
site.getsitepackages() # list of global package locations

and

site.getusersitepackages() #string for user-specific package location

for locations 3rd party packages (those not in the core Python distribution) are installed to.

On my Brew-installed Python on MacOS, the former outputs

['/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages'],

which canonicalizes to the same path output by pip show, as mentioned in a previous answer:

$ readlink -f /usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages
/usr/local/lib/python3.7/site-packages

Reference: https://docs.python.org/3/library/site.html#site.getsitepackages


如何从虚拟环境内部更新点子本身?

问题:如何从虚拟环境内部更新点子本身?

我可以更新点子管理的软件包,但是如何更新点子本身?据介绍pip --version,我目前在virtualenv中安装了pip 1.1,我想更新到最新版本。

这是什么命令?我需要使用distribute还是本机pip或virtualenv命令?我已经尝试过pip update,并pip update pip没有成功。

I’m able to update pip-managed packages, but how do I update pip itself? According to pip --version, I currently have pip 1.1 installed in my virtualenv and I want to update to the latest version.

What’s the command for that? Do I need to use distribute or is there a native pip or virtualenv command? I’ve already tried pip update and pip update pip with no success.


回答 0

pip仅仅是一个的PyPI包像任何其他; 您可以像升级任何软件包一样使用它来升级自身:

pip install --upgrade pip

在Windows上,推荐的命令是:

python -m pip install --upgrade pip

pip is just a PyPI package like any other; you could use it to upgrade itself the same way you would upgrade any package:

pip install --upgrade pip

On Windows the recommended command is:

python -m pip install --upgrade pip

回答 1

更安全的方法是通过python模块运行pip

python -m pip install -U pip

在Windows上,尝试替换自身的二进制文件似乎存在问题,此方法可解决该限制。

The more safe method is to run pip though a python module:

python -m pip install -U pip

On windows there seem to be a problem with binaries that try to replace themselves, this method works around that limitation.


回答 2

就我而言,我的pip版本已损坏,因此更新本身无法进行。

固定:

(inside virtualenv):easy_install -U pip

In my case my pip version was broken so the update by itself would not work.

Fix:

(inside virtualenv):easy_install -U pip

回答 3

我在Debian Jessie下尝试了上面提到的所有这些解决方案。它们不起作用,因为它只需要由debian软件包管理器编译的最新版本1.5.6相当于6.0.x版本。某些使用pip作为前提条件的软件包将无法正常运行,例如spaCy(需要使用–no-cache-dir选项才能正常运行)。

因此,解决这些问题的实际最佳方法是运行从wget下载的get-pip.py,它是从网站或使用curl进行的,如下所示:

 wget https://bootstrap.pypa.io/get-pip.py -O ./get-pip.py
 python ./get-pip.py
 python3 ./get-pip.py

这将安装当前版本,在编写此解决方案时为9.0.1,这远远超出了Debian提供的功能。

 $ pip --version
 pip 9.0.1 from /home/myhomedir/myvirtualenvdir/lib/python2.7/dist-packages (python 2.7)
 $ pip3 --version
 pip 9.0.1 from /home/myhomedir/myvirtualenvdir/lib/python3.4/site-packages (python 3.4)

I tried all of these solutions mentioned above under Debian Jessie. They don’t work, because it just takes the latest version compile by the debian package manager which is 1.5.6 which equates to version 6.0.x. Some packages that use pip as prerequisites will not work as a results, such as spaCy (which needs the option –no-cache-dir to function correctly).

So the actual best way to solve these problems is to run get-pip.py downloaded using wget, from the website or using curl as follows:

 wget https://bootstrap.pypa.io/get-pip.py -O ./get-pip.py
 python ./get-pip.py
 python3 ./get-pip.py

This will install the current version which at the time of writing this solution is 9.0.1 which is way beyond what Debian provides.

 $ pip --version
 pip 9.0.1 from /home/myhomedir/myvirtualenvdir/lib/python2.7/dist-packages (python 2.7)
 $ pip3 --version
 pip 9.0.1 from /home/myhomedir/myvirtualenvdir/lib/python3.4/site-packages (python 3.4)

回答 4

由于可怕的证书问题,使用’ pip install –upgrade pip ‘ 升级pip 并不总是有效:确认ssl证书时出现问题:[SSL:TLSV1_ALERT_PROTOCOL_VERSION] tlsv1警报协议版本

我喜欢对虚拟环境使用单行命令:

curl https://bootstrap.pypa.io/get-pip.py | python -

或者,如果您想将其安装在宽盒中,则需要

curl https://bootstrap.pypa.io/get-pip.py | sudo python -

如果要在自动化脚本中运行时使输出静音,则可以给curl -s标志。

Upgrading pip using ‘pip install –upgrade pip‘ does not always work because of the dreaded cert issue: There was a problem confirming the ssl certificate: [SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version

I like to use the one line command for virtual envs:

curl https://bootstrap.pypa.io/get-pip.py | python -

Or if you want to install it box wide you will need

curl https://bootstrap.pypa.io/get-pip.py | sudo python -

you can give curl a -s flag if you want to silence the output when running in an automation script.


回答 5

就我而言,这是从Debian Stable中的终端命令行执行的

python3 -m pip install --upgrade pip

In my case this worked from the terminal command line in Debian Stable

python3 -m pip install --upgrade pip

回答 6

为了使它对我有用,我必须使用Python命令提示符(在VS CODE的WIN10上)在Python目录中进行深入研究。就我而言,它位于我的“ AppData \ Local \ Programs \ Python \ python35-32”目录中。从现在开始,我执行命令…

python -m pip install --upgrade pip

这很有效,我很好。

To get this to work for me I had to drill down in the Python directory using the Python command prompt (on WIN10 from VS CODE). In my case it was in my “AppData\Local\Programs\Python\python35-32” directory. From there now I ran the command…

python -m pip install --upgrade pip

This worked and I’m good to go.


回答 7

使用管理员权限打开命令提示符,然后重复以下命令:

python -m pip install --upgrade pip

Open Command Prompt with Administrator Permissions, and repeat the command:

python -m pip install --upgrade pip

回答 8

pip版本10有问题。它将显示为错误:

ubuntu@mymachine-:~/mydir$ sudo pip install --upgrade pip
Traceback (most recent call last):
  File "/usr/bin/pip", line 9, in <module>
    from pip import main
ImportError: cannot import name main

解决方案是在要升级的venv中,然后运行:

sudo myvenv/bin/pip install --upgrade pip

而不只是

sudo pip install --upgrade pip

pip version 10 has an issue. It will manifest as the error:

ubuntu@mymachine-:~/mydir$ sudo pip install --upgrade pip
Traceback (most recent call last):
  File "/usr/bin/pip", line 9, in <module>
    from pip import main
ImportError: cannot import name main

The solution is to be in the venv you want to upgrade and then run:

sudo myvenv/bin/pip install --upgrade pip

rather than just

sudo pip install --upgrade pip

回答 9

如果您使用venv,则任何更新到pip的安装都将导致升级系统pip,而不是venv pip。您还需要升级pip引导程序包。

  python3 -m pip install --upgrade pip setuptools wheel

In case you are using venv any update to pip install will result in upgrading the system pip instead of the venv pip. You need to upgrade the pip bootstrapping packages as well.

  python3 -m pip install --upgrade pip setuptools wheel

回答 10

我已经在C:\ Python \ Python36中安装了Python,因此转到Windows命令提示符并键入“ cd C:\ Python \ Python36”以获取正确的目录。然后输入“ python -m install –upgrade pip”全部好!

I had installed Python in C:\Python\Python36 so I went to the Windows command prompt and typed “cd C:\Python\Python36 to get to the right directory. Then entered the “python -m install –upgrade pip” all good!


回答 11

在Windows 7笔记本电脑上,正确安装最新版本的pip的正确方法是:

python.exe -m pip install --upgrade pip

On my lap-top with Windows 7 the right way to install latest version of pip is:

python.exe -m pip install --upgrade pip

回答 12

单行Python程序
我发现的最好方法是编写一个单行程序,该程序可以下载并运行官方的get-pip脚本。参见下面的代码。

官方文档建议使用curl下载get-pip脚本,但是由于我在Windows上工作且未安装curl,因此我更喜欢使用python本身来下载和运行脚本。

这是可以使用Python 3通过命令行运行的单行程序:

python -c "import urllib.request; exec(urllib.request.urlopen('https://bootstrap.pypa.io/get-pip.py').read())"

根据安装说明,该行将获取官方的“ get-pip.py”脚本,并使用“ exec”命令执行该脚本。

对于Python2,您可以将“ urllib.request”替换为“ urllib2”:

python -c "import urllib2; exec(urllib2.urlopen('https://bootstrap.pypa.io/get-pip.py').read())"

预防措施
值得注意的是,盲目运行任何python脚本本质上都是危险的。因此,官方说明建议在运行之前下载脚本并进行检查。

就是说,许多人实际上并不检查代码,而只是运行它。这一单行程序使这一过程变得更加容易。

Single Line Python Program
The best way I have found is to write a single line program that downloads and runs the official get-pip script. See below for the code.

The official docs recommend using curl to download the get-pip script, but since I work on windows and don’t have curl installed I prefer using python itself to download and run the script.

Here is the single line program that can be run via the command line using Python 3:

python -c "import urllib.request; exec(urllib.request.urlopen('https://bootstrap.pypa.io/get-pip.py').read())"

This line gets the official “get-pip.py” script as per the installation notes and executes the script with the “exec” command.

For Python2 you would replace “urllib.request” with “urllib2”:

python -c "import urllib2; exec(urllib2.urlopen('https://bootstrap.pypa.io/get-pip.py').read())"

Precautions
It’s worth noting that running any python script blindly is inherently dangerous. For this reason, the official instructions recommend downloading the script and inspecting it before running.

That said, many people don’t actually inspect the code and just run it. This one-line program makes that easier.


回答 13

我在树莓派上遇到了类似的问题。

问题在于http需要SSL,因此我需要强制它使用https来解决此要求。

sudo pip install --upgrade pip --index-url=https://pypi.python.org/simple

要么

sudo pip-3.2 --upgrade pip --index-url=https://pypi.python.org/simple/

I had a similar problem on a raspberry pi.

The problem was that http requires SSL and so I needed to force it to use https to get around this requirement.

sudo pip install --upgrade pip --index-url=https://pypi.python.org/simple

or

sudo pip-3.2 --upgrade pip --index-url=https://pypi.python.org/simple/

回答 14

我处于类似情况,想更新urllib3软件包。对我有用的是:

pip3 install --upgrade --force-reinstall --ignore-installed urllib3==1.25.3

I was in a similar situation and wanted to update urllib3 package. What worked for me was:

pip3 install --upgrade --force-reinstall --ignore-installed urllib3==1.25.3

回答 15

很简单。只需从https://bootstrap.pypa.io/get-pip.py下载pip 。将文件保存在forlder或dekstop中。我将文件保存在D盘中,然后从命令提示符导航到下载pip的文件夹。然后在那打

python -get-pip.py

点安装屏幕截图

Very Simple. Just download pip from https://bootstrap.pypa.io/get-pip.py . Save the file in some forlder or dekstop. I saved the file in my D drive.Then from your command prompt navigate to the folder where you have downloaded pip. Then type there

python -get-pip.py

Pip installation screenshot


如何在Python上使用“ pip”安装psycopg2?

问题:如何在Python上使用“ pip”安装psycopg2?

我在用着 virtualenv,我需要安装“ psycopg2”。

我已经完成以下工作:

pip install http://pypi.python.org/packages/source/p/psycopg2/psycopg2-2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160

我有以下消息:

Downloading/unpacking http://pypi.python.org/packages/source/p/psycopg2/psycopg2
-2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160
  Downloading psycopg2-2.4.tar.gz (607Kb): 607Kb downloaded
  Running setup.py egg_info for package from http://pypi.python.org/packages/sou
rce/p/psycopg2/psycopg2-2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160
    Error: pg_config executable not found.

    Please add the directory containing pg_config to the PATH
    or specify the full executable path with the option:

        python setup.py build_ext --pg-config /path/to/pg_config build ...

    or with the pg_config option in 'setup.cfg'.
    Complete output from command python setup.py egg_info:
    running egg_info

creating pip-egg-info\psycopg2.egg-info

writing pip-egg-info\psycopg2.egg-info\PKG-INFO

writing top-level names to pip-egg-info\psycopg2.egg-info\top_level.txt

writing dependency_links to pip-egg-info\psycopg2.egg-info\dependency_links.txt

writing manifest file 'pip-egg-info\psycopg2.egg-info\SOURCES.txt'

warning: manifest_maker: standard file '-c' not found

Error: pg_config executable not found.



Please add the directory containing pg_config to the PATH

or specify the full executable path with the option:



    python setup.py build_ext --pg-config /path/to/pg_config build ...



or with the pg_config option in 'setup.cfg'.

----------------------------------------
Command python setup.py egg_info failed with error code 1
Storing complete log in C:\Documents and Settings\anlopes\Application Data\pip\p
ip.log

我的问题是,我只需要这样做才能使psycopg2工作?

python setup.py build_ext --pg-config /path/to/pg_config build ...

I’m using virtualenv and I need to install “psycopg2”.

I have done the following:

pip install http://pypi.python.org/packages/source/p/psycopg2/psycopg2-2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160

And I have the following messages:

Downloading/unpacking http://pypi.python.org/packages/source/p/psycopg2/psycopg2
-2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160
  Downloading psycopg2-2.4.tar.gz (607Kb): 607Kb downloaded
  Running setup.py egg_info for package from http://pypi.python.org/packages/sou
rce/p/psycopg2/psycopg2-2.4.tar.gz#md5=24f4368e2cfdc1a2b03282ddda814160
    Error: pg_config executable not found.

    Please add the directory containing pg_config to the PATH
    or specify the full executable path with the option:

        python setup.py build_ext --pg-config /path/to/pg_config build ...

    or with the pg_config option in 'setup.cfg'.
    Complete output from command python setup.py egg_info:
    running egg_info

creating pip-egg-info\psycopg2.egg-info

writing pip-egg-info\psycopg2.egg-info\PKG-INFO

writing top-level names to pip-egg-info\psycopg2.egg-info\top_level.txt

writing dependency_links to pip-egg-info\psycopg2.egg-info\dependency_links.txt

writing manifest file 'pip-egg-info\psycopg2.egg-info\SOURCES.txt'

warning: manifest_maker: standard file '-c' not found

Error: pg_config executable not found.



Please add the directory containing pg_config to the PATH

or specify the full executable path with the option:



    python setup.py build_ext --pg-config /path/to/pg_config build ...



or with the pg_config option in 'setup.cfg'.

----------------------------------------
Command python setup.py egg_info failed with error code 1
Storing complete log in C:\Documents and Settings\anlopes\Application Data\pip\p
ip.log

My question, I only need to do this to get the psycopg2 working?

python setup.py build_ext --pg-config /path/to/pg_config build ...

回答 0

注意:早在不久之前,PyPI中就存在Windows的二进制轮子,因此Windows用户不再是问题。以下是适用于Linux和Mac用户的解决方案,因为他们中的很多人都是通过网络搜索找到这篇文章的。


选项1

psycopg2-binary而是安装PyPI软件包,它具有适用于Linux和Mac OS的Python轮子。

pip install psycopg2-binary

选项2

安装先决条件来构建 psycopg2从源代码软件包:

Debian / Ubuntu

Python 3

sudo apt install libpq-dev python3-dev

您可能需要安装 python3.8-dev或类似的工具,例如Python 3.8。

Python 2 1

sudo apt install libpq-dev python-dev

如果还不够,请尝试

sudo apt install build-essential

要么

sudo apt install postgresql-server-dev-all

在再次安装psycopg2之前。

CentOS的6

参见班杰的答案


1真的吗?2020年

Note: Since a while back, there are binary wheels for Windows in PyPI, so this should no longer be an issue for Windows users. Below are solutions for Linux, Mac users, since lots of them find this post through web searches.


Option 1

Install the psycopg2-binary PyPI package instead, it has Python wheels for Linux and Mac OS.

pip install psycopg2-binary

Option 2

Install the prerequsisites for building the psycopg2 package from source:

Debian/Ubuntu

Python 3

sudo apt install libpq-dev python3-dev

You might need to install python3.8-dev or similar for e.g. Python 3.8.

Python 21

sudo apt install libpq-dev python-dev

If that’s not enough, try

sudo apt install build-essential

or

sudo apt install postgresql-server-dev-all

as well before installing psycopg2 again.

CentOS 6

See Banjer’s answer


1 Really? It’s 2020


回答 1

在CentOS上,您需要postgres开发软件包:

sudo yum install python-devel postgresql-devel

至少这是CentOS 6上的解决方案。

On CentOS, you need the postgres dev packages:

sudo yum install python-devel postgresql-devel

That was the solution on CentOS 6 at least.


回答 2

在安装了Postgres.app 9.3.2.0 RC2的Mac Mavericks上,安装Postgres之后,我需要使用以下代码:

sudo PATH=$PATH:/Applications/Postgres.app/Contents/Versions/9.3/bin pip install psycopg2

On Mac Mavericks with Postgres.app version 9.3.2.0 RC2 I needed to use the following code after installing Postgres:

sudo PATH=$PATH:/Applications/Postgres.app/Contents/Versions/9.3/bin pip install psycopg2


回答 3

如果您使用的是Mac,则可以使用自制软件

brew install postgresql

其他所有选项都在这里:http : //www.postgresql.org/download/macosx/

祝好运

if you’re on a mac you can use homebrew

brew install postgresql

And all other options are here: http://www.postgresql.org/download/macosx/

Good luck


回答 4

我最近在Windows机器上配置了psycopg2。最简单的安装是使用Windows可执行二进制文件。您可以在http://stickpeople.com/projects/python/win-psycopg/中找到它。

要在虚拟环境中安装本机二进制文件,请使用easy_install:

C:\virtualenv\Scripts\> activate.bat
(virtualenv) C:\virtualenv\Scripts\> easy_install psycopg2-2.5.win32-py2.7-pg9.2.4-release.exe

I recently configured psycopg2 on a windows machine. The easiest install is using a windows executable binary. You can find it at http://stickpeople.com/projects/python/win-psycopg/.

To install the native binary in a virtual envrionment, use easy_install:

C:\virtualenv\Scripts\> activate.bat
(virtualenv) C:\virtualenv\Scripts\> easy_install psycopg2-2.5.win32-py2.7-pg9.2.4-release.exe

回答 5

对于Python 3,您应该sudo apt-get install libpq-dev python3-dev在Debian下使用。

For Python 3 you should use sudo apt-get install libpq-dev python3-dev under Debian.


回答 6

这对我有用(在RHEL,CentOS上:

sudo yum install postgresql postgresql-devel python-devel

现在在pip install中包含指向您的postgresql二进制目录的路径:

sudo PATH=$PATH:/usr/pgsql-9.3/bin/ pip install psycopg2

确保包括正确的路径。就这样 :)

更新:对于python 3,请安装python3-devel而不是python-devel

This is what worked for me (On RHEL, CentOS:

sudo yum install postgresql postgresql-devel python-devel

And now include the path to your postgresql binary dir with you pip install:

sudo PATH=$PATH:/usr/pgsql-9.3/bin/ pip install psycopg2

Make sure to include the correct path. Thats all :)

UPDATE: For python 3, please install python3-devel instead of python-devel


回答 7

如果使用Mac OS,则应从源代码安装PostgreSQL。安装完成后,您需要使用以下方法添加此路径:

export PATH=/local/pgsql/bin:$PATH

或者您可以像这样添加路径:

export PATH=.../:usr/local/pgsql/bin

在您的.profile文件或.zshrc文件中。

这可能因操作系统而异。

您可以从http://www.thegeekstuff.com/2009/04/linux-postgresql-install-and-configure-from-source/遵循安装过程

If you using Mac OS, you should install PostgreSQL from source. After installation is finished, you need to add this path using:

export PATH=/local/pgsql/bin:$PATH

or you can append the path like this:

export PATH=.../:usr/local/pgsql/bin

in your .profile file or .zshrc file.

This maybe vary by operating system.

You can follow the installation process from http://www.thegeekstuff.com/2009/04/linux-postgresql-install-and-configure-from-source/


回答 8

到目前为止的答案太像魔术食谱。收到的错误告诉您pip无法找到PostgreSQL查询库的所需部分。可能是因为您在操作系统的非标准位置安装了它,这就是为什么该消息建议使用–pg-config选项的原因。

但是更常见的原因是您根本没有安装libpq。这通常发生在没有安装PostgreSQL服务器的机器上,因为您只想运行客户端应用程序,而不是服务器本身。每个OS /发行版都不相同,例如在Debian / Ubuntu上,您需要安装libpq-dev。这使您可以针对PostgreSQL查询库编译和链接代码。

大多数答案还建议安装Python开发库。小心。如果仅使用发行版中安装的默认Python,则可以使用,但是如果您使用的是较新版本,则可能会引起问题。如果您在此计算机上构建了Python,那么您已经具有编译C / C ++库与Python交互所需的dev库。只要您使用的是正确的pip版本,即与python二进制文件安装在同一bin文件夹中的版本,您便都已准备就绪。无需安装旧版本。

The answers so far are too much like magic recipes. The error that you received tells you that pip cannot find a needed part of the PostgreSQL Query library. Possibly this is because you have it installed in a non-standard place for your OS which is why the message suggests using the –pg-config option.

But a more common reason is that you don’t have libpq installed at all. This commonly happens on machines where you do NOT have PostgreSQL server installed because you only want to run client apps, not the server itself. Each OS/distro is different, for instance on Debian/Ubuntu you need to install libpq-dev. This allows you to compile and link code against the PostgreSQL Query library.

Most of the answers also suggest installing a Python dev library. Be careful. If you are only using the default Python installed by your distro, that will work, but if you have a newer version, it could cause problems. If you have built Python on this machine then you already have the dev libraries needed for compiling C/C++ libraries to interface with Python. As long as you are using the correct pip version, the one installed in the same bin folder as the python binary, then you are all set. No need to install the old version.


回答 9

Debian/Ubuntu

首先安装和构建psycopg2软件包的依赖项:

# apt-get build-dep python-psycopg2

然后在您的虚拟环境中,编译并安装psycopg2模块:

(env)$ pip install psycopg2

On Debian/Ubuntu:

First install and build dependencies of psycopg2 package:

# apt-get build-dep python-psycopg2

Then in your virtual environment, compile and install psycopg2 module:

(env)$ pip install psycopg2

回答 10

我已经在Windows中首先安装到基本python安装中的位置之前完成了此操作。

然后,您手动将已安装的psycopg2复制到virtualenv安装中。

它不漂亮,但是可以用。

I’ve done this before where in windows you install first into your base python installation.

Then, you manually copy the installed psycopg2 to the virtualenv install.

It’s not pretty, but it works.


回答 11

除了安装必需的软件包外,我还需要手动将PostgreSQL bin目录添加到PATH。在之前
$vi ~/.bash_profile
添加。PATH=/usr/pgsql-9.2/bin:$PATHexport PATH
$source ~/.bash_profile
$pip install psycopg2

Besides installing the required packages, I also needed to manually add PostgreSQL bin directory to PATH.
$vi ~/.bash_profile
Add PATH=/usr/pgsql-9.2/bin:$PATH before export PATH.
$source ~/.bash_profile
$pip install psycopg2


回答 12

在Windows XP上,如果未安装postgres,则会出现此错误…

On windows XP you get this error if postgres is not installed …


回答 13

我使用PG下载网站http://www.postgresql.org/download/linux/redhat/上的RedHat / CentOS存储库安装了Postgresql92

要获取pg_config,我必须将/usr/pgsql-9.2/bin添加到PATH。

I installed Postgresql92 using the RedHat / CentOS repository on PG’s downloads site http://www.postgresql.org/download/linux/redhat/

To get pg_config, I had to add /usr/pgsql-9.2/bin to PATH.


回答 14

在安装psycopg2之前,您需要安装python-dev软件包。

如果您使用的是Linux(可能还有其他系统,但我不能从经验上讲),则在安装dev软件包时,需要确保准确地了解运行的python版本。

例如,当我使用命令时:

sudo apt-get install python3-dev

尝试执行以下操作时,我仍然遇到相同的错误

pip install psycopg2

当我使用python 3.7时,我需要使用命令

sudo apt-get install python3.7-dev

完成此操作后,我再也不会遇到任何问题。显然,如果您使用的是python 3.5版,则可以将该7更改为5。

Before you can install psycopg2 you will need to install the python-dev package.

If you’re working from Linux (and possibly other systems but i can’t speak from experience) you will need to make sure to be quite exact about what version of python your running when installing the dev package.

For example when I used the command:

sudo apt-get install python3-dev

I still ran into the same error when trying to

pip install psycopg2

As I am using python 3.7 I needed to use the command

sudo apt-get install python3.7-dev

Once I did this I ran into no more issues. Obviously if your on python version 3.5 you would change that 7 to a 5.


回答 15

我已经为此奋斗了好几天,终于找到了如何使“ pip install psycopg2”命令在Windows(运行Cygwin)的virtualenv中运行的方法。

我碰到了“找不到pg_config可执行文件”。错误,但我已经在Windows中下载并安装了postgres。它也安装在Cygwin中。在Cygwin中运行“哪个pg_config”给出了“ / usr / bin / pg_config”,而运行“ pg_config”给出了合理的输出-但是,与Cygwin一起安装的版本是:

版本= PostgreSQL 8.2.11

这不适用于当前版本的psycopg2,后者似乎至少需要9.1。当我在Windows路径中添加“ c:\ Program Files \ PostgreSQL \ 9.2 \ bin”时,Cygwin pip安装程序能够找到正确的PostgreSQL版本,并且能够使用pip成功安装该模块。(无论如何,这可能比使用Cygwin版本的PostgreSQL更可取,因为本机版本运行得更快)。

I’ve been battling with this for days, and have finally figured out how to get the “pip install psycopg2” command to run in a virtualenv in Windows (running Cygwin).

I was hitting the “pg_config executable not found.” error, but I had already downloaded and installed postgres in Windows. It installed in Cygwin as well; running “which pg_config” in Cygwin gave “/usr/bin/pg_config”, and running “pg_config” gave sane output — however the version installed with Cygwin is:

VERSION = PostgreSQL 8.2.11

This won’t work with the current version of psycopg2, which appears to require at least 9.1. When I added “c:\Program Files\PostgreSQL\9.2\bin” to my Windows path, the Cygwin pip installer was able to find the correct version of PostgreSQL, and I was able to successfully install the module using pip. (This is probably preferable to using the Cygwin version of PostgreSQL anyway, as the native version will run much quicker).


回答 16

在Fedora 24上:对于Python 3.x

sudo dnf install postgresql-devel python3-devel

sudo dnf install redhat-rpm-config

激活您的虚拟环境:

pip install psycopg2

On Fedora 24: For Python 3.x

sudo dnf install postgresql-devel python3-devel

sudo dnf install redhat-rpm-config

Activate your Virtual Environment:

pip install psycopg2

回答 17

Psycopg2取决于Postgres库。在Ubuntu上,您可以使用:

apt-get install libpq-dev

然后:

pip install psycopg2

Psycopg2 Depends on Postgres Libraries. On Ubuntu You can use:

apt-get install libpq-dev

Then:

pip install psycopg2

回答 18

对于Windows较低的用户,他们不得不从下面的链接安装psycopg2,只需将其安装到您设置的任何Python安装中即可。它将名为“ psycopg2”的文件夹放置在python安装的site-packages文件夹中。

之后,只需将该文件夹复制到virtualenv的site-packages目录中,就不会有问题。

这是您可以找到安装psycopg2的可执行文件的链接

http://www.lfd.uci.edu/~gohlke/pythonlibs/

For lowly Windows users were stuck having to install psycopg2 from the link below, just install it to whatever Python installation you have setup. It will place the folder named “psycopg2” in the site-packages folder of your python installation.

After that, just copy that folder to the site-packages directory of your virtualenv and you will have no problems.

here is the link you can find the executable to install psycopg2

http://www.lfd.uci.edu/~gohlke/pythonlibs/


回答 19

在OpenSUSE 13.2上,此操作已修复:

sudo zypper in postgresql-devel 

On OpenSUSE 13.2, this fixed it:

sudo zypper in postgresql-devel 

回答 20

我可以将其安装在Windows计算机上,并通过以下命令将Anaconda / Spyder与python 2.7结合使用:

 !pip install psycopg2

然后建立与数据库的连接:

 import psycopg2
 conn = psycopg2.connect(dbname='dbname',host='host_name',port='port_number', user='user_name', password='password')

I could install it in a windows machine and using Anaconda/Spyder with python 2.7 through the following commands:

 !pip install psycopg2

Then to establish the connection to the database:

 import psycopg2
 conn = psycopg2.connect(dbname='dbname',host='host_name',port='port_number', user='user_name', password='password')

回答 21

Arch基本发行版中:

sudo pacman -S python-psycopg2
pip2 install psycopg2  # Use pip or pip3 to python3

In Arch base distributions:

sudo pacman -S python-psycopg2
pip2 install psycopg2  # Use pip or pip3 to python3

回答 22

如果pip不起作用,则可以从此处https://pypi.python.org/pypi/psycopg2下载.whl文件 。python setup.py install

if pip is not working than you can download .whl file from here https://pypi.python.org/pypi/psycopg2 extract it.. than python setup.py install


回答 23

在Ubuntu上,我只需要postgres dev软件包:

sudo apt-get install postgresql-server-dev-all

*在virtualenv中测试

On Ubuntu I just needed the postgres dev package:

sudo apt-get install postgresql-server-dev-all

*Tested in a virtualenv


回答 24

在OSX 10.11.6(El Capitan)上

brew install postgresql
PATH=$PATH:/Library/PostgreSQL/9.4/bin pip install psycopg2

On OSX 10.11.6 (El Capitan)

brew install postgresql
PATH=$PATH:/Library/PostgreSQL/9.4/bin pip install psycopg2

回答 25

在具有Macports的OSX上:

sudo port install postgresql96
export PATH=/opt/local/lib/postgresql96/bin:$PATH

On OSX with macports:

sudo port install postgresql96
export PATH=/opt/local/lib/postgresql96/bin:$PATH

回答 26

我遇到了这个问题,主要原因是安装了2个相同的版本。一种通过postgres.app,另一种通过HomeBrew。

如果您选择仅保留APP:

brew unlink postgresql
pip3 install psycopg2

I was having this problem, the main reason was with 2 equal versions installed. One by postgres.app and one by HomeBrew.

If you choose to keep only the APP:

brew unlink postgresql
pip3 install psycopg2

回答 27

在macOS Mojave上,请确保您使用适用于我的Command Line Tools 10.3进行了最新更新-通过Software Update对其进行了更新,Mojave上的Command Line Tools的先前版本对我不起作用。

On macOS Mojave make sure you on newest update with Command Line Tools 10.3 – that worked for me – updated it with Software Update, previous version of Command Line Tools on Mojave did not work for me.


回答 28

试试这个Gentoo

emerge dev-libs/libpqxx

Try this in Gentoo:

emerge dev-libs/libpqxx

回答 29

在Windows上是这样工作
的在虚拟环境中通过pip安装flask之后,在命令提示符下运行此命令

>pip install psycopg2

检查一下

On windows this is how it works
On the command prompt after installing flask via pip in virtual environment, run this command

>pip install psycopg2

Check this


如何删除/删除virtualenv?

问题:如何删除/删除virtualenv?

我使用以下命令创建了一个环境: virtualenv venv --distribute

:我无法用下面的命令将其删除rmvirtualenv venv这是部分virtualenvwrapper中提到下面virtualenvwrapper答案

ls在当前目录上执行了,但仍然看到venv

我可以删除它的唯一方法似乎是: sudo rm -rf venv

请注意该环境处于非活动状态。我正在运行Ubuntu 11.10。有任何想法吗?我尝试重新启动系统无济于事。

I created an environment with the following command: virtualenv venv --distribute

I cannot remove it with the following command: rmvirtualenv venvThis is part of virtualenvwrapper as mentioned in answer below for virtualenvwrapper

I do an lson my current directory and I still see venv

The only way I can remove it seems to be: sudo rm -rf venv

Note that the environment is not active. I’m running Ubuntu 11.10. Any ideas? I’ve tried rebooting my system to no avail.


回答 0

而已!没有用于删除虚拟环境的命令。只需停用它,然后通过递归删除它即可消除应用程序的工件。

请注意,无论您使用哪种虚拟环境,都一样。virtualenvvenv,Python环境pyenvpipenv都在这里基于同样的原则。

That’s it! There is no command for deleting your virtual environment. Simply deactivate it and rid your application of its artifacts by recursively removing it.

Note that this is the same regardless of what kind of virtual environment you are using. virtualenv, venv, Anaconda environment, pyenv, pipenv are all based the same principle here.


回答 1

只是为了回应@skytreader先前评论的内容,它rmvirtualenv是由virtualenvwrapper而不是提供的命令virtualenv。也许您没有virtualenvwrapper安装?

有关更多详细信息,请参见VirtualEnvWrapper命令参考

Just to echo what @skytreader had previously commented, rmvirtualenv is a command provided by virtualenvwrapper, not virtualenv. Maybe you didn’t have virtualenvwrapper installed?

See VirtualEnvWrapper Command Reference for more details.


回答 2

采用 rmvirtualenv

在中删除环境$WORKON_HOME

句法:

rmvirtualenv ENVNAME

在删除当前环境之前,必须使用停用功能。

$ rmvirtualenv my_env

参考:http : //virtualenvwrapper.readthedocs.io/en/latest/command_ref.html

Use rmvirtualenv

Remove an environment, in the $WORKON_HOME.

Syntax:

rmvirtualenv ENVNAME

You must use deactivate before removing the current environment.

$ rmvirtualenv my_env

Reference: http://virtualenvwrapper.readthedocs.io/en/latest/command_ref.html


回答 3

您可以通过递归卸载所有依赖项来删除所有依赖项,然后删除venv。

编辑,包括艾萨克·特纳评论

source venv/bin/activate
pip freeze > requirements.txt
pip uninstall -r requirements.txt -y
deactivate
rm -r venv/

You can remove all the dependencies by recursively uninstalling all of them and then delete the venv.

Edit including Isaac Turner commentary

source venv/bin/activate
pip freeze > requirements.txt
pip uninstall -r requirements.txt -y
deactivate
rm -r venv/

回答 4

只需从系统中删除虚拟环境即可,无需特殊命令

rm -rf venv

Simply remove the virtual environment from the system.There’s no special command for it

rm -rf venv

回答 5

来自virtualenv的官方文档https://virtualenv.pypa.io/en/stable/userguide/

删除环境

只需删除虚拟环境,然后将其所有内容删除即可,只需删除虚拟环境即可:

(ENV)$ deactivate
$ rm -r /path/to/ENV

from virtualenv’s official document https://virtualenv.pypa.io/en/stable/userguide/

Removing an Environment

Removing a virtual environment is simply done by deactivating it and deleting the environment folder with all its contents:

(ENV)$ deactivate
$ rm -r /path/to/ENV

回答 6

如果您使用的是pyenv,则可以删除您的虚拟环境:

$ pyenv virtualenv-delete <name>

If you are using pyenv, it is possible to delete your virtual environment:

$ pyenv virtualenv-delete <name>

回答 7

以下命令对我有用。

rm -rf /path/to/virtualenv

The following command works for me.

rm -rf /path/to/virtualenv

回答 8

我曾经pyenv uninstall my_virt_env_name删除虚拟环境。

注意:我使用的是通过安装脚本安装的pyenv-virtualenv。

I used pyenv uninstall my_virt_env_name to delete the virual environment.

Note: I’m using pyenv-virtualenv installed through the install script.


回答 9

如果您是Windows用户并且正在使用conda在Anaconda提示符下管理环境,则可以执行以下操作:

确保停用虚拟环境或重新启动Anaconda Prompt。使用以下命令删除虚拟环境:

$ conda env remove --name $MyEnvironmentName

或者,您可以转到

C:\Users\USERNAME\AppData\Local\Continuum\anaconda3\envs\MYENVIRONMENTNAME

(这是默认文件路径)并手动删除文件夹。

If you are a Windows user and you are using conda to manage the environment in Anaconda prompt, you can do the following:

Make sure you deactivate the virtual environment or restart Anaconda Prompt. Use the following command to remove virtual environment:

$ conda env remove --name $MyEnvironmentName

Alternatively, you can go to the

C:\Users\USERNAME\AppData\Local\Continuum\anaconda3\envs\MYENVIRONMENTNAME

(that’s the default file path) and delete the folder manually.


回答 10

如果您是Windows用户,则位于C:\ Users \您的用户名\ Envs中。您可以从那里删除它。

也可以在命令提示符下输入rmvirtualenv环境名称。

我尝试使用命令提示符,所以它说已删除,但它仍然存在。所以我手动将其删除。

if you are windows user, then it’s in C:\Users\your_user_name\Envs. You can delete it from there.

Also try in command prompt rmvirtualenv environment name.

I tried with command prompt so it said deleted but it was still existed. So i manually delete it.


回答 11

deactivate是您要查找的命令。就像已经说过的一样,没有删除虚拟环境的命令。只需停用它!

deactivate is the command you are looking for. Like what has already been said, there is no command for deleting your virtual environment. Simply deactivate it!


回答 12

如果您是Windows用户,还可以通过以下步骤删除环境:C:/Users/username/Anaconda3/envs 在这里,您可以看到虚拟环境列表,并删除不再需要的环境。

If you’re a windows user, you can also delete the environment by going to: C:/Users/username/Anaconda3/envs Here you can see a list of virtual environment and delete the one that you no longer need.


回答 13

您可以按照以下步骤删除与virtualenv关联的所有文件,然后再次重新安装virtualenv并使用它

cd {python virtualenv folder}

find {broken virtualenv}/ -type l                             ## to list out all the links

deactivate                                           ## deactivate if virtualenv is active

find {broken virtualenv}/ -type l -delete                    ## to delete the broken links

virtualenv {broken virtualenv} --python=python3           ## recreate links to OS's python

workon {broken virtualenv}                       ## activate & workon the fixed virtualenv

pip3 install  ... {other packages required for the project}

You can follow these steps to remove all the files associated with virtualenv and then reinstall the virtualenv again and using it

cd {python virtualenv folder}

find {broken virtualenv}/ -type l                             ## to list out all the links

deactivate                                           ## deactivate if virtualenv is active

find {broken virtualenv}/ -type l -delete                    ## to delete the broken links

virtualenv {broken virtualenv} --python=python3           ## recreate links to OS's python

workon {broken virtualenv}                       ## activate & workon the fixed virtualenv

pip3 install  ... {other packages required for the project}


回答 14

步骤1:通过复制并粘贴以下命令来删除virtualenv virtualenvwrapper:

$ sudo pip uninstall virtualenv virtualenvwrapper

步骤2:转到.bashrc并删除所有virtualenv和virtualenvwrapper

打开终端:

$ sudo nano .bashrc

向下滚动,您将看到下面的代码,然后将其删除。

# virtualenv and virtualenvwrapper
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source /usr/local/bin/virtualenvwrapper.sh

接下来,获取.bashrc:

$ source ~/.bashrc

最后步骤:在没有终端/外壳的情况下,转到/ home并查找.virtualenv(我忘记了名称,因此,如果您发现与之相似.virtualenv.venv只是删除它。这将起作用。

step 1: delete virtualenv virtualenvwrapper by copy and paste the following command below:

$ sudo pip uninstall virtualenv virtualenvwrapper

step 2: go to .bashrc and delete all virtualenv and virtualenvwrapper

open terminal:

$ sudo nano .bashrc

scroll down and you will see the code bellow then delete it.

# virtualenv and virtualenvwrapper
export WORKON_HOME=$HOME/.virtualenvs
export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3
source /usr/local/bin/virtualenvwrapper.sh

next, source the .bashrc:

$ source ~/.bashrc

FINAL steps: without terminal/shell go to /home and find .virtualenv (I forgot the name so if your find similar to .virtualenv or .venv just delete it. That will work.


没有名为pkg_resources的模块

问题:没有名为pkg_resources的模块

我正在将Django应用程序部署到开发服务器,并且在运行时遇到此错误pip install -r requirements.txt

Traceback (most recent call last):
  File "/var/www/mydir/virtualenvs/dev/bin/pip", line 5, in <module>
    from pkg_resources import load_entry_point
ImportError: No module named pkg_resources

pkg_resources似乎与一起分发setuptools。最初,我认为可能不会将它安装到virtualenv中的Python,所以我setuptools 2.6使用以下命令将了(与Python相同的版本)安装到virtualenv 中的Python站点软件包中:

sh setuptools-0.6c11-py2.6.egg --install-dir /var/www/mydir/virtualenvs/dev/lib/python2.6/site-packages

编辑:这只发生在virtualenv内部。如果我在virtualenv之外打开控制台,则pkg_resources存在,但仍然出现相同的错误。

关于为什么pkg_resources不在路上的任何想法?

I’m deploying a Django app to a dev server and am hitting this error when I run pip install -r requirements.txt:

Traceback (most recent call last):
  File "/var/www/mydir/virtualenvs/dev/bin/pip", line 5, in <module>
    from pkg_resources import load_entry_point
ImportError: No module named pkg_resources

pkg_resources appears to be distributed with setuptools. Initially I thought this might not be installed to the Python in the virtualenv, so I installed setuptools 2.6 (same version as Python) to the Python site-packages in the virtualenv with the following command:

sh setuptools-0.6c11-py2.6.egg --install-dir /var/www/mydir/virtualenvs/dev/lib/python2.6/site-packages

EDIT: This only happens inside the virtualenv. If I open a console outside the virtualenv then pkg_resources is present, but I am still getting the same error.

Any ideas as to why pkg_resources is not on the path?


回答 0

2018年7月更新

现在大多数人都应该使用pip install setuptools(可能与一起使用sudo)。

有些人可能需要(重新)安装python-setuptools通过他们的软件包管理的软件包(apt-get installyum install,等)。

此问题可能高度取决于您的操作系统和开发环境。如果上述方法不适用于您,请参见下面的旧式/其他答案。

说明

此错误消息是由缺少/损坏的Python setuptools软件包引起的。根据Matt M.的注释和setuptools问题#581,以下引用的引导脚本不再是推荐的安装方法。

如果仍然对任何人有帮助,引导脚本说明将保留在下面。

旧版答案

ImportError今天在尝试使用点子时遇到了同样的问题。不知何故,该setuptools软件包已在我的Python环境中删除。

要解决此问题,请运行以下安装脚本setuptools

wget https://bootstrap.pypa.io/ez_setup.py -O - | python

(或者,如果您尚未wget安装(例如OS X),请尝试

curl https://bootstrap.pypa.io/ez_setup.py | python

可能带有sudo前缀。)

如果您使用的任何版本distribute,或setuptools0.6以下的版本,则必须先将其卸载。*

有关更多详细信息,请参见安装说明


*如果您已经可以使用distribute,则将其升级到“兼容性包装器” setuptools可以更轻松地进行切换。但是,如果事情已经坏了,请不要尝试。

July 2018 Update

Most people should now use pip install setuptools (possibly with sudo).

Some may need to (re)install the python-setuptools package via their package manager (apt-get install, yum install, etc.).

This issue can be highly dependent on your OS and dev environment. See the legacy/other answers below if the above isn’t working for you.

Explanation

This error message is caused by a missing/broken Python setuptools package. Per Matt M.’s comment and setuptools issue #581, the bootstrap script referred to below is no longer the recommended installation method.

The bootstrap script instructions will remain below, in case it’s still helpful to anyone.

Legacy Answer

I encountered the same ImportError today while trying to use pip. Somehow the setuptools package had been deleted in my Python environment.

To fix the issue, run the setup script for setuptools:

wget https://bootstrap.pypa.io/ez_setup.py -O - | python

(or if you don’t have wget installed (e.g. OS X), try

curl https://bootstrap.pypa.io/ez_setup.py | python

possibly with sudo prepended.)

If you have any version of distribute, or any setuptools below 0.6, you will have to uninstall it first.*

See Installation Instructions for further details.


* If you already have a working distribute, upgrading it to the “compatibility wrapper” that switches you over to setuptools is easier. But if things are already broken, don’t try that.


回答 1

sudo apt-get install --reinstall python-pkg-resources

在Debian中为我修复了该问题。似乎卸载某些.deb软件包(在我的情况下为扭曲集)已破坏python用于查找软件包的路径

sudo apt-get install --reinstall python-pkg-resources

fixed it for me in Debian. Seems like uninstalling some .deb packages (twisted set in my case) has broken the path python uses to find packages


回答 2

尝试在Ubuntu 13.10上将rhodecode安装到virtualenv时,我已经看到此错误。对我来说,解决方案是运行

pip install --upgrade setuptools
pip install --upgrade distribute 

在运行easy_install rhodecode之前。

I have seen this error while trying to install rhodecode to a virtualenv on ubuntu 13.10. For me the solution was to run

pip install --upgrade setuptools
pip install --upgrade distribute 

before I run easy_install rhodecode.


回答 3

这也发生在我身上。我认为,在virtualenv使用setuptools的情况下,如果requirements.txt包含“ distribute”条目,则会出现此问题。Pip将尝试修补setuptools以便为分发腾出空间,但不幸的是,它将失败一半。

一种简单的解决方案是删除当前的virtualenv,然后使用–distribute参数创建一个新的virtualenv。

如果使用virtualenvwrapper的示例:

$ deactivate
$ rmvirtualenv yourenv
$ mkvirtualenv yourenv --distribute
$ workon yourenv
$ pip install -r requirements.txt

It also happened to me. I think the problem will happen if the requirements.txt contains a “distribute” entry while the virtualenv uses setuptools. Pip will try to patch setuptools to make room for distribute, but unfortunately it will fail half way.

The easy solution is delete your current virtualenv then make a new virtualenv with –distribute argument.

An example if using virtualenvwrapper:

$ deactivate
$ rmvirtualenv yourenv
$ mkvirtualenv yourenv --distribute
$ workon yourenv
$ pip install -r requirements.txt

回答 4

在CentOS 6中,安装软件包python-setuptools对其进行了修复。

yum install python-setuptools

In CentOS 6 installing the package python-setuptools fixed it.

yum install python-setuptools

回答 5

我之前有这个错误,评分最高的答案给我一个错误,试图下载ez_setup.py文件。我找到了另一个来源,因此您可以运行以下命令:

curl http://peak.telecommunity.com/dist/ez_setup.py | python

我发现还必须使用sudo它才能使其正常工作,因此您可能需要运行:

sudo curl http://peak.telecommunity.com/dist/ez_setup.py | sudo python

我还创建了另一个位置,可以从以下位置下载脚本:

https://gist.github.com/ajtrichards/42e73562a89edb1039f3

I had this error earlier and the highest rated answer gave me an error trying to download the ez_setup.py file. I found another source so you can run the command:

curl http://peak.telecommunity.com/dist/ez_setup.py | python

I found that I also had to use sudo to get it working, so you may need to run:

sudo curl http://peak.telecommunity.com/dist/ez_setup.py | sudo python

I’ve also created another location that the script can be downloaded from:

https://gist.github.com/ajtrichards/42e73562a89edb1039f3


回答 6

在尝试了以下几个答案之后,与一位同事联系,在Ubuntu 16.04上为我工作的是:

pip install --force-reinstall -U setuptools
pip install --force-reinstall -U pip

就我而言,只有枕头3.1.1的旧版本有问题(枕头4.x正常工作),现在已解决!

After trying several of these answers, then reaching out to a colleague, what worked for me on Ubuntu 16.04 was:

pip install --force-reinstall -U setuptools
pip install --force-reinstall -U pip

In my case, it was only an old version of pillow 3.1.1 that was having trouble (pillow 4.x worked fine), and that’s now resolved!


回答 7

需要更多的须藤。然后使用easy_install安装pip。作品。

sudo wget https://bootstrap.pypa.io/ez_setup.py -O - | sudo python
sudo easy_install pip

Needed a little bit more sudo. Then used easy_install to install pip. Works.

sudo wget https://bootstrap.pypa.io/ez_setup.py -O - | sudo python
sudo easy_install pip

回答 8

我通过执行以下操作修复了virtualenv的错误:

从复制了pkg_resources.py

/Library/Python/2.7/site-packages/setuptools

/Library/Python/2.7/site-packages/

这可能是一个便宜的解决方法,但对我有用。

如果不存在安装工具,则可以通过键入尝试安装系统站点软件包virtualenv --system-site-packages /DESTINATION DIRECTORY,将最后一部分更改为要安装到的目录。pkg_rousources.py将在lib / python2.7 / site-packages中的该目录下

I fixed the error with virtualenv by doing this:

Copied pkg_resources.py from

/Library/Python/2.7/site-packages/setuptools

to

/Library/Python/2.7/site-packages/

This may be a cheap workaround, but it worked for me.

.

If setup tools doesn’t exist, you can try installing system-site-packages by typing virtualenv --system-site-packages /DESTINATION DIRECTORY, changing the last part to be the directory you want to install to. pkg_rousources.py will be under that directory in lib/python2.7/site-packages


回答 9

对我来说,导致此错误是因为我有一个名为“ site”的子目录!我不知道这是否是pip错误,但我从以下内容开始:

/some/dir/requirements.txt / some / dir / site /

pip install -r requirements.txt无法正常工作,出现上述错误!

将子文件夹从“ site”重命名为“ src”解决了该问题!也许pip正在寻找“网站包装”?疯。

For me, this error was being caused because I had a subdirectory called “site”! I don’t know if this is a pip bug or not, but I started with:

/some/dir/requirements.txt /some/dir/site/

pip install -r requirements.txt wouldn’t work, giving me the above error!

renaming the subfolder from “site” to “src” fixed the problem! Maybe pip is looking for “site-packages”? Crazy.


回答 10

当我将我的virtualenv激活为不同于创建它的用户时,我遇到了这个问题。看来是权限问题。我在尝试@cwc的答案时发现了这一点,并在输出中看到了这一点:

Installing easy_install script to /path/env/bin
error: /path/env/bin/easy_install: Permission denied

切换回创建virtualenv的用户,然后运行原始pip install命令没有任何问题。希望这可以帮助!

I had this problem when I had activated my virtualenv as a different user than the one who created it. It seems to be a permission problem. I discovered this when I tried the answer by @cwc and saw this in the output:

Installing easy_install script to /path/env/bin
error: /path/env/bin/easy_install: Permission denied

Switching back to the user that created the virtualenv, then running the original pip install command went without problems. Hope this helps!


回答 11

我今天也有这个问题。我只在虚拟环境中遇到问题。

对我来说,解决方案是停用虚拟环境,删除后再使用pip卸载virtualenv并重新安装。之后,我为我的项目创建了一个新的虚拟环境,然后pip在虚拟环境中都能正常工作,就像在正常环境中一样。

I had this problem today as well. I only got the problem inside the virtual env.

The solution for me was deactivating the virtual env, deleting and then uninstalling virtualenv with pip and reinstalling it. After that I created a new virtual env for my project, then pip worked fine both inside the virtual environment as in the normal environment.


回答 12

看起来他们已经离开了bitbucket,现在在github(https://github.com/pypa/setuptools)上

运行的命令是:

wget https://bootstrap.pypa.io/ez_setup.py -O - | sudo python

Looks like they have moved away from bitbucket and are now on github (https://github.com/pypa/setuptools)

Command to run is:

wget https://bootstrap.pypa.io/ez_setup.py -O - | sudo python

回答 13

对我来说,原来是上的权限问题site-packages。由于这只是我的开发环境,因此我提出了权限,然后一切又重新开始了:

sudo chmod -R a+rwx /path/to/my/venv/lib/python2.7/site-packages/

For me, it turned out to be a permissions problem on site-packages. Since it’s only my dev environment, I raised the permissions and everything is working again:

sudo chmod -R a+rwx /path/to/my/venv/lib/python2.7/site-packages/

回答 14

如果通过conda安装的应用程序遇到此问题,则解决方案(如此错误报告中所述)仅是使用以下命令安装安装工具:

conda install setuptools

If you are encountering this issue with an application installed via conda, the solution (as stated in this bug report) is simply to install setup-tools with:

conda install setuptools

回答 15

在Windows上,使用python 3.7,这对我有用:

pip install --upgrade setuptools --user

--user 将软件包安装在您的主目录中,该目录不需要管理员权限。

On Windows, with python 3.7, this worked for me:

pip install --upgrade setuptools --user

--user installs packages in your home directory, which doesn’t require admin privileges.


回答 16

简单的解决方法是您可以使用conda升级setuptools或整个环境。(特别适用于Windows用户。)

conda upgrade -c anaconda setuptools

如果删除了setuptools,则需要再次安装setuptools。

conda install -c anaconda setuptools

如果所有方法均无效,则可以升级conda环境。但是我不建议您需要重新安装和卸载某些软件包,因为这样做会加剧这种情况。

the simple resoluition is that you can use conda to upgrade setuptools or entire enviroment. (Specially for windows user.)

conda upgrade -c anaconda setuptools

if the setuptools is removed, you need to install setuptools again.

conda install -c anaconda setuptools

if these all methodes doesn’t work, you can upgrade conda environement. But I do not recommend that you need to reinstall and uninstall some packages because after that it will exacerbate the situation.


回答 17

显然您缺少setuptools。某些virtualenv版本默认情况下使用分发而不是setuptools。--setuptools在创建virtualenv时使用该选项,或者VIRTUALENV_SETUPTOOLS=1在您的环境中设置。

Apparently you’re missing setuptools. Some virtualenv versions use distribute instead of setuptools by default. Use the --setuptools option when creating the virtualenv or set the VIRTUALENV_SETUPTOOLS=1 in your environment.


回答 18

就我而言,我最初安装了2个python版本,后来又删除了较旧的版本。因此,在创建虚拟环境时

virtualenv venv

指的是卸载的python

什么对我有用

python3 -m virtualenv venv

当您尝试使用点子时也是如此。

In my case, I had 2 python versions installed initially and later I had deleted the older one. So while creating the virtual environment

virtualenv venv

was referring to the uninstalled python

What worked for me

python3 -m virtualenv venv

Same is true when you are trying to use pip.


回答 19

当我尝试遵循本OSX指南时,遇到了这个答案。对我python get-pip有用的是,跑步后,我还必须easy_install pip。这解决了根本无法运行点子的问题。我确实安装了一堆旧的Macport东西。那可能有冲突。

I came across this answer when I was trying to follow this guide for OSX. What worked for me was, after running python get-pip, I had to ALSO easy_install pip. That fixed the issue of not being able to run pip at all. I did have a bunch of old macport stuff installed. That may have conflicted.


回答 20

在Windows上,我安装了从www.lfd.uci.edu/~gohlke/pythonlibs/下载的pip然后出现了这个问题。

所以我应该先安装setuptools(easy_install)。

On windows, I installed pip downloaded from www.lfd.uci.edu/~gohlke/pythonlibs/ then encontered this problem.

So I should have installed setuptools(easy_install) first.


回答 21

只需setuptools通过以下方式重新安装您的:

$ sudo wget https://pypi.python.org/packages/source/s/setuptools/setuptools-0.6c11.tar.gz#md5=7df2a529a074f613b509fb44feefefe74e
$ tar -zxvf setuptools-0.6c11.tar.gz
$ cd setuptools-0.6c11/
$ sudo python setup.py build
$ sudo python setup.py install
$ sudo pip install --upgrade setuptools

那么一切都会好起来的。

just reinstall your setuptools by :

$ sudo wget https://pypi.python.org/packages/source/s/setuptools/setuptools-0.6c11.tar.gz#md5=7df2a529a074f613b509fb44feefefe74e
$ tar -zxvf setuptools-0.6c11.tar.gz
$ cd setuptools-0.6c11/
$ sudo python setup.py build
$ sudo python setup.py install
$ sudo pip install --upgrade setuptools

then everything will be fine.


回答 22

我使用CentOS 6.7,而我的python刚刚从2.6.6升级到2.7.11,在尝试了许多不同的答案之后,终于有以下一个工作了:

sudo yum install python-devel

希望能帮助同样情况的人。

I use CentOS 6.7, and my python was just upgrade from 2.6.6 to 2.7.11, after tried so many different answer, finally the following one does the job:

sudo yum install python-devel

Hope help someone in the same situation.


回答 23

没有一个发布的答案对我有用,所以我重新安装了pip并成功了!

sudo apt-get install python-setuptools python-dev build-essential 

sudo easy_install pip 

pip install --upgrade setuptools

(参考:http//www.saltycrane.com/blog/2010/02/how-install-pip-ubuntu/

None of the posted answers worked for me, so I reinstalled pip and it worked!

sudo apt-get install python-setuptools python-dev build-essential 

sudo easy_install pip 

pip install --upgrade setuptools

(reference: http://www.saltycrane.com/blog/2010/02/how-install-pip-ubuntu/)


回答 24

更新我的Ubuntu版本后,我遇到了这个问题。它似乎已经遍历并删除了我所有虚拟环境中的设置工具。

为了解决这个问题,我将虚拟环境重新安装回了目标目录。这清理了缺少的设置工具,并使一切重新运行。

例如:

~/RepoDir/TestProject$ virtualenv TestEnvironmentDir

I ran into this problem after updating my Ubuntu build. It seems to have gone through and removed set up tools in all of my virtual environments.

To remedy this I reinstalled the virtual environment back into the target directory. This cleaned up missing setup tools and got things running again.

e.g.:

~/RepoDir/TestProject$ virtualenv TestEnvironmentDir

回答 25

对我来说,一个很好的解决方法是使用--no-download选项virtualenv(VIRTUALENV_NO_DOWNLOAD=1 tox用于tox。)

For me a good fix was to use --no-download option to virtualenv (VIRTUALENV_NO_DOWNLOAD=1 tox for tox.)


回答 26

在Opensuse 42.1上,以下内容解决了此问题:

zypper in python-Pygments

On Opensuse 42.1 the following fixed this issue:

zypper in python-Pygments

回答 27

ImportError:没有名为pkg_resources的模块:解决方法是使用下面的命令重新安装python pip。

步骤:1登录到root用户。

sudo su root

步骤:2卸载python-pip软件包(如果存在)。

apt-get purge -y python-pip

步骤:3使用wget命令下载文件(在中下载文件pwd

wget https://bootstrap.pypa.io/get-pip.py

步骤:4运行python文件。

python ./get-pip.py

步骤:5 Finalic exicute安装命令。

apt-get install python-pip

注意:用户必须是root用户。

ImportError: No module named pkg_resources: the solution is to reinstall python pip using the following Command are under.

Step: 1 Login in root user.

sudo su root

Step: 2 Uninstall python-pip package if existing.

apt-get purge -y python-pip

Step: 3 Download files using wget command(File download in pwd )

wget https://bootstrap.pypa.io/get-pip.py

Step: 4 Run python file.

python ./get-pip.py

Step: 5 Finaly exicute installation command.

apt-get install python-pip

Note: User must be root.


回答 28

我在Google App Engine环境中遇到了该错误。并pip install -t lib setuptools解决了问题。

I experienced that error in my Google App Engine environment. And pip install -t lib setuptools fixed the issue.


回答 29

如果您使用的是Python 3,则应使用pip3而不是pip。该命令看起来像$ pip3 install requirements.txt

If you are using Python 3, you should use pip3 instead of pip. The command looks like $ pip3 install requirements.txt