标签归档:pip

找不到满足需求张量流的版本

问题:找不到满足需求张量流的版本

我安装了最新版本的Python (3.6.4 64-bit)和最新版本的PyCharm (2017.3.3 64-bit)。然后我在PyCharm中安装了一些模块(Numpy,Pandas等),但是当我尝试安装Tensorflow时却没有安装,并且出现了错误消息:

找不到满足TensorFlow要求的版本(来自版本:)找不到与TensorFlow匹配的发行版。

然后我尝试从命令提示符下安装TensorFlow,并得到了相同的错误消息。但是,我确实成功安装了tflearn。

我还安装了Python 2.7,但又收到了相同的错误消息。我搜索了该错误,并尝试了一些建议给其他人的方法,但是没有任何效果(包括安装Flask)。

我该如何安装Tensorflow?谢谢。

I installed the latest version of Python (3.6.4 64-bit) and the latest version of PyCharm (2017.3.3 64-bit). Then I installed some modules in PyCharm (Numpy, Pandas, etc), but when I tried installing Tensorflow it didn’t install, and I got the error message:

Could not find a version that satisfies the requirement TensorFlow (from versions: ) No matching distribution found for TensorFlow.

Then I tried installing TensorFlow from the command prompt and I got the same error message. I did however successfully install tflearn.

I also installed Python 2.7, but I got the same error message again. I googled the error and tried some of the things which were suggested to other people, but nothing worked (this included installing Flask).

How can I install Tensorflow? Thanks.


回答 0

截至2018年8月13日的Tensorflow支持Python 3.6.x和仅64位版本。

As of October 2020:

  • Tensorflow only supports the 64-bit version of Python

  • Tensorflow only supports Python 3.5 to 3.8

So, if you’re using an out-of-range version of Python (older or newer) or a 32-bit version, then you’ll need to use a different version.


回答 1

安装Tensorflow有两个重要规则:

  • 您必须安装Python x64。它在32b上不起作用,并且给出与您相同的错误。

  • 支持最新版本的Python3 = 3.7。

例如,您可以安装Python3.6.2-64bit,它的工作原理类似于Charm。

更新资料

据说在评论中,它可以在x64版本的Python3.8中使用。

There are a few important rules to install Tensorflow:

  • You have to install Python x64. It doesn’t work on 32b and it gives the same error as yours.

  • It doesn’t support Python versions later than 3.8 and Python 3.8 requires TensorFlow 2.2 or later.

For example, you can install Python3.8.6-64bit and it works like a charm.


回答 2

我成功安装了 pip install https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.8.0-py3-none-any.whl

I installed it successfully by pip install https://storage.googleapis.com/tensorflow/mac/cpu/tensorflow-1.8.0-py3-none-any.whl


回答 3

如果您使用anaconda,则默认情况下会安装python 3.7,因此您必须将其降级为3.6:

康达安装python = 3.6

然后:

点安装tensorflow

它在Ubuntu中为我工作。

if you are using anaconda, python 3.7 is installed by default, so you have to downgrade it to 3.6:

conda install python=3.6

then:

pip install tensorflow

it worked for me in Ubuntu.


回答 4

我正在为Windows提供它

如果您使用的是python-3

  1. 使用以下命令将pip升级到最新版本 py -m pip install --upgrade pip
  2. 使用安装软件包 py -m pip install <package-name>

如果您使用的是python-2

  1. 使用以下命令将pip升级到最新版本 py -2 -m pip install --upgrade pip
  2. 使用安装软件包 py -2 -m pip install <package-name>

对我有用

I am giving it for Windows

If you are using python-3

  1. Upgrade pip to the latest version using py -m pip install --upgrade pip
  2. Install package using py -m pip install <package-name>

If you are using python-2

  1. Upgrade pip to the latest version using py -2 -m pip install --upgrade pip
  2. Install package using py -2 -m pip install <package-name>

It worked for me


回答 5

根据Tensorflow python 3.8文档页面(截至2019年12月4日),该版本不可用。您将必须降级到python 3.7

Tensorflow isn’t available for python 3.8 (as of Dec 4th 2019) according to their documentation page. You will have to downgrade to python 3.7.


回答 6

卸载Python然后重新安装解决了我的问题,并且我能够成功安装TensorFlow。

Uninstalling Python and then reinstalling solved my issue and I was able to successfully install TensorFlow.


回答 7

不支持Python版本卸载python

https://www.python.org/downloads/release/python-362/

您应该在安装页面中检查并使用确切的版本。 https://www.tensorflow.org/install/install_windows

python 3.6.2或python 3.5.2为我解决了这个问题

Python version is not supported Uninstall python

https://www.python.org/downloads/release/python-362/

You should check and use the exact version in install page. https://www.tensorflow.org/install/install_windows

python 3.6.2 or python 3.5.2 solved this issue for me


回答 8

Tensorflow 2.2.0支持Python3.8

首先,请确保安装Python 3.8 64bit。出于某种原因,官方网站默认为32位。使用python -VV(两个大写字母V,不是W)验证此内容。然后照常继续:

python -m pip install --upgrade pip
python -m pip install wheel  # not necessary
python -m pip install tensorflow

与往常一样,请确保已安装CUDA 10.1和CuDNN。

Tensorflow 2.2.0 supports Python3.8

First, make sure to install Python 3.8 64bit. For some reason, the official site defaults to 32bit. Verify this using python -VV (two capital V, not W). Then continue as usual:

python -m pip install --upgrade pip
python -m pip install wheel  # not necessary
python -m pip install tensorflow

As usual, make sure you have CUDA 10.1 and CuDNN installed.


回答 9

看起来问题出在Python 3.8。请改用Python 3.7。我已采取步骤解决此问题。

  • 使用conda创建了python 3.7环境
  • 列表项在环境中使用pip install rasa安装了rasa。

为我工作。

Looks like the problem is with Python 3.8. Use Python 3.7 instead. Steps I took to solve this.

  • Created a python 3.7 environment with conda
  • List item Installed rasa using pip install rasa within the environment.

Worked for me.


回答 10

我在ubunu 18.04上使用python 3.6.8,对我来说解决方案是只升级pip

pip install --upgrade pip
pip install tensorflow==2.1.0

I am using python 3.6.8, on ubunu 18.04, for me the solution was to just upgrade pip

pip install --upgrade pip
pip install tensorflow==2.1.0

回答 11

Tensorflow似乎需要特殊版本的工具和库。Pip仅负责python版本。

要以专业的方式处理此问题(意味着它为我和其他人节省了Tremendos的时间),您必须为每个这样的软件设置一个特殊的环境。

为此,conda是一种高级工具。

我使用以下命令安装了Tensorflow:

sudo apt安装python3

sudo update-alternatives –install / usr / bin / python python / usr / bin / python3 1

sudo apt安装python3-pip

须藤apt-get install curl

卷曲https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh > Miniconda3-latest-Linux-x86_64.sh

bash Miniconda3-最新-Linux-x86_64.sh

来源〜/ .bashrc

  • 安装自己的phyton等

纳米.bashrc

  • 也许在这里插入您的代理等。

conda创建–name your_name python = 3

conda激活your_name

conda安装-c conda-forge tensorflow

  • 检查一切顺利

python -c“将tensorflow导入为tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000,1000])))”“

PS:一些可能有助于conda搜索tensorflow的命令

https://www.tensorflow.org/install/pip

使用virtualenv。康达更胜任。迷你主义者就足够了;不需要完整的conda

Tensorflow seems to need special versions of tools and libs. Pip only takes care of python version.

To handle this in a professional way (means it save tremendos time for me and others) you have to set a special environment for each software like this.

An advanced tool for this is conda.

I installed Tensorflow with this commands:

sudo apt install python3

sudo update-alternatives –install /usr/bin/python python /usr/bin/python3 1

sudo apt install python3-pip

sudo apt-get install curl

curl https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh > Miniconda3-latest-Linux-x86_64.sh

bash Miniconda3-latest-Linux-x86_64.sh

yes

source ~/.bashrc

  • installs its own phyton etc

nano .bashrc

  • maybe insert here your proxies etc.

conda create –name your_name python=3

conda activate your_name

conda install -c conda-forge tensorflow

  • check everything went well

python -c “import tensorflow as tf; tf.enable_eager_execution(); print(tf.reduce_sum(tf.random_normal([1000, 1000])))”

PS: some commands that may be helpful conda search tensorflow

https://www.tensorflow.org/install/pip

uses virtualenv. Conda is more capable. Miniconda ist sufficient; the full conda is not necessary


回答 12

tensorflow安装为我解决之前运行此命令:

pip install "pip>=19"

正如tensorflow的系统要求所述:

点19.0或更高版本

Running this before the tensorflow installation solved it for me:

pip install "pip>=19"

As the tensorflow‘s system requirements states:

pip 19.0 or later


回答 13

使用python 3.6或3.7版本,但重要的是您应该安装python版本的64位。

use python version 3.6 or 3.7 but the important thing is you should install the python version of 64-bit.


回答 14

对于TensorFlow 2.2版本:

  1. 确保您拥有python 3.8

尝试: python --version

要么 python3 --version

要么 py --version

  1. 升级python版本3.8的pip

尝试: python3 -m pip install --upgrade pip

要么 python -m pip install --upgrade pip

要么 py -m pip install --upgrade pip

  1. 安装TensorFlow:

尝试: python3 -m pip install TensorFlow

要么 python -m pip install TensorFlow

要么 py -m pip install TensorFlow

  1. 确保使用正确的python运行文件:

尝试: python3 file.py

要么 python file.py

要么 py file.py

For version TensorFlow 2.2:

  1. Make sure you have python 3.8

try: python --version

or python3 --version

or py --version

  1. Upgrade the pip of the python which has version 3.8

try: python3 -m pip install --upgrade pip

or python -m pip install --upgrade pip

or py -m pip install --upgrade pip

  1. Install TensorFlow:

try: python3 -m pip install TensorFlow

or python -m pip install TensorFlow

or py -m pip install TensorFlow

  1. Make sure to run the file with the correct python:

try: python3 file.py

or python file.py

or py file.py


回答 15

通过一一安装所需的所有软件包,我解决了与python 3.7相同的问题

步骤如下:

  1. 安装套件
  2. 请参阅错误消息:

    找不到满足要求的版本-所需模块的名称

  3. 安装所需的模块。通常,安装所需的模块需要安装另一个模块,以及另一个模块-其他两个模块,依此类推。

这样,我安装了30多个软件包,并有所帮助。现在我有了python 3.7中最新版本的tensorflow,而不必降级内核。

I solved the same problem with python 3.7 by installing one by one all the packages required

Here are the steps:

  1. Install the package
  2. See the error message:

    couldn’t find a version that satisfies the requirement — the name of the module required

  3. Install the module required. Very often, installation of the required module requires the installation of another module, and another module – a couple of the others and so on.

This way I installed more than 30 packages and it helped. Now I have tensorflow of the latest version in Python 3.7 and didn’t have to downgrade the kernel.


“ pip install –editable ./” vs“ python setup.py开发”

问题:“ pip install –editable ./” vs“ python setup.py开发”

两者之间有什么明显区别

pip install -e /path/to/mypackage

和setuptools的变体?

python /path/to/mypackage/setup.py develop

Is there any significant difference between

pip install -e /path/to/mypackage

and the setuptools variant?

python /path/to/mypackage/setup.py develop

回答 0

尝试避免setup.py直接调用,它不会正确告诉pip您已安装软件包。

pip install -e

对于本地项目,相对于项目路径创建“ SomeProject.egg-info”目录。与仅使用相比setup.py develop,这是一个优势 ,它可以直接相对于当前工作目录创建“ egg-info”。

更多:文档

另请阅读setuptools的文档

Try to avoid calling setup.py directly, it will not properly tell pip that you’ve installed your package.

With pip install -e:

For local projects, the “SomeProject.egg-info” directory is created relative to the project path. This is one advantage over just using setup.py develop, which creates the “egg-info” directly relative the current working directory.

More: docs

Also read the setuptools’ docs.


dist-packages和site-packages有什么区别?

问题:dist-packages和site-packages有什么区别?

我对python软件包的安装过程有些不满意。具体来说,安装在dist-packages目录和site-packages目录中的软件包之间有什么区别?

I’m a bit miffed by the python package installation process. Specifically, what’s the difference between packages installed in the dist-packages directory and the site-packages directory?


回答 0

dist-packages是特定于Debian的约定,也存在于其衍生版本中,例如Ubuntu。当模块从Debian软件包管理器进入以下位置时,它们将安装到dist-packages中:

/usr/lib/python2.7/dist-packages

由于easy_installpip是从软件包管理器安装的,因此它们也使用dist-packages,但是它们将软件包放在此处:

/usr/local/lib/python2.7/dist-packages

Debian Python Wiki

dist-packages而不是site-packages。从Debian软件包安装的第三方Python软件进入dist软件包,而不是站点软件包。这是为了减少系统Python与您可能手动安装的任何源Python构建之间的冲突。

这意味着,如果您从源代码手动安装Python,它将使用site-packages目录。这使您可以将两个安装分开,特别是因为Debian和Ubuntu在许多系统实用程序中都依赖Python的系统版本。

dist-packages is a Debian-specific convention that is also present in its derivatives, like Ubuntu. Modules are installed to dist-packages when they come from the Debian package manager into this location:

/usr/lib/python2.7/dist-packages

Since easy_install and pip are installed from the package manager, they also use dist-packages, but they put packages here:

/usr/local/lib/python2.7/dist-packages

From the Debian Python Wiki:

dist-packages instead of site-packages. Third party Python software installed from Debian packages goes into dist-packages, not site-packages. This is to reduce conflict between the system Python, and any from-source Python build you might install manually.

This means that if you manually install Python from source, it uses the site-packages directory. This allows you to keep the two installations separate, especially since Debian and Ubuntu rely on the system version of Python for many system utilities.


回答 1

dist-packages是debian专用的目录,apt朋友可以在其中安装他们的东西,并且site-packages是标准pip目录。

问题是-当不同目录中存在相同软件包的不同版本时,会发生什么?

我对这个问题的解决方案是建立dist-packages一个符号链接到site-packages

for d in $(find $WORKON_HOME -type d -name dist-packages); do
  pushd $d
  cd ..
  if test -d dist-packages/__pycache__; then
    mv -v dist-packages/__pycache__/* site-packages/__pycache__/
    rmdir -v dist-packages/__pycache__
  fi
  mv -v dist-packages/* site-packages/
  rmdir -v dist-packages
  ln -sv site-packages dist-packages
  popd
done

(如果您不使用gnu工具,请删除该-v选项)。

dist-packages is the debian-specific directory where apt and friends install their stuff, and site-packages is the standard pip directory.

The problem is — what happens when different versions of the same package are present in different directories?

My solution to the problem is to make dist-packages a symlink to site-packages:

for d in $(find $WORKON_HOME -type d -name dist-packages); do
  pushd $d
  cd ..
  if test -d dist-packages/__pycache__; then
    mv -v dist-packages/__pycache__/* site-packages/__pycache__/
    rmdir -v dist-packages/__pycache__
  fi
  mv -v dist-packages/* site-packages/
  rmdir -v dist-packages
  ln -sv site-packages dist-packages
  popd
done

(if you are not using gnu tools, remove the -v option).


如何点安装最小和最大版本范围的软件包?

问题:如何点安装最小和最大版本范围的软件包?

我想知道是否有任何方法可以告诉pip,特别是在需求文件中,安装pip install package>=0.2不应该安装最低版本()和最高版本的软件包(理论api:)pip install package<0.3

我问是因为我正在使用正在积极开发的第三方库。我希望我的pip要求文件指定它应该始终安装0.5.x分支的最新次要版本,但是我不希望pip尝试安装任何更新的主要版本(例如0.6.x),因为API是不同的。这很重要,因为即使0.6.x分支可用,但开发人员仍在向0.5.x分支发布补丁和错误修正,因此我不想package==0.5.9在需求文件中使用静态行。

有什么办法吗?

I’m wondering if there’s any way to tell pip, specifically in a requirements file, to install a package with both a minimum version (pip install package>=0.2) and a maximum version which should never be installed (theoretical api: pip install package<0.3).

I ask because I am using a third party library that’s in active development. I’d like my pip requirements file to specify that it should always install the most recent minor release of the 0.5.x branch, but I don’t want pip to ever try to install any newer major versions (like 0.6.x) since the API is different. This is important because even though the 0.6.x branch is available, the devs are still releasing patches and bugfixes to the 0.5.x branch, so I don’t want to use a static package==0.5.9 line in my requirements file.

Is there any way to do that?


回答 0

你可以做:

$ pip install "package>=0.2,<0.3"

并且pip会寻找最佳匹配,假设版本至少为0.2,且小于0.3。

这也适用于点子要求文件。请参阅PEP 440中有关版本说明符的完整详细信息。

You can do:

$ pip install "package>=0.2,<0.3"

And pip will look for the best match, assuming the version is at least 0.2, and less than 0.3.

This also applies to pip requirements files. See the full details on version specifiers in PEP 440.


回答 1

您还可以使用:

pip install package==0.5.*

更加一致且易于阅读。

you can also use:

pip install package==0.5.*

which is more consistent and easy to read.


回答 2

一种优雅的方法是使用~=符合PEP 440的兼容发布运算符。在您的情况下,总计为:

package~=0.5.0

例如,如果存在以下版本,它将选择0.5.9

  • 0.5.0
  • 0.5.9
  • 0.6.0

为了澄清起见,每对都是等效的:

~= 0.5.0
>= 0.5.0, == 0.5.*

~= 0.5
>= 0.5, == 0.*

An elegant method would be to use the ~= compatible release operator according to PEP 440. In your case this would amount to:

package~=0.5.0

As an example, if the following versions exist, it would choose 0.5.9:

  • 0.5.0
  • 0.5.9
  • 0.6.0

For clarification, each pair is equivalent:

~= 0.5.0
>= 0.5.0, == 0.5.*

~= 0.5
>= 0.5, == 0.*

为什么Python中的“ pip install”会引发SyntaxError?

问题:为什么Python中的“ pip install”会引发SyntaxError?

我正在尝试使用pip安装软件包。我尝试pip install从Python Shell 运行,但得到了SyntaxError。为什么会出现此错误?如何使用pip安装软件包?

>>> pip install selenium
              ^
SyntaxError: invalid syntax

I’m trying to use pip to install a package. I try to run pip install from the Python shell, but I get a SyntaxError. Why do I get this error? How do I use pip to install the package?

>>> pip install selenium
              ^
SyntaxError: invalid syntax

回答 0

pip是从命令行而不是Python解释器运行的。这是一个安装模块的程序,因此您可以从Python使用它们。安装模块后,即可打开Python shell并执行import selenium

Python Shell不是命令行,而是一个交互式解释器。您在其中键入Python代码,而不是命令。

pip is run from the command line, not the Python interpreter. It is a program that installs modules, so you can use them from Python. Once you have installed the module, then you can open the Python shell and do import selenium.

The Python shell is not a command line, it is an interactive interpreter. You type Python code into it, not commands.


回答 1

使用命令行,而不是Python Shell(Windows中的DOS,PowerShell)。

C:\Program Files\Python2.7\Scripts> pip install XYZ

如果您使用最新的安装程序将Python安装到PATH中,则无需进入该文件夹即可运行pip

Mac或Linux中的终端

$ pip install XYZ

Use the command line, not the Python shell (DOS, PowerShell in Windows).

C:\Program Files\Python2.7\Scripts> pip install XYZ

If you installed Python into your PATH using the latest installers, you don’t need to be in that folder to run pip

Terminal in Mac or Linux

$ pip install XYZ

回答 2

正如@sinoroc所建议的那样,通过pip安装软件包的正确方法是使用单独的进程,因为pip可能会导致关闭线程或可能需要重新启动解释器以加载新安装的软件包,因此这是使用API​​的正确方法:subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'SomeProject'])但是由于Python允许访问内部API,并且您知道自己在使用什么API,无论如何,您可能想使用内部API。如果您使用其他资源(例如https://www.lfd.uci.edu/~gohlke/pythonlibs/)构建自己的GUI软件包管理器

解决方案已过期,而不是拒绝建议更新。请参阅https://github.com/pypa/pip/issues/7498以获取参考。


更新由于点子版本10.x,没有更多get_installed_distributions()main方法import pip 转而使用 import pip._internal as pip

更新ca。v.18 get_installed_distributions()已被删除。相反,您可以使用如下生成器freeze

from pip._internal.operations.freeze import freeze

print([package for package in freeze()])

# eg output ['pip==19.0.3']


如果要在Python解释器中使用pip,请尝试以下操作:

import pip

package_names=['selenium', 'requests'] #packages to install
pip.main(['install'] + package_names + ['--upgrade']) 
# --upgrade to install or update existing packages

如果需要更新每个已安装的软件包,请使用以下命令:

import pip

for i in pip.get_installed_distributions():
    pip.main(['install', i.key, '--upgrade'])

如果要在任何安装失败的情况下停止安装其他软件包,请在一个pip.main([])调用中使用它:

import pip

package_names = [i.key for i in pip.get_installed_distributions()]
pip.main(['install'] + package_names + ['--upgrade'])

注意:使用-r/ --requirement参数从文件列表中安装时,不需要open()函数。

pip.main(['install', '-r', 'filename'])

警告:一些简单的参数--help可能会导致python解释器停止。

好奇心:pip.exe无论如何,通过使用您实际上都在使用python解释器和pip模块。如果您解压缩pip.exe或使用pip3.exepython 2.x或3.x,则里面是相同的单个文件__main__.py

# -*- coding: utf-8 -*-
import re
import sys

from pip import main

if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
    sys.exit(main())

As @sinoroc suggested correct way of installing a package via pip is using separate process since pip may cause closing a thread or may require a restart of interpreter to load new installed package so this is the right way of using the API: subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'SomeProject']) but since Python allows to access internal API and you know what you’re using the API for you may want to use internal API anyway eg. if you’re building own GUI package manager with alternative resourcess like https://www.lfd.uci.edu/~gohlke/pythonlibs/

Following soulution is OUT OF DATE, instead of downvoting suggest updates. see https://github.com/pypa/pip/issues/7498 for reference.


UPDATE: Since pip version 10.x there is no more get_installed_distributions() or main method under import pip instead use import pip._internal as pip.

UPDATE ca. v.18 get_installed_distributions() has been removed. Instead you may use generator freeze like this:

from pip._internal.operations.freeze import freeze

print([package for package in freeze()])

# eg output ['pip==19.0.3']


If you want to use pip inside the Python interpreter, try this:
import pip

package_names=['selenium', 'requests'] #packages to install
pip.main(['install'] + package_names + ['--upgrade']) 
# --upgrade to install or update existing packages

If you need to update every installed package, use following:

import pip

for i in pip.get_installed_distributions():
    pip.main(['install', i.key, '--upgrade'])

If you want to stop installing other packages if any installation fails, use it in one single pip.main([]) call:

import pip

package_names = [i.key for i in pip.get_installed_distributions()]
pip.main(['install'] + package_names + ['--upgrade'])

Note: When you install from list in file with -r / --requirement parameter you do NOT need open() function.

pip.main(['install', '-r', 'filename'])

Warning: Some parameters as simple --help may cause python interpreter to stop.

Curiosity: By using pip.exe you actually use python interpreter and pip module anyway. If you unpack pip.exe or pip3.exe regardless it’s python 2.x or 3.x, inside is the SAME single file __main__.py:

# -*- coding: utf-8 -*-
import re
import sys

from pip import main

if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
    sys.exit(main())

回答 3

要在Python 3.x中运行pip,只需按照Python页面:安装Python模块上的说明进行操作。

python -m pip install SomePackage

请注意,这是从命令行而不是python shell运行的(原始问题中语法错误的原因)。

To run pip in Python 3.x, just follow the instructions on Python’s page: Installing Python Modules.

python -m pip install SomePackage

Note that this is run from the command line and not the python shell (the reason for syntax error in the original question).


回答 4

最初我也遇到过同样的问题,我安装了python,当我运行pip命令时,它常常向我抛出一个错误,如下图所示。

确保在环境变量中添加点路径。对我而言,python和pip的安装路径为::
Python:C:\Users\fhhz\AppData\Local\Programs\Python\Python38\
pip:C:\Users\fhhz\AppData\Local\Programs\Python\Python38\Scripts
这两个路径均已添加到环境变量的路径中。

现在,打开一个新的cmd窗口并键入pip,您应该会看到如下屏幕。

现在输入pip install <<package-name>>。在这里,我正在安装软件包spyder,因此我的命令行语句将为as,pip install spyder然后进入运行屏幕。

我希望我们已经完成了!

Initially I too faced this same problem, I installed python and when I run pip command it used to throw me an error like shown in pic below.

Make Sure pip path is added in environmental variables. For me, the python and pip installation path is::
Python: C:\Users\fhhz\AppData\Local\Programs\Python\Python38\
pip: C:\Users\fhhz\AppData\Local\Programs\Python\Python38\Scripts
Both these paths were added to path in environmental variables.

Now Open a new cmd window and type pip, you should be seeing a screen as below.

Now type pip install <<package-name>>. Here I’m installing package spyder so my command line statement will be as pip install spyder and here goes my running screen..

and I hope we are done with this!!


回答 5

您需要在cmd中而不是在IDLE中键入它。因为如果您要从IDLE安装某些内容,则IDLE不是命令提示符,请输入以下命令

>>>from pip.__main__ import _main as main
>>>main(#args splitted by space in list example:['install', 'requests'])

这就像pip <commands>在终端一样叫点子。这些命令将由您在其中执行的空格分隔。

you need to type it in cmd not in the IDLE. becuse IDLE is not an command prompt if you want to install something from IDLE type this

>>>from pip.__main__ import _main as main
>>>main(#args splitted by space in list example:['install', 'requests'])

this is calling pip like pip <commands> in terminal. The commands will be seperated by spaces that you are doing there to.


回答 6

以编程方式,以下内容当前有效。我看到10.0和所有之后的所有答案,但没有一个对我来说是正确的路径。在Kaggle中,这种方法肯定有效

from pip._internal import main as _main

package_names=['pandas'] #packages to install
_main(['install'] + package_names + ['--upgrade']) 

Programmatically, the following currently works. I see all the answers post 10.0 and all, but none of them are the correct path for me. Within Kaggle for sure, this apporach works

from pip._internal import main as _main

package_names=['pandas'] #packages to install
_main(['install'] + package_names + ['--upgrade']) 

回答 7

尝试使用以下命令升级pip,然后重试

python -m pip install -U pip

Try upgrade pip with the below command and retry

python -m pip install -U pip

pip install-locale.Error:不支持的语言环境设置

问题:pip install-locale.Error:不支持的语言环境设置

完整的堆栈跟踪:

  ~ pip install virtualenv
Traceback (most recent call last):
  File "/usr/bin/pip", line 11, in <module>
    sys.exit(main())
  File "/usr/lib/python3.4/site-packages/pip/__init__.py", line 215, in main
    locale.setlocale(locale.LC_ALL, '')
  File "/usr/lib64/python3.4/locale.py", line 592, in setlocale
    return _setlocale(category, locale)
locale.Error: unsupported locale setting

在同一台服务器上,我成功运行pip install virtualenv了python2.7.x。

现在,我刚刚使用安装了python3.4 curl https://bootstrap.pypa.io/get-pip.py | python3.4

  ~ pip --version
pip 8.1.1 from /usr/lib/python3.4/site-packages (python 3.4)

pip uninstall virtualenv 也会引发相同的错误

Full stacktrace:

➜  ~ pip install virtualenv
Traceback (most recent call last):
  File "/usr/bin/pip", line 11, in <module>
    sys.exit(main())
  File "/usr/lib/python3.4/site-packages/pip/__init__.py", line 215, in main
    locale.setlocale(locale.LC_ALL, '')
  File "/usr/lib64/python3.4/locale.py", line 592, in setlocale
    return _setlocale(category, locale)
locale.Error: unsupported locale setting

On the same server, I successfully ran pip install virtualenv with python 2.7.x.

Now, I’ve just installed python3.4 using curl https://bootstrap.pypa.io/get-pip.py | python3.4.

➜  ~ pip --version
pip 8.1.1 from /usr/lib/python3.4/site-packages (python 3.4)

pip uninstall virtualenv throws the same error too


回答 0

根本原因是:您的环境变量LC_ALL丢失或以某种方式无效

简短答案-

只需运行以下命令:

$ export LC_ALL=C

如果在新的终端窗口中仍然出现错误,请在.bashrc文件底部添加错误。

长答案-

这是我的locale设置:

$ locale
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_COLLATE="C"
LC_MONETARY="C"
LC_MESSAGES="C"
LC_PAPER="C"
LC_NAME="C"
LC_ADDRESS="C"
LC_TELEPHONE="C"
LC_MEASUREMENT="C"
LC_IDENTIFICATION="C"
LC_ALL=C

Python2.7

    $ uname -a
    Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1+deb8u6 (2015-11-09) x86_64 GNU/Linux
    $ python --version
    Python 2.7.9
    $ pip --version
    pip 8.1.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)
    $ unset LC_ALL
    $ pip install virtualenv
    Traceback (most recent call last):
      File "/usr/local/bin/pip", line 11, in <module>
        sys.exit(main())
      File "/usr/local/lib/python2.7/dist-packages/pip/__init__.py", line 215, in main
        locale.setlocale(locale.LC_ALL, '')
      File "/usr/lib/python2.7/locale.py", line 579, in setlocale
        return _setlocale(category, locale)
    locale.Error: unsupported locale setting
    $ export LC_ALL=C
    $ pip install virtualenv
    Requirement already satisfied (use --upgrade to upgrade): virtualenv in /usr/local/lib/python2.7/dist-packages

The root cause is: your environment variable LC_ALL is missing or invalid somehow

Short answer-

just run the following command:

$ export LC_ALL=C

If you keep getting the error in new terminal windows, add it at the bottom of your .bashrc file.

Long answer-

Here is my locale settings:

$ locale
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_COLLATE="C"
LC_MONETARY="C"
LC_MESSAGES="C"
LC_PAPER="C"
LC_NAME="C"
LC_ADDRESS="C"
LC_TELEPHONE="C"
LC_MEASUREMENT="C"
LC_IDENTIFICATION="C"
LC_ALL=C

Python2.7

    $ uname -a
    Linux debian 3.16.0-4-amd64 #1 SMP Debian 3.16.7-ckt11-1+deb8u6 (2015-11-09) x86_64 GNU/Linux
    $ python --version
    Python 2.7.9
    $ pip --version
    pip 8.1.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)
    $ unset LC_ALL
    $ pip install virtualenv
    Traceback (most recent call last):
      File "/usr/local/bin/pip", line 11, in <module>
        sys.exit(main())
      File "/usr/local/lib/python2.7/dist-packages/pip/__init__.py", line 215, in main
        locale.setlocale(locale.LC_ALL, '')
      File "/usr/lib/python2.7/locale.py", line 579, in setlocale
        return _setlocale(category, locale)
    locale.Error: unsupported locale setting
    $ export LC_ALL=C
    $ pip install virtualenv
    Requirement already satisfied (use --upgrade to upgrade): virtualenv in /usr/local/lib/python2.7/dist-packages

回答 1

运行以下命令(它将起作用):

export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"
sudo dpkg-reconfigure locales

Run the following command (it will work):

export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"
sudo dpkg-reconfigure locales

回答 2

有人可能会觉得有用。您可以将这些语言环境设置放在.bashrc文件中,该文件通常位于主目录中。
只需在.bashrc中添加此命令:
export LC_ALL=C
然后键入source .bashrc
Now,例如,当您通过ssh连接时,您无需每次都手动调用此命令。

Someone may find it useful. You could put those locale settings in .bashrc file, which usually located in the home directory.
Just add this command in .bashrc:
export LC_ALL=C
then type source .bashrc
Now you don’t need to call this command manually every time, when you connecting via ssh for example.


回答 3

尽管可以设置导出环境变量的语言环境,但每次启动会话时都必须这样做。以这种方式设置语言环境将永久解决问题:

sudo apt-get install locales
sudo locale-gen en_US.UTF-8
sudo echo "LANG=en_US.UTF-8" > /etc/default/locale

While you can set the locale exporting an env variable, you will have to do that every time you start a session. Setting a locale this way will solve the problem permanently:

sudo apt-get install locales
sudo locale-gen en_US.UTF-8
sudo echo "LANG=en_US.UTF-8" > /etc/default/locale

回答 4

[此答案仅适用于linux平台]

您应该知道的第一件事是,大多数语言环境配置文件的定位路径都可以从localedef --help以下位置获取:

$ localedef --help | tail -n 5
System's directory for character maps : /usr/share/i18n/charmaps
                       repertoire maps: /usr/share/i18n/repertoiremaps
                       locale path    : /usr/lib/locale:/usr/share/i18n
For bug reporting instructions, please see:
<https://bugs.launchpad.net/ubuntu/+source/glibc/+bugs>

看到最后一个/usr/share/i18n?这是您的xx_XX.UTF-8配置文件所在的位置:

$ ls /usr/share/i18n/locales/zh_*
/usr/share/i18n/locales/zh_CN  /usr/share/i18n/locales/zh_HK  /usr/share/i18n/locales/zh_SG  /usr/share/i18n/locales/zh_TW

怎么办 ?我们需要将它们编译为存档二进制文件。一种方式,例如假设我有/usr/share/i18n/locales/en_LOVE,我可以将其添加到编译列表(即/etc/locale-gen文件)中:

$ tail -1 /etc/locale.gen 
en_LOVE.UTF-8 UTF-8

并将其编译为二进制sudo locale-gen

$ sudo locale-gen 
Generating locales (this might take a while)...
  en_AG.UTF-8... done
  en_AU.UTF-8... done
  en_BW.UTF-8... done
  ...
  en_LOVE.UTF-8... done
Generation complete.

且以期望现在更新系统默认的语言环境LANGLC_ALL…等与此update-locale

sudo update-locale LANG=en_LOVE.UTF-8

update-locale实际上还意味着更新此/etc/default/locale文件,该文件将在登录时由系统提供以设置环境变量:

$ head /etc/default/locale 
#  File generated by update-locale
LANG=en_LOVE.UTF-8
LC_NUMERIC="en_US.UTF-8"
...

但是我们可能不想重启才能生效,因此我们可以将其来源到当前shell会话中的环境变量:

$ . /etc/default/locale

怎么sudo dpkg-reconfigure locales样 如果您玩转它,您将知道此命令基本上充当GUI来简化上述步骤,即Edit /etc/locale.gen-> sudo locale-gen->sudo update-locale LANG=en_LOVE.UTF-8

对于python,只要/etc/locale.gen包含该语言环境候选者并locale.gen进行编译,就setlocale(category, locale)可以正常运行locale.Error: unsupoorted locale setting。您可以通过观察文件来检查要在中设置的正确字符串en_US.UTF-8/ ,然后取消注释并根据需要对其进行编译。该文件中不带点的表示正确的字符串是和。en_US/....etcsetlocale()/etc/locale.genzh_CN GB2312zh_CNzh_CN.GB2312

[This answer is target on linux platform only]

The first thing you should know is most of the locale config file located path can be get from localedef --help :

$ localedef --help | tail -n 5
System's directory for character maps : /usr/share/i18n/charmaps
                       repertoire maps: /usr/share/i18n/repertoiremaps
                       locale path    : /usr/lib/locale:/usr/share/i18n
For bug reporting instructions, please see:
<https://bugs.launchpad.net/ubuntu/+source/glibc/+bugs>

See the last /usr/share/i18n ? This is where your xx_XX.UTF-8 config file located:

$ ls /usr/share/i18n/locales/zh_*
/usr/share/i18n/locales/zh_CN  /usr/share/i18n/locales/zh_HK  /usr/share/i18n/locales/zh_SG  /usr/share/i18n/locales/zh_TW

Now what ? We need to compile them into archive binary. One of the way, e.g. assume I have /usr/share/i18n/locales/en_LOVE, I can add it into compile list, i.e. /etc/locale-gen file:

$ tail -1 /etc/locale.gen 
en_LOVE.UTF-8 UTF-8

And compile it to binary with sudo locale-gen:

$ sudo locale-gen 
Generating locales (this might take a while)...
  en_AG.UTF-8... done
  en_AU.UTF-8... done
  en_BW.UTF-8... done
  ...
  en_LOVE.UTF-8... done
Generation complete.

And now update the system default locale with desired LANG, LC_ALL …etc with this update-locale:

sudo update-locale LANG=en_LOVE.UTF-8

update-locale actually also means to update this /etc/default/locale file which will source by system on login to setup environment variables:

$ head /etc/default/locale 
#  File generated by update-locale
LANG=en_LOVE.UTF-8
LC_NUMERIC="en_US.UTF-8"
...

But we may not want to reboot to take effect, so we can just source it to environment variable in current shell session:

$ . /etc/default/locale

How about sudo dpkg-reconfigure locales ? If you play around it you will know this command basically act as GUI to simplify the above steps, i.e. Edit /etc/locale.gen -> sudo locale-gen -> sudo update-locale LANG=en_LOVE.UTF-8

For python, as long as /etc/locale.gen contains that locale candidate and locale.gen get compiled, setlocale(category, locale) should work without throws locale.Error: unsupoorted locale setting. You can check the correct string en_US.UTF-8/en_US/....etc to be set in setlocale(), by observing /etc/locale.gen file, and then uncomment and compile it as desired. zh_CN GB2312 without dot in that file means the correct string is zh_CN and zh_CN.GB2312.


回答 5

对于Dockerfile,这对我有用:

RUN locale-gen en_US.UTF-8  
ENV LANG en_US.UTF-8  
ENV LANGUAGE en_US:en  
ENV LC_ALL en_US.UTF-8  

如何安装locale-gen?

docker ubuntu / bin / sh:1:locale-gen:找不到

For Dockerfile, this works for me:

RUN locale-gen en_US.UTF-8  
ENV LANG en_US.UTF-8  
ENV LANGUAGE en_US:en  
ENV LC_ALL en_US.UTF-8  

How to install locale-gen?

docker ubuntu /bin/sh: 1: locale-gen: not found


回答 6

我有同样的问题,对我没有用"export LC_ALL=c"

尝试export LC_ALL="en_US.UTF-8"(它将起作用)。

I had the same problem, and "export LC_ALL=c" didn’t work for me.

Try export LC_ALL="en_US.UTF-8" (it will work).


回答 7

该错误消息表示语言环境设置有问题。要解决此问题(如其他答案所示),您需要修改语言环境。

在Mac OS X Sierra上,我发现最好的方法是~/bash_profile按如下所示修改文件:

export LANG="en_US.UTF-8"
export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"

除非您使用以下命令重新加载bash配置文件,否则此更改在当前cli会话中不会立即显现source ~/.bash_profile

这个答案非常接近我发布给其他非相同,非重复的问题(即与pipenv不相关)的答案,但是碰巧需要相同的解决方案。

致主持人:尊敬;由于这个原因,我以前的答案被删除了,但是我觉得这有点愚蠢,因为实际上,无论何时只要错误是“语言环境问题”,这个答案都适用…但是可能会触发多种不同的情况,语言和环境该错误。

因此,A)将问题标记为重复项是没有意义的,而B)调整答案也没有意义,因为解决方法非常简单,在每种情况下都是相同的,并且无法从修饰中受益。

The error message indicates a problem with the locale setting. To fix this as indicated by other answers you need to modify your locale.

On Mac OS X Sierra I found that the best way to do this was to modify the ~/bash_profile file as follows:

export LANG="en_US.UTF-8"
export LC_ALL="en_US.UTF-8"
export LC_CTYPE="en_US.UTF-8"

This change will not be immediately evident in your current cli session unless you reload the bash profile by using: source ~/.bash_profile.

This answer is pretty close to answers that I’ve posted to other non-identical, non-duplicate questions (i.e. not related to pipenv) but which happen to require the same solution.

To the moderator: With respect; my previous answer got deleted for this reason but I feel that was a bit silly because really this answer applies almost whenever the error is “problem with locale”… but there are a number of differing situations, languages, and environments which could trigger that error.

Thus it A) doesn’t make sense to mark the questions as duplicates and B) doesn’t make sense to tailor the answer either because the fix is very simple, is the same in each case and does not benefit from ornamentation.


回答 8

Ubuntu:

$ sudo vi /etc/default/locale

在文件末尾添加以下设置。

LC_ALL = en_US.UTF-8

Ubuntu:

$ sudo vi /etc/default/locale

Add below setting at the end of file.

LC_ALL = en_US.UTF-8


如何修复“ ImportError:无法导入名称IncompleteRead”?

问题:如何修复“ ImportError:无法导入名称IncompleteRead”?

当我尝试使用pip或安装任何内容时pip3,我得到:

$ sudo pip3 install python3-tk
Traceback (most recent call last):
  File "/usr/bin/pip3", line 9, in <module>
    load_entry_point('pip==1.5.6', 'console_scripts', 'pip3')()
  File "/usr/lib/python3/dist-packages/pkg_resources.py", line 356, in load_entry_point
    return get_distribution(dist).load_entry_point(group, name)
  File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2476, in load_entry_point
    return ep.load()
  File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2190, in load
    ['__name__'])
  File "/usr/lib/python3/dist-packages/pip/__init__.py", line 61, in <module>
    from pip.vcs import git, mercurial, subversion, bazaar  # noqa
  File "/usr/lib/python3/dist-packages/pip/vcs/mercurial.py", line 9, in <module>
    from pip.download import path_to_url
  File "/usr/lib/python3/dist-packages/pip/download.py", line 25, in <module>
    from requests.compat import IncompleteRead
ImportError: cannot import name 'IncompleteRead'

我有一个Ubuntu 14.10系统。

我该如何解决这个问题?

When I try to install anything with pip or pip3, I get:

$ sudo pip3 install python3-tk
Traceback (most recent call last):
  File "/usr/bin/pip3", line 9, in <module>
    load_entry_point('pip==1.5.6', 'console_scripts', 'pip3')()
  File "/usr/lib/python3/dist-packages/pkg_resources.py", line 356, in load_entry_point
    return get_distribution(dist).load_entry_point(group, name)
  File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2476, in load_entry_point
    return ep.load()
  File "/usr/lib/python3/dist-packages/pkg_resources.py", line 2190, in load
    ['__name__'])
  File "/usr/lib/python3/dist-packages/pip/__init__.py", line 61, in <module>
    from pip.vcs import git, mercurial, subversion, bazaar  # noqa
  File "/usr/lib/python3/dist-packages/pip/vcs/mercurial.py", line 9, in <module>
    from pip.download import path_to_url
  File "/usr/lib/python3/dist-packages/pip/download.py", line 25, in <module>
    from requests.compat import IncompleteRead
ImportError: cannot import name 'IncompleteRead'

I have a Ubuntu 14.10 system.

How can I fix this problem?


回答 0

尽管以前的答案可能是原因,但此片段为我解决了问题(在中Ubuntu 14.04):

首先从程序包管理器中删除程序包:

# apt-get remove python-pip

然后并行安装最新版本:

# easy_install pip

(感谢@ Aufziehvogel,@ JunchaoGu)

While this previous answer might be the reason, this snipped worked for me as a solution (in Ubuntu 14.04):

First remove the package from the package manager:

# apt-get remove python-pip

And then install the latest version by side:

# easy_install pip

(thanks to @Aufziehvogel, @JunchaoGu)


回答 1

此问题是由您的pip安装与请求安装之间的不匹配引起的。

根据要求,版本2.4.0 requests.compat.IncompleteRead 已被删除。较旧版本的点子(例如从2014年7月开始)仍然依赖IncompleteRead。在当前版本的pip中,IncompleteRead已删除的导入。

因此,应该怪的是:

  • 请求,以太快地删除公共API
  • Ubuntu的更新点太慢

您可以通过通过Ubuntu更新pip(如果有较新版本)或通过在Ubuntu之外安装pip来解决此问题。

This problem is caused by a mismatch between your pip installation and your requests installation.

As of requests version 2.4.0 requests.compat.IncompleteRead has been removed. Older versions of pip, e.g. from July 2014, still relied on IncompleteRead. In the current version of pip, the import of IncompleteRead has been removed.

So the one to blame is either:

  • requests, for removing public API too quickly
  • Ubuntu for updating pip too slowly

You can solve this issue, by either updating pip via Ubuntu (if there is a newer version) or by installing pip aside from Ubuntu.


回答 2

要修复pip3(在Ubuntu 14.10上工作):

easy_install3 -U pip

For fixing pip3 (worked on Ubuntu 14.10):

easy_install3 -U pip

回答 3

或者您可以删除所有requests

例如:

  • rm -rf /usr/local/lib/python2.7/dist-packages/requests*

Or you can remove all requests.

For example:

  • rm -rf /usr/local/lib/python2.7/dist-packages/requests*

回答 4

在Ubuntu 14.04上,我通过使用pip安装引导脚本解决了此问题,如文档所述

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

对于开发环境来说,这是一个好的解决方案。

On Ubuntu 14.04 I resolved this by using the pip installation bootstrap script, as described in the documentation

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

That’s an OK solution for a development environment.


回答 5

问题是Python模块requests。可以通过固定

$ sudo apt-get purge python-requests
[now requests and pip gets deinstalled]
$ sudo apt-get install python-requests python-pip

如果您在Python 3中遇到此问题,则必须编写python3而不是python

The problem is the Python module requests. It can be fixed by

$ sudo apt-get purge python-requests
[now requests and pip gets deinstalled]
$ sudo apt-get install python-requests python-pip

If you have this problem with Python 3, you have to write python3 instead of python.


回答 6

这应该为您工作。请遵循以下简单步骤。

首先,让我们删除已经安装的点子,这样就不会引起任何错误。

打开终端。

类型:sudo apt-get remove python-pip

它会删除已安装的点子。

方法1

步骤:1 sudo easy_install -U pip

它将安装pip最新版本。

并将返回其地址:已安装/usr/local/lib/python2.7/dist-packages/pip-6.1.1-py2.7.egg

要么

方法2

步骤:1转到此链接

步骤:2右键单击>>另存为..,名称为get-pip.py。

步骤:3使用:cd转到与get-pip.py文件相同的目录

步骤:4使用:sudo python get-pip.py

它将安装pip最新版本。

要么

方法3

步骤:1使用:sudo apt-get install python-pip

它将安装pip最新版本。

This should work for you. Follow these simple steps.

First, let’s remove the pip which is already installed so it won’t cause any error.

Open Terminal.

Type: sudo apt-get remove python-pip

It removes pip that is already installed.

Method-1

Step: 1 sudo easy_install -U pip

It will install pip latest version.

And will return its address: Installed /usr/local/lib/python2.7/dist-packages/pip-6.1.1-py2.7.egg

or

Method-2

Step: 1 go to this link.

Step: 2 Right click >> Save as.. with name get-pip.py .

Step: 3 use: cd to go to the same directory as your get-pip.py file

Step: 4 use: sudo python get-pip.py

It will install pip latest version.

or

Method-3

Step: 1 use: sudo apt-get install python-pip

It will install pip latest version.


回答 7

只需运行即可easy_install -U pip解决我的问题。

Simply running easy_install -U pip resolved my problem.


回答 8

请检查是否你有一个旧版本的requests坐在你~/.local/lib/python2.7/site-packages/并删除它,如果它是(以反映您的Python版本的变化路径)的情况下。这为我解决了这个问题。

Check wether you have an older version of requests sitting in your ~/.local/lib/python2.7/site-packages/ and remove it if it is the case (change path to reflect your python version). This solved the issue for me.


回答 9

我在ubuntu上的pip版本建议:

  pip install --upgrade pip

My version of pip on ubuntu suggests:

  pip install --upgrade pip

回答 10

在Windows中,这是通过管理提示进行的:

  • 删除 C:\Python27\Lib\site-packages\requests*
  • easy_install requests==2.3
  • pip install --upgrade pip
  • pip install --upgrade requests

In Windows, this worked from an administrative prompt:

  • Delete C:\Python27\Lib\site-packages\requests*
  • easy_install requests==2.3
  • pip install --upgrade pip
  • pip install --upgrade requests

回答 11

我尝试了所有答案,但无法成功。

做到了并且工作了

sudo apt-get purge python-virtualenv
sudo pip install pip -U

之后,我用pip安装了virtualenv

sudo pip install virtualenv

我构建了正在使用的virtualenv,并且该软件包易于安装。通过使用进入virtualenv source /bin/activate 并尝试安装您的软件包,例如:

pip install terminado

它为我工作,尽管我使用的是python2.7而不是python3

I tried with every answer avobe, but couldn’t make it.

Did this and worked

sudo apt-get purge python-virtualenv
sudo pip install pip -U

After that I just installed virtualenv with pip

sudo pip install virtualenv

I built the virtualenv that I was working on and the package was installed easily. Get into the virtualenv by using source /bin/activate and try to install your package, for example:

pip install terminado

It worked for me, although I was using python2.7 not python3


回答 12

检查是否在任何终端窗口中都存在python解释器。如果是这样,请杀死它并尝试sudo pip对我有用。

Check if have a python interpreter alive in any of the terminal windows. If so kill it and try sudo pip which worked for me.


回答 13

  1. sudo apt-get删除python-pip
  2. sudo easy_install请求== 2.3.0
  3. 须藤apt-get install python-pip
  1. sudo apt-get remove python-pip
  2. sudo easy_install requests==2.3.0
  3. sudo apt-get install python-pip

回答 14

您可以从以下页面手动下载最新软件包:

然后,通过运行安装它dpkg

dpkg -i *.deb

You can download recent packages manually from these pages:

Then, install it by running dpkg:

dpkg -i *.deb

回答 15

对于CentOS,我使用了它,并且它起作用了,请使用以下命令:

sudo pip uninstall requests
sudo pip uninstall urllib3
sudo yum remove python-urllib3
sudo yum remove python-requests

(确认已删除所有这些库)

sudo yum install python-urllib3
sudo yum install python-requests

For CentOS I used this and it worked please use the following commands:

sudo pip uninstall requests
sudo pip uninstall urllib3
sudo yum remove python-urllib3
sudo yum remove python-requests

(confirm that all those libraries have been removed)

sudo yum install python-urllib3
sudo yum install python-requests

setuptools setup.py文件中install_requires kwarg的参考requirements.txt

问题:setuptools setup.py文件中install_requires kwarg的参考requirements.txt

我有一个requirements.txt与Travis-CI一起使用的文件。在requirements.txt和中都重复要求似乎很愚蠢setup.py,所以我希望将文件句柄传递给install_requiresin setuptools.setup

这可能吗?如果是这样,我应该怎么做呢?

这是我的requirements.txt文件:

guessit>=0.5.2
tvdb_api>=1.8.2
hachoir-metadata>=1.3.3
hachoir-core>=1.3.3
hachoir-parser>=1.3.4

I have a requirements.txt file that I’m using with Travis-CI. It seems silly to duplicate the requirements in both requirements.txt and setup.py, so I was hoping to pass a file handle to the install_requires kwarg in setuptools.setup.

Is this possible? If so, how should I go about doing it?

Here is my requirements.txt file:

guessit>=0.5.2
tvdb_api>=1.8.2
hachoir-metadata>=1.3.3
hachoir-core>=1.3.3
hachoir-parser>=1.3.4

回答 0

你可以翻转它周围,列表中的依赖关系setup.py,并有单字符-点.-在requirements.txt代替。


另外,即使不建议使用,也可以requirements.txt通过以下技巧(通过进行测试pip 9.0.1)来分析文件(如果它没有通过URL引用任何外部要求):

install_reqs = parse_requirements('requirements.txt', session='hack')

但是,这不会过滤环境标记


在pip的旧版本中(更具体地讲,版本早于6.0),可以使用公共API来实现此目的。需求文件可以包含注释(#),也可以包含其他一些文件(--requirement-r)。因此,如果您确实要解析a requirements.txt,则可以使用pip解析器:

from pip.req import parse_requirements

# parse_requirements() returns generator of pip.req.InstallRequirement objects
install_reqs = parse_requirements(<requirements_path>)

# reqs is a list of requirement
# e.g. ['django==1.5.1', 'mezzanine==1.4.6']
reqs = [str(ir.req) for ir in install_reqs]

setup(
    ...
    install_requires=reqs
)

You can flip it around and list the dependencies in setup.py and have a single character — a dot . — in requirements.txt instead.


Alternatively, even if not advised, it is still possible to parse the requirements.txt file (if it doesn’t refer any external requirements by URL) with the following hack (tested with pip 9.0.1):

install_reqs = parse_requirements('requirements.txt', session='hack')

This doesn’t filter environment markers though.


In old versions of pip, more specifically older than 6.0, there is a public API that can be used to achieve this. A requirement file can contain comments (#) and can include some other files (--requirement or -r). Thus, if you really want to parse a requirements.txt you can use the pip parser:

from pip.req import parse_requirements

# parse_requirements() returns generator of pip.req.InstallRequirement objects
install_reqs = parse_requirements(<requirements_path>)

# reqs is a list of requirement
# e.g. ['django==1.5.1', 'mezzanine==1.4.6']
reqs = [str(ir.req) for ir in install_reqs]

setup(
    ...
    install_requires=reqs
)

回答 1

在它面前,它似乎是requirements.txtsetup.py是愚蠢的重复,而是要明白,虽然形式是相似的,预定的功能有很大的不同是很重要的。

程序包作者在指定依赖项时的目的是说:“无论您在何处安装此程序包,都需要其他程序包,此程序包才能工作。”

相反,部署作者(可能在不同时间是同一个人)的工作不同,他们说:“这是我们收集并测试过的软件包列表,现在我需要安装”。

软件包作者针对各种各样的场景进行了写作,因为他们将自己的工作放到那里以他们可能不了解的方式使用,并且无法知道将在软件包旁边安装哪些软件包。为了成为一个好邻居并避免依赖版本与其他软件包冲突,他们需要指定尽可能广泛的依赖版本。这就是install_requiressetup.py做。

部署作者写的是一个非常不同,非常特定的目标:在特定计算机上安装的已安装应用程序或服务的单个实例。为了精确控制部署,并确保测试和部署了正确的软件包,部署作者必须指定要安装的每个软件包的确切版本和源位置,包括依赖关系和依赖关系。使用此规范,可以将部署重复地应用于多台计算机,或在测试计算机上进行测试,并且部署作者可以确信每次都部署了相同的程序包。这就是一个requirements.txt

因此,您可以看到,尽管它们看起来都像是一个很大的软件包和版本列表,但是这两件事的工作却截然不同。而且混合起来并弄错它肯定很容易!但是考虑这一点的正确方法是,requirements.txt对所有各种setup.py软件包文件中的需求提出的“问题”进行“解答” 。而不是手工编写,它通常是通过告诉pip查看setup.py一组所需软件包中的所有文件,找到它认为符合所有要求的一组软件包,然后在安装后冻结来生成的。 ”将软件包列表转换为文本文件(这就是pip freeze名称的来源)。

因此,外卖:

  • setup.py应该声明仍然可用的最宽松的依赖版本。它的工作是说特定的软件包可以使用什么。
  • requirements.txt是一个定义整个安装工作​​的部署清单,不应将其视为与任何一个软件包捆绑在一起。它的工作是为完成部署工作而声明所有必要软件包的详尽清单。
  • 由于这两件事具有如此不同的内容和存在的原因,因此简单地将其中一项复制到另一项中是不可行的。

参考文献:

On the face of it, it does seem that requirements.txt and setup.py are silly duplicates, but it’s important to understand that while the form is similar, the intended function is very different.

The goal of a package author, when specifying dependencies, is to say “wherever you install this package, these are the other packages you need, in order for this package to work.”

In contrast, the deployment author (which may be the same person at a different time) has a different job, in that they say “here’s the list of packages that we’ve gathered together and tested and that I now need to install”.

The package author writes for a wide variety of scenarios, because they’re putting their work out there to be used in ways they may not know about, and have no way of knowing what packages will be installed alongside their package. In order to be a good neighbor and avoid dependency version conflicts with other packages, they need to specify as wide a range of dependency versions as can possibly work. This is what install_requires in setup.py does.

The deployment author writes for a very different, very specific goal: a single instance of an installed application or service, installed on a particular computer. In order to precisely control a deployment, and be sure that the right packages are tested and deployed, the deployment author must specify the exact version and source-location of every package to be installed, including dependencies and dependency’s dependencies. With this spec, a deployment can be repeatably applied to several machines, or tested on a test machine, and the deployment author can be confident that the same packages are deployed every time. This is what a requirements.txt does.

So you can see that, while they both look like a big list of packages and versions, these two things have very different jobs. And it’s definitely easy to mix this up and get it wrong! But the right way to think about this is that requirements.txt is an “answer” to the “question” posed by the requirements in all the various setup.py package files. Rather than write it by hand, it’s often generated by telling pip to look at all the setup.py files in a set of desired packages, find a set of packages that it thinks fits all the requirements, and then, after they’re installed, “freeze” that list of packages into a text file (this is where the pip freeze name comes from).

So the takeaway:

  • setup.py should declare the loosest possible dependency versions that are still workable. Its job is to say what a particular package can work with.
  • requirements.txt is a deployment manifest that defines an entire installation job, and shouldn’t be thought of as tied to any one package. Its job is to declare an exhaustive list of all the necessary packages to make a deployment work.
  • Because these two things have such different content and reasons for existing, it’s not feasible to simply copy one into the other.

References:


回答 2

它不能使用文件句柄。该install_requires参数可以仅仅是一个字符串或字符串列表

当然,您可以在设置脚本中读取文件,并将其作为字符串列表传递给install_requires

import os
from setuptools import setup

with open('requirements.txt') as f:
    required = f.read().splitlines()

setup(...
install_requires=required,
...)

It can’t take a file handle. The install_requires argument can only be a string or a list of strings.

You can, of course, read your file in the setup script and pass it as a list of strings to install_requires.

import os
from setuptools import setup

with open('requirements.txt') as f:
    required = f.read().splitlines()

setup(...
install_requires=required,
...)

回答 3

需求文件使用扩展的pip格式,仅当您需要setup.py用更严格的约束来补充时(例如,指定某些依赖项必须来自的确切网址,或pip freeze将整个包冻结为已知工作的输出),该文件才有用版本。如果您不需要额外的约束,请仅使用setup.py。如果您觉得确实需要运送requirements.txt,可以将其放在一行中:

.

这将是有效的,并且完全引用setup.py同一目录中的内容。

Requirements files use an expanded pip format, which is only useful if you need to complement your setup.py with stronger constraints, for example specifying the exact urls some of the dependencies must come from, or the output of pip freeze to freeze the entire package set to known-working versions. If you don’t need the extra constraints, use only a setup.py. If you feel like you really need to ship a requirements.txt anyway, you can make it a single line:

.

It will be valid and refer exactly to the contents of the setup.py that is in the same directory.


回答 4

虽然不是该问题的确切答案,但我还是推荐Donald Stufft的博客文章,网址https://caremad.io/2013/07/setup-vs-requirement/,以很好地解决这个问题。我一直在使用它取得巨大的成功。

简而言之, requirements.txt这不是setup.py替代方案,而是部署的补充。在中保持适当的软件包依赖关系抽象setup.py。设置一个requirements.txt或多个’em以获取特定版本的软件包依赖项以进行开发,测试或生产。

例如,包含在回购下的软件包中 deps/

# fetch specific dependencies
--no-index
--find-links deps/

# install package
# NOTE: -e . for editable mode
.

pip执行包的程序setup.py并安装在中声明的依赖项的特定版本install_requires。没有重复性,并且保留了两个工件的目的。

While not an exact answer to the question, I recommend Donald Stufft’s blog post at https://caremad.io/2013/07/setup-vs-requirement/ for a good take on this problem. I’ve been using it to great success.

In short, requirements.txt is not a setup.py alternative, but a deployment complement. Keep an appropriate abstraction of package dependencies in setup.py. Set requirements.txt or more of ’em to fetch specific versions of package dependencies for development, testing, or production.

E.g. with packages included in the repo under deps/:

# fetch specific dependencies
--no-index
--find-links deps/

# install package
# NOTE: -e . for editable mode
.

pip executes package’s setup.py and installs the specific versions of dependencies declared in install_requires. There’s no duplicity and the purpose of both artifacts is preserved.


回答 5

使用parse_requirements存在问题,因为未公开记录和支持pip API。在第1.6点中,该功能实际上正在移动,因此该功能的现有用途可能会中断。

消除setup.py和之间重复的一种更可靠的方法requirements.txt是特定于您的依赖项setup.py,然后将其-e .放入requirements.txt文件中。从一个有些信息pip为什么这是去一个更好的办法开发人员可以在这里找到:https://caremad.io/blog/setup-vs-requirement/

Using parse_requirements is problematic because the pip API isn’t publicly documented and supported. In pip 1.6, that function is actually moving, so existing uses of it are likely to break.

A more reliable way to eliminate duplication between setup.py and requirements.txt is to specific your dependencies in setup.py and then put -e . into your requirements.txt file. Some information from one of the pip developers about why that’s a better way to go is available here: https://caremad.io/blog/setup-vs-requirement/


回答 6

以上大多数其他答案不适用于当前版本的pip API。这是使用当前版本的pip(在撰写本文时为6.0.8,在7.1.2中也可以使用。)的正确方法。您可以使用pip -V检查版本。

from pip.req import parse_requirements
from pip.download import PipSession

install_reqs = parse_requirements(<requirements_path>, session=PipSession())

reqs = [str(ir.req) for ir in install_reqs]

setup(
    ...
    install_requires=reqs
    ....
)

*正确,因为这是对当前点使用parse_requirements的方式。仍然可能不是最好的方法,因为正如上面的海报所述,pip并没有真正维护API。

Most of the other answers above don’t work with the current version of pip’s API. Here is the correct* way to do it with the current version of pip (6.0.8 at the time of writing, also worked in 7.1.2. You can check your version with pip -V).

from pip.req import parse_requirements
from pip.download import PipSession

install_reqs = parse_requirements(<requirements_path>, session=PipSession())

reqs = [str(ir.req) for ir in install_reqs]

setup(
    ...
    install_requires=reqs
    ....
)

* Correct, in that it is the way to use parse_requirements with the current pip. It still probably isn’t the best way to do it, since, as posters above said, pip doesn’t really maintain an API.


回答 7

在Travis中安装当前软件包。这样可以避免使用requirements.txt文件。例如:

language: python
python:
  - "2.7"
  - "2.6"
install:
  - pip install -q -e .
script:
  - python runtests.py

Install the current package in Travis. This avoids the use of a requirements.txt file. For example:

language: python
python:
  - "2.7"
  - "2.6"
install:
  - pip install -q -e .
script:
  - python runtests.py

回答 8

from pip.req import parse_requirements 不适用于我,我认为它适用于我的requirements.txt中的空白行,但是此功能确实有效

def parse_requirements(requirements):
    with open(requirements) as f:
        return [l.strip('\n') for l in f if l.strip('\n') and not l.startswith('#')]

reqs = parse_requirements(<requirements_path>)

setup(
    ...
    install_requires=reqs,
    ...
)

from pip.req import parse_requirements did not work for me and I think it’s for the blank lines in my requirements.txt, but this function does work

def parse_requirements(requirements):
    with open(requirements) as f:
        return [l.strip('\n') for l in f if l.strip('\n') and not l.startswith('#')]

reqs = parse_requirements(<requirements_path>)

setup(
    ...
    install_requires=reqs,
    ...
)

回答 9

如果您不想强迫用户安装pip,可以使用以下方法模拟其行为:

import sys

from os import path as p

try:
    from setuptools import setup, find_packages
except ImportError:
    from distutils.core import setup, find_packages


def read(filename, parent=None):
    parent = (parent or __file__)

    try:
        with open(p.join(p.dirname(parent), filename)) as f:
            return f.read()
    except IOError:
        return ''


def parse_requirements(filename, parent=None):
    parent = (parent or __file__)
    filepath = p.join(p.dirname(parent), filename)
    content = read(filename, parent)

    for line_number, line in enumerate(content.splitlines(), 1):
        candidate = line.strip()

        if candidate.startswith('-r'):
            for item in parse_requirements(candidate[2:].strip(), filepath):
                yield item
        else:
            yield candidate

setup(
...
    install_requires=list(parse_requirements('requirements.txt'))
)

If you don’t want to force your users to install pip, you can emulate its behavior with this:

import sys

from os import path as p

try:
    from setuptools import setup, find_packages
except ImportError:
    from distutils.core import setup, find_packages


def read(filename, parent=None):
    parent = (parent or __file__)

    try:
        with open(p.join(p.dirname(parent), filename)) as f:
            return f.read()
    except IOError:
        return ''


def parse_requirements(filename, parent=None):
    parent = (parent or __file__)
    filepath = p.join(p.dirname(parent), filename)
    content = read(filename, parent)

    for line_number, line in enumerate(content.splitlines(), 1):
        candidate = line.strip()

        if candidate.startswith('-r'):
            for item in parse_requirements(candidate[2:].strip(), filepath):
                yield item
        else:
            yield candidate

setup(
...
    install_requires=list(parse_requirements('requirements.txt'))
)

回答 10

以下界面在点10中已弃用:

from pip.req import parse_requirements
from pip.download import PipSession

所以我将其切换为简单的文本解析:

with open('requirements.txt', 'r') as f:
    install_reqs = [
        s for s in [
            line.split('#', 1)[0].strip(' \t\n') for line in f
        ] if s != ''
    ]

The following interface became deprecated in pip 10:

from pip.req import parse_requirements
from pip.download import PipSession

So I switched it just to simple text parsing:

with open('requirements.txt', 'r') as f:
    install_reqs = [
        s for s in [
            line.split('#', 1)[0].strip(' \t\n') for line in f
        ] if s != ''
    ]

回答 11

这种简单的方法从中读取需求文件setup.py。这是Dmitiry S.答案的变形。此答案仅与Python 3.6+兼容。

DSrequirements.txt可以记录与特定的版本号具体要求,而setup.py可以记录与宽松版范围抽象的要求。

以下是我的摘录setup.py

import distutils.text_file
from pathlib import Path
from typing import List

def _parse_requirements(filename: str) -> List[str]:
    """Return requirements from requirements file."""
    # Ref: https://stackoverflow.com/a/42033122/
    return distutils.text_file.TextFile(filename=str(Path(__file__).with_name(filename))).readlines()

setup(...
      install_requires=_parse_requirements('requirements.txt'),
   ...)

请注意,这distutils.text_file.TextFile将删除注释。而且,根据我的经验,您显然不需要采取任何特殊步骤将需求文件捆绑在一起。

This simple approach reads the requirements file from setup.py. It is a variation of the answer by Dmitiry S.. This answer is compatible only with Python 3.6+.

Per D.S., requirements.txt can document concrete requirements with specific version numbers, whereas setup.py can document abstract requirements with loose version ranges.

Below is an excerpt of my setup.py.

import distutils.text_file
from pathlib import Path
from typing import List

def _parse_requirements(filename: str) -> List[str]:
    """Return requirements from requirements file."""
    # Ref: https://stackoverflow.com/a/42033122/
    return distutils.text_file.TextFile(filename=str(Path(__file__).with_name(filename))).readlines()

setup(...
      install_requires=_parse_requirements('requirements.txt'),
   ...)

Note that distutils.text_file.TextFile will strip comments. Also, per my experience, you apparently do not need to take any special step to bundle in the requirements file.


回答 12

小心parse_requirements行为!

请注意,pip.req.parse_requirements下划线将变为短划线。在发现它之前,这让我很生气。示例说明:

from pip.req import parse_requirements  # tested with v.1.4.1

reqs = '''
example_with_underscores
example-with-dashes
'''

with open('requirements.txt', 'w') as f:
    f.write(reqs)

req_deps = parse_requirements('requirements.txt')
result = [str(ir.req) for ir in req_deps if ir.req is not None]
print result

产生

['example-with-underscores', 'example-with-dashes']

BEWARE OF parse_requirements BEHAVIOUR!

Please note that pip.req.parse_requirements will change underscores to dashes. This was enraging me for a few days before I discovered it. Example demonstrating:

from pip.req import parse_requirements  # tested with v.1.4.1

reqs = '''
example_with_underscores
example-with-dashes
'''

with open('requirements.txt', 'w') as f:
    f.write(reqs)

req_deps = parse_requirements('requirements.txt')
result = [str(ir.req) for ir in req_deps if ir.req is not None]
print result

produces

['example-with-underscores', 'example-with-dashes']

回答 13

我为此创建了一个可重用的函数。它实际上解析需求文件的整个目录,并将它们设置为extras_require。

最新的始终可用在这里:https : //gist.github.com/akatrevorjay/293c26fefa24a7b812f5

import glob
import itertools
import os

# This is getting ridiculous
try:
    from pip._internal.req import parse_requirements
    from pip._internal.network.session import PipSession
except ImportError:
    try:
        from pip._internal.req import parse_requirements
        from pip._internal.download import PipSession
    except ImportError:
        from pip.req import parse_requirements
        from pip.download import PipSession


def setup_requirements(
        patterns=[
            'requirements.txt', 'requirements/*.txt', 'requirements/*.pip'
        ],
        combine=True):
    """
    Parse a glob of requirements and return a dictionary of setup() options.
    Create a dictionary that holds your options to setup() and update it using this.
    Pass that as kwargs into setup(), viola

    Any files that are not a standard option name (ie install, tests, setup) are added to extras_require with their
    basename minus ext. An extra key is added to extras_require: 'all', that contains all distinct reqs combined.

    Keep in mind all literally contains `all` packages in your extras.
    This means if you have conflicting packages across your extras, then you're going to have a bad time.
    (don't use all in these cases.)

    If you're running this for a Docker build, set `combine=True`.
    This will set `install_requires` to all distinct reqs combined.

    Example:

    >>> import setuptools
    >>> _conf = dict(
    ...     name='mainline',
    ...     version='0.0.1',
    ...     description='Mainline',
    ...     author='Trevor Joynson <github@trevor.joynson,io>',
    ...     url='https://trevor.joynson.io',
    ...     namespace_packages=['mainline'],
    ...     packages=setuptools.find_packages(),
    ...     zip_safe=False,
    ...     include_package_data=True,
    ... )
    >>> _conf.update(setup_requirements())
    >>> # setuptools.setup(**_conf)

    :param str pattern: Glob pattern to find requirements files
    :param bool combine: Set True to set install_requires to extras_require['all']
    :return dict: Dictionary of parsed setup() options
    """
    session = PipSession()

    # Handle setuptools insanity
    key_map = {
        'requirements': 'install_requires',
        'install': 'install_requires',
        'tests': 'tests_require',
        'setup': 'setup_requires',
    }
    ret = {v: set() for v in key_map.values()}
    extras = ret['extras_require'] = {}
    all_reqs = set()

    files = [glob.glob(pat) for pat in patterns]
    files = itertools.chain(*files)

    for full_fn in files:
        # Parse
        reqs = {
            str(r.req)
            for r in parse_requirements(full_fn, session=session)
            # Must match env marker, eg:
            #   yarl ; python_version >= '3.0'
            if r.match_markers()
        }
        all_reqs.update(reqs)

        # Add in the right section
        fn = os.path.basename(full_fn)
        barefn, _ = os.path.splitext(fn)
        key = key_map.get(barefn)

        if key:
            ret[key].update(reqs)
            extras[key] = reqs

        extras[barefn] = reqs

    if 'all' not in extras:
        extras['all'] = list(all_reqs)

    if combine:
        extras['install'] = ret['install_requires']
        ret['install_requires'] = list(all_reqs)

    def _listify(dikt):
        ret = {}

        for k, v in dikt.items():
            if isinstance(v, set):
                v = list(v)
            elif isinstance(v, dict):
                v = _listify(v)
            ret[k] = v

        return ret

    ret = _listify(ret)

    return ret


__all__ = ['setup_requirements']

if __name__ == '__main__':
    reqs = setup_requirements()
    print(reqs)

I created a reusable function for this. It actually parses an entire directory of requirements files and sets them to extras_require.

Latest always available here: https://gist.github.com/akatrevorjay/293c26fefa24a7b812f5

import glob
import itertools
import os

# This is getting ridiculous
try:
    from pip._internal.req import parse_requirements
    from pip._internal.network.session import PipSession
except ImportError:
    try:
        from pip._internal.req import parse_requirements
        from pip._internal.download import PipSession
    except ImportError:
        from pip.req import parse_requirements
        from pip.download import PipSession


def setup_requirements(
        patterns=[
            'requirements.txt', 'requirements/*.txt', 'requirements/*.pip'
        ],
        combine=True):
    """
    Parse a glob of requirements and return a dictionary of setup() options.
    Create a dictionary that holds your options to setup() and update it using this.
    Pass that as kwargs into setup(), viola

    Any files that are not a standard option name (ie install, tests, setup) are added to extras_require with their
    basename minus ext. An extra key is added to extras_require: 'all', that contains all distinct reqs combined.

    Keep in mind all literally contains `all` packages in your extras.
    This means if you have conflicting packages across your extras, then you're going to have a bad time.
    (don't use all in these cases.)

    If you're running this for a Docker build, set `combine=True`.
    This will set `install_requires` to all distinct reqs combined.

    Example:

    >>> import setuptools
    >>> _conf = dict(
    ...     name='mainline',
    ...     version='0.0.1',
    ...     description='Mainline',
    ...     author='Trevor Joynson <github@trevor.joynson,io>',
    ...     url='https://trevor.joynson.io',
    ...     namespace_packages=['mainline'],
    ...     packages=setuptools.find_packages(),
    ...     zip_safe=False,
    ...     include_package_data=True,
    ... )
    >>> _conf.update(setup_requirements())
    >>> # setuptools.setup(**_conf)

    :param str pattern: Glob pattern to find requirements files
    :param bool combine: Set True to set install_requires to extras_require['all']
    :return dict: Dictionary of parsed setup() options
    """
    session = PipSession()

    # Handle setuptools insanity
    key_map = {
        'requirements': 'install_requires',
        'install': 'install_requires',
        'tests': 'tests_require',
        'setup': 'setup_requires',
    }
    ret = {v: set() for v in key_map.values()}
    extras = ret['extras_require'] = {}
    all_reqs = set()

    files = [glob.glob(pat) for pat in patterns]
    files = itertools.chain(*files)

    for full_fn in files:
        # Parse
        reqs = {
            str(r.req)
            for r in parse_requirements(full_fn, session=session)
            # Must match env marker, eg:
            #   yarl ; python_version >= '3.0'
            if r.match_markers()
        }
        all_reqs.update(reqs)

        # Add in the right section
        fn = os.path.basename(full_fn)
        barefn, _ = os.path.splitext(fn)
        key = key_map.get(barefn)

        if key:
            ret[key].update(reqs)
            extras[key] = reqs

        extras[barefn] = reqs

    if 'all' not in extras:
        extras['all'] = list(all_reqs)

    if combine:
        extras['install'] = ret['install_requires']
        ret['install_requires'] = list(all_reqs)

    def _listify(dikt):
        ret = {}

        for k, v in dikt.items():
            if isinstance(v, set):
                v = list(v)
            elif isinstance(v, dict):
                v = _listify(v)
            ret[k] = v

        return ret

    ret = _listify(ret)

    return ret


__all__ = ['setup_requirements']

if __name__ == '__main__':
    reqs = setup_requirements()
    print(reqs)

回答 14

另一种可能的解决方案…

def gather_requirements(top_path=None):
    """Captures requirements from repo.

    Expected file format is: requirements[-_]<optional-extras>.txt

    For example:

        pip install -e .[foo]

    Would require:

        requirements-foo.txt

        or

        requirements_foo.txt

    """
    from pip.download import PipSession
    from pip.req import parse_requirements
    import re

    session = PipSession()
    top_path = top_path or os.path.realpath(os.getcwd())
    extras = {}
    for filepath in tree(top_path):
        filename = os.path.basename(filepath)
        basename, ext = os.path.splitext(filename)
        if ext == '.txt' and basename.startswith('requirements'):
            if filename == 'requirements.txt':
                extra_name = 'requirements'
            else:
                _, extra_name = re.split(r'[-_]', basename, 1)
            if extra_name:
                reqs = [str(ir.req) for ir in parse_requirements(filepath, session=session)]
                extras.setdefault(extra_name, []).extend(reqs)
    all_reqs = set()
    for key, values in extras.items():
        all_reqs.update(values)
    extras['all'] = list(all_reqs)
    return extras

然后使用…

reqs = gather_requirements()
install_reqs = reqs.pop('requirements', [])
test_reqs = reqs.pop('test', [])
...
setup(
    ...
    'install_requires': install_reqs,
    'test_requires': test_reqs,
    'extras_require': reqs,
    ...
)

Another possible solution…

def gather_requirements(top_path=None):
    """Captures requirements from repo.

    Expected file format is: requirements[-_]<optional-extras>.txt

    For example:

        pip install -e .[foo]

    Would require:

        requirements-foo.txt

        or

        requirements_foo.txt

    """
    from pip.download import PipSession
    from pip.req import parse_requirements
    import re

    session = PipSession()
    top_path = top_path or os.path.realpath(os.getcwd())
    extras = {}
    for filepath in tree(top_path):
        filename = os.path.basename(filepath)
        basename, ext = os.path.splitext(filename)
        if ext == '.txt' and basename.startswith('requirements'):
            if filename == 'requirements.txt':
                extra_name = 'requirements'
            else:
                _, extra_name = re.split(r'[-_]', basename, 1)
            if extra_name:
                reqs = [str(ir.req) for ir in parse_requirements(filepath, session=session)]
                extras.setdefault(extra_name, []).extend(reqs)
    all_reqs = set()
    for key, values in extras.items():
        all_reqs.update(values)
    extras['all'] = list(all_reqs)
    return extras

and then to use…

reqs = gather_requirements()
install_reqs = reqs.pop('requirements', [])
test_reqs = reqs.pop('test', [])
...
setup(
    ...
    'install_requires': install_reqs,
    'test_requires': test_reqs,
    'extras_require': reqs,
    ...
)

回答 15

我不建议这样做。正如多次提到的install_requiresrequirements.txt绝对不应该是同一列表。但是,由于涉及pip的专用内部API的周围存在许多误导性答案,因此可能值得寻找更明智的选择…

不需要piprequirements.txtsetuptools setup.py脚本中解析文件。该setuptools的项目已经包含在了所有必要的工具顶层pkg_resources

它或多或少看起来像这样:

#!/usr/bin/env python3

import pathlib

import pkg_resources
import setuptools

with pathlib.Path('requirements.txt').open() as requirements_txt:
    install_requires = [
        str(requirement)
        for requirement
        in pkg_resources.parse_requirements(requirements_txt)
    ]

setuptools.setup(
    install_requires=install_requires,
)

I would not recommend doing such a thing. As mentioned multiple times install_requires and requirements.txt are definitely not supposed to be the same list. But since there are a lot of misleading answers all around involving private internal APIs of pip, it might be worth looking at saner alternatives…

There is no need for pip to parse a requirements.txt file from a setuptools setup.py script. The setuptools project already contains all the necessary tools in its top level package pkg_resources.

It could more or less look like this:

#!/usr/bin/env python3

import pathlib

import pkg_resources
import setuptools

with pathlib.Path('requirements.txt').open() as requirements_txt:
    install_requires = [
        str(requirement)
        for requirement
        in pkg_resources.parse_requirements(requirements_txt)
    ]

setuptools.setup(
    install_requires=install_requires,
)

Notes:


回答 16

这个SO问题交叉发布我的答案,以获得另一个简单的pip版本证明解决方案。

try:  # for pip >= 10
    from pip._internal.req import parse_requirements
    from pip._internal.download import PipSession
except ImportError:  # for pip <= 9.0.3
    from pip.req import parse_requirements
    from pip.download import PipSession

requirements = parse_requirements(os.path.join(os.path.dirname(__file__), 'requirements.txt'), session=PipSession())

if __name__ == '__main__':
    setup(
        ...
        install_requires=[str(requirement.req) for requirement in requirements],
        ...
    )

然后,将所有需求requirements.txt放在项目根目录下即可。

Cross posting my answer from this SO question for another simple, pip version proof solution.

try:  # for pip >= 10
    from pip._internal.req import parse_requirements
    from pip._internal.download import PipSession
except ImportError:  # for pip <= 9.0.3
    from pip.req import parse_requirements
    from pip.download import PipSession

requirements = parse_requirements(os.path.join(os.path.dirname(__file__), 'requirements.txt'), session=PipSession())

if __name__ == '__main__':
    setup(
        ...
        install_requires=[str(requirement.req) for requirement in requirements],
        ...
    )

Then just throw in all your requirements under requirements.txt under project root directory.


回答 17

我这样做:

import re

def requirements(filename):
    with open(filename) as f:
        ll = f.read().splitlines()
    d = {}
    for l in ll:
        k, v = re.split(r'==|>=', l)
        d[k] = v
    return d

def packageInfo():
    try:
        from pip._internal.operations import freeze
    except ImportError:
        from pip.operations import freeze

    d = {}
    for kv in freeze.freeze():
        k, v = re.split(r'==|>=', kv)
        d[k] = v
    return d

req = getpackver('requirements.txt')
pkginfo = packageInfo()

for k, v in req.items():
    print(f'{k:<16}: {v:<6} -> {pkginfo[k]}')

I did this:

import re

def requirements(filename):
    with open(filename) as f:
        ll = f.read().splitlines()
    d = {}
    for l in ll:
        k, v = re.split(r'==|>=', l)
        d[k] = v
    return d

def packageInfo():
    try:
        from pip._internal.operations import freeze
    except ImportError:
        from pip.operations import freeze

    d = {}
    for kv in freeze.freeze():
        k, v = re.split(r'==|>=', kv)
        d[k] = v
    return d

req = getpackver('requirements.txt')
pkginfo = packageInfo()

for k, v in req.items():
    print(f'{k:<16}: {v:<6} -> {pkginfo[k]}')

回答 18

另一个parse_requirements将环境标记解析为extras_require以下内容的黑客:

from collections import defaultdict
from pip.req import parse_requirements

requirements = []
extras = defaultdict(list)
for r in parse_requirements('requirements.txt', session='hack'):
    if r.markers:
        extras[':' + str(r.markers)].append(str(r.req))
    else:
        requirements.append(str(r.req))

setup(
    ...,
    install_requires=requirements,
    extras_require=extras
)

它应该同时支持sdist和二进制dists。

正如其他人所述,它parse_requirements有几个缺点,因此这不是您应该在公共项目上执行的操作,但对于内部/个人项目来说就足够了。

Yet another parse_requirements hack that also parses environment markers into extras_require:

from collections import defaultdict
from pip.req import parse_requirements

requirements = []
extras = defaultdict(list)
for r in parse_requirements('requirements.txt', session='hack'):
    if r.markers:
        extras[':' + str(r.markers)].append(str(r.req))
    else:
        requirements.append(str(r.req))

setup(
    ...,
    install_requires=requirements,
    extras_require=extras
)

It should support both sdist and binary dists.

As stated by others, parse_requirements has several shortcomings, so this is not what you should do on public projects, but it may suffice for internal/personal projects.


回答 19

这是pip 9.0.1根据Romain的答案(requirements.txt根据当前环境标记进行解析和过滤)的完整技巧(已通过测试):

from pip.req import parse_requirements

requirements = []
for r in parse_requirements('requirements.txt', session='hack'):
    # check markers, such as
    #
    #     rope_py3k    ; python_version >= '3.0'
    #
    if r.match_markers():
        requirements.append(str(r.req))

print(requirements)

Here is a complete hack (tested with pip 9.0.1) based on Romain’s answer that parses requirements.txt and filters it according to current environment markers:

from pip.req import parse_requirements

requirements = []
for r in parse_requirements('requirements.txt', session='hack'):
    # check markers, such as
    #
    #     rope_py3k    ; python_version >= '3.0'
    #
    if r.match_markers():
        requirements.append(str(r.req))

print(requirements)

lang错误:未知参数:’-mno-fused-madd’(python软件包安装失败)

问题:lang错误:未知参数:’-mno-fused-madd’(python软件包安装失败)

psycopg2在Mavericks 10.9上尝试通过pip 安装时出现以下错误:

clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]

不知道如何进行,并已在此和其他地方搜索了此特定错误。任何帮助深表感谢!

这是pip的完整输出:

$ pip install psycopg2
Downloading/unpacking psycopg2
  Downloading psycopg2-2.5.2.tar.gz (685kB): 685kB downloaded
  Running setup.py (path:/private/var/folders/0z/ljjwsjmn4v9_zwm81vhxj69m0000gn/T/pip_build_tino/psycopg2/setup.py) egg_info for package psycopg2

Installing collected packages: psycopg2
  Running setup.py install for psycopg2
    building 'psycopg2._psycopg' extension
    cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch x86_64 -arch i386 -pipe -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.5.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090303 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/local/Cellar/postgresql/9.3.3/include -I/usr/local/Cellar/postgresql/9.3.3/include/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.9-intel-2.7/psycopg/psycopgmodule.o
    clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]
    clang: note: this will be a hard error (cannot be downgraded to a warning) in the future
    error: command 'cc' failed with exit status 1
    Complete output from command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/0z/ljjwsjmn4v9_zwm81vhxj69m0000gn/T/pip_build_tino/psycopg2/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/0z/ljjwsjmn4v9_zwm81vhxj69m0000gn/T/pip-bnWiwB-record/install-record.txt --single-version-externally-managed --compile:
    running install

running build

running build_py

creating build

creating build/lib.macosx-10.9-intel-2.7

creating build/lib.macosx-10.9-intel-2.7/psycopg2

copying lib/__init__.py -> build/lib.macosx-10.9-intel-2.7/psycopg2

copying lib/_json.py -> build/lib.macosx-10.9-intel-2.7/psycopg2

copying lib/_range.py -> build/lib.macosx-10.9-intel-2.7/psycopg2

copying lib/errorcodes.py -> build/lib.macosx-10.9-intel-2.7/psycopg2

copying lib/extensions.py -> build/lib.macosx-10.9-intel-2.7/psycopg2

copying lib/extras.py -> build/lib.macosx-10.9-intel-2.7/psycopg2

copying lib/pool.py -> build/lib.macosx-10.9-intel-2.7/psycopg2

copying lib/psycopg1.py -> build/lib.macosx-10.9-intel-2.7/psycopg2

copying lib/tz.py -> build/lib.macosx-10.9-intel-2.7/psycopg2

creating build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/__init__.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/dbapi20.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/dbapi20_tpc.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_async.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_bug_gc.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_bugX000.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_cancel.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_connection.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_copy.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_cursor.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_dates.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_extras_dictcursor.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_green.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_lobject.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_module.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_notify.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_psycopg2_dbapi20.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_quote.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_transaction.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_types_basic.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_types_extras.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_with.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/testconfig.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/testutils.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

running build_ext

building 'psycopg2._psycopg' extension

creating build/temp.macosx-10.9-intel-2.7

creating build/temp.macosx-10.9-intel-2.7/psycopg

cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch x86_64 -arch i386 -pipe -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.5.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090303 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/local/Cellar/postgresql/9.3.3/include -I/usr/local/Cellar/postgresql/9.3.3/include/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.9-intel-2.7/psycopg/psycopgmodule.o

clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]

clang: note: this will be a hard error (cannot be downgraded to a warning) in the future

error: command 'cc' failed with exit status 1

----------------------------------------
Cleaning up...
Command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/0z/ljjwsjmn4v9_zwm81vhxj69m0000gn/T/pip_build_tino/psycopg2/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/0z/ljjwsjmn4v9_zwm81vhxj69m0000gn/T/pip-bnWiwB-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /private/var/folders/0z/ljjwsjmn4v9_zwm81vhxj69m0000gn/T/pip_build_tino/psycopg2

I get the following error when attempting to install psycopg2 via pip on Mavericks 10.9:

clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]

Not sure how to proceed and have searched here and elsewhere for this particular error. Any help is much appreciated!

Here is the complete output from pip:

$ pip install psycopg2
Downloading/unpacking psycopg2
  Downloading psycopg2-2.5.2.tar.gz (685kB): 685kB downloaded
  Running setup.py (path:/private/var/folders/0z/ljjwsjmn4v9_zwm81vhxj69m0000gn/T/pip_build_tino/psycopg2/setup.py) egg_info for package psycopg2

Installing collected packages: psycopg2
  Running setup.py install for psycopg2
    building 'psycopg2._psycopg' extension
    cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch x86_64 -arch i386 -pipe -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.5.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090303 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/local/Cellar/postgresql/9.3.3/include -I/usr/local/Cellar/postgresql/9.3.3/include/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.9-intel-2.7/psycopg/psycopgmodule.o
    clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]
    clang: note: this will be a hard error (cannot be downgraded to a warning) in the future
    error: command 'cc' failed with exit status 1
    Complete output from command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/0z/ljjwsjmn4v9_zwm81vhxj69m0000gn/T/pip_build_tino/psycopg2/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/0z/ljjwsjmn4v9_zwm81vhxj69m0000gn/T/pip-bnWiwB-record/install-record.txt --single-version-externally-managed --compile:
    running install

running build

running build_py

creating build

creating build/lib.macosx-10.9-intel-2.7

creating build/lib.macosx-10.9-intel-2.7/psycopg2

copying lib/__init__.py -> build/lib.macosx-10.9-intel-2.7/psycopg2

copying lib/_json.py -> build/lib.macosx-10.9-intel-2.7/psycopg2

copying lib/_range.py -> build/lib.macosx-10.9-intel-2.7/psycopg2

copying lib/errorcodes.py -> build/lib.macosx-10.9-intel-2.7/psycopg2

copying lib/extensions.py -> build/lib.macosx-10.9-intel-2.7/psycopg2

copying lib/extras.py -> build/lib.macosx-10.9-intel-2.7/psycopg2

copying lib/pool.py -> build/lib.macosx-10.9-intel-2.7/psycopg2

copying lib/psycopg1.py -> build/lib.macosx-10.9-intel-2.7/psycopg2

copying lib/tz.py -> build/lib.macosx-10.9-intel-2.7/psycopg2

creating build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/__init__.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/dbapi20.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/dbapi20_tpc.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_async.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_bug_gc.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_bugX000.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_cancel.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_connection.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_copy.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_cursor.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_dates.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_extras_dictcursor.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_green.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_lobject.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_module.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_notify.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_psycopg2_dbapi20.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_quote.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_transaction.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_types_basic.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_types_extras.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/test_with.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/testconfig.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

copying tests/testutils.py -> build/lib.macosx-10.9-intel-2.7/psycopg2/tests

running build_ext

building 'psycopg2._psycopg' extension

creating build/temp.macosx-10.9-intel-2.7

creating build/temp.macosx-10.9-intel-2.7/psycopg

cc -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE -arch x86_64 -arch i386 -pipe -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSION="2.5.2 (dt dec pq3 ext)" -DPG_VERSION_HEX=0x090303 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHAVE_PQFREEMEM=1 -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I. -I/usr/local/Cellar/postgresql/9.3.3/include -I/usr/local/Cellar/postgresql/9.3.3/include/server -c psycopg/psycopgmodule.c -o build/temp.macosx-10.9-intel-2.7/psycopg/psycopgmodule.o

clang: error: unknown argument: '-mno-fused-madd' [-Wunused-command-line-argument-hard-error-in-future]

clang: note: this will be a hard error (cannot be downgraded to a warning) in the future

error: command 'cc' failed with exit status 1

----------------------------------------
Cleaning up...
Command /usr/bin/python -c "import setuptools, tokenize;__file__='/private/var/folders/0z/ljjwsjmn4v9_zwm81vhxj69m0000gn/T/pip_build_tino/psycopg2/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /var/folders/0z/ljjwsjmn4v9_zwm81vhxj69m0000gn/T/pip-bnWiwB-record/install-record.txt --single-version-externally-managed --compile failed with error code 1 in /private/var/folders/0z/ljjwsjmn4v9_zwm81vhxj69m0000gn/T/pip_build_tino/psycopg2

回答 0

您可以通过在编译之前设置以下环境变量来告诉clang不要将其引发错误:

export CFLAGS=-Qunused-arguments
export CPPFLAGS=-Qunused-arguments

然后pip install psycopg2应该工作。

尝试时我有同样的想法pip install lxml

编辑:如果您是以超级用户身份安装(如果要追加到/Library/Python/2.7/site-packages,则可能是这种情况,如果要附加到OS X附带的本地Apple工厂安装的Python发行版,而不是随后安装了自己的其他Python发行版中),则您需要执行此操作,如@Thijs Kuipers在以下评论中所述:

sudo -E pip install psycopg2

或等价的商品,您可能会用它代替任何其他包装名称psycopg2

更新[2014-05-16]:Apple已使用更新的系统Python(2.7、2.6和2.5)修复了此问题,OS X 10.9.3因此在使用最新的Mavericks和时不再需要解决方法Xcode 5.1+。但是,到目前为止,OS X 10.8.x如果您正在使用(山狮,当前为10.8.5),仍需要解决方法Xcode 5.1+

You can tell clang to not raise this as an error by setting the following environment variables prior compilation:

export CFLAGS=-Qunused-arguments
export CPPFLAGS=-Qunused-arguments

Then pip install psycopg2should work.

I had the same when trying to pip install lxml.

Edit: if you are installing as superuser (which will likely be the case if you are trying to append to /Library/Python/2.7/site-packages, the native Apple factory-installed Python distribution which ships with OS X, rather than to some other Python distribution which you have subsequently installed yourself), then you will need to do, as described by @Thijs Kuipers in comments below:

sudo -E pip install psycopg2

or the equivalent, for whatever other package name you may be substituting in place of psycopg2.

UPDATE [2014-05-16]: Apple has fixed this problem with updated system Pythons (2.7, 2.6, and 2.5) in OS X 10.9.3 so the workaround is no longer necessary when using the latest Mavericks and Xcode 5.1+. However, as of now, the workaround is still required for OS X 10.8.x (Mountain Lion, currently 10.8.5) if you are using Xcode 5.1+ there.


回答 1

更新:10.9.3解决了系统CPython的问题。

这是由今天Xcode 5.1附带的Apple最新的clang更新引起的,它影响了很多人,因此希望可以尽快修复。

更新:没想到它会引起如此多的关注,但是这里有更多详细信息:clang 3.4苹果公司正在将默认设置发送给未知标志错误,但是CPython使用与原始编译时相同的标志集来构建模块。系统CPython使用clang未知的几个标志进行编译,从而导致此问题。以下是当前的Mavericks(10.9.2)CPython编译标志:

-I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE

要解决此问题,您有几种选择:

  • 添加ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future到您的编译标志。
  • 通过 CFLAGS=""
  • 从sysconfigdata.py中删除不受支持的标志(如另一个答案中所述)。
  • 使用homebrew编译新的python 。
  • 等待下一次OS X更新,据传其中包括重新编译的Python / Ruby,以消除系统运行时的此问题。

Update: 10.9.3 resolves the issue with system CPython.

This is caused by the latest clang update from Apple that came with Xcode 5.1 today and is affecting many, many people, so hopefully a fix will appear soon.

Update: Did not expect this to get so much attention, but here’s more detail: the clang 3.4 Apple is shipping defaults to erroring on unknown flags, but CPython builds modules using the same set of flags it was compiled with originally. The system CPython was compiled with several flags that are unknown by clang, thus causing this problem. The following are the current Mavericks (10.9.2) CPython compile flags:

-I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I/System/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -fno-strict-aliasing -fno-common -dynamic -arch x86_64 -arch i386 -g -Os -pipe -fno-common -fno-strict-aliasing -fwrapv -mno-fused-madd -DENABLE_DTRACE -DMACOSX -DNDEBUG -Wall -Wstrict-prototypes -Wshorten-64-to-32 -DNDEBUG -g -fwrapv -Os -Wall -Wstrict-prototypes -DENABLE_DTRACE

To resolve this issue you have a few options:

  • Add ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future to your compile flags.
  • Pass CFLAGS=""
  • Strip the unsupported flags from the sysconfigdata.py (as is noted in another answer).
  • Compile a new python using homebrew.
  • Wait for the next OS X update, which is rumored to include recompiled Python/Ruby to remove this issue for system runtimes.

回答 2

xCode 5.1

ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install psycopg2

xCode 5.1

ARCHFLAGS=-Wno-error=unused-command-line-argument-hard-error-in-future pip install psycopg2

回答 3

这是一种解决方法,涉及从python安装中删除标志。

在/ 标志设置的/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_sysconfigdata.py几个地方。-mfused-madd-mno-fused-madd

编辑此文件,并删除对该标记应起作用的所有引用:

sudo sed -i '.old' 's/ -m\(no-\)\{0,1\}fused-madd //g' /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_sysconfigdata.py

您还需要删除相应的_sysconfigdata.pyc_sysconfigdata.pyo文件-至少在我的系统上,这些文件没有自动重建:

cd /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/
sudo rm _sysconfigdata.pyo _sysconfigdata.pyc

注意,必须使用root用户访问权限来进行那些更改。

Here is a work around that involves removing the flag from the python installation.

In /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_sysconfigdata.py are several places where the -mfused-madd / -mno-fused-madd flag is set.

Edit this file and remove all of the references to that flag your compilation should work:

sudo sed -i '.old' 's/ -m\(no-\)\{0,1\}fused-madd //g' /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_sysconfigdata.py

You need to delete the corresponding _sysconfigdata.pyc and _sysconfigdata.pyo files as well – at least on my system these files did not automatically get rebuilt:

cd /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/
sudo rm _sysconfigdata.pyo _sysconfigdata.pyc

Note that have to use root access to make those changes.


回答 4

我还编辑了系统python原始编译标志的概念(就像@ user3405479一样)。我使用命令行工具而不是编辑器来“就地”编辑文件(inode确实发生了变化)。我还编译了新的pyo和pyc文件,而不是删除它们。

以下命令以root用户身份运行,例如在 sudo -i

pushd /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7

sed 's/-mno-fused-madd//g' _sysconfigdata.py \ | diff -p _sysconfigdata.py - | patch -b

python -m py_compile _sysconfigdata.py

python -OO -m py_compile _sysconfigdata.py

popd

I also edited the system python’s notion of its original compile flags (as @user3405479 did). Instead of an editor I used command line tools to edit the file “in place” (the inode does change). I also compiled new pyo and pyc files instead of leaving them deleted.

The following commands are run as root, for example under sudo -i

pushd /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7

sed 's/-mno-fused-madd//g' _sysconfigdata.py \ | diff -p _sysconfigdata.py - | patch -b

python -m py_compile _sysconfigdata.py

python -OO -m py_compile _sysconfigdata.py

popd


回答 5

我用自制软件安装了postgresql,然后想将psycopg2安装到Mavericks上系统提供的python 2.7中。为了使它起作用,我最终运行了此命令:

sudo ARCHFLAGS="-arch x86_64" CFLAGS=-Wunused-command-line-argument-hard-error-in-future pip install psycopg2

I used homebrew to install postgresql, and then wanted to install psycopg2 into the system-provided python 2.7 on Mavericks. To get that to work I ended up running this:

sudo ARCHFLAGS="-arch x86_64" CFLAGS=-Wunused-command-line-argument-hard-error-in-future pip install psycopg2

回答 6

至少Apple意识到了这一点,因为在Xcode 5.1 发行说明(“编译器”部分)中讨论了此问题。在下一个操作系统更新中,期待更新的Python和Ruby(手指交叉!)。还要注意,该-Wno-error=unused-command-line-argument-hard-error-in-future标志只是临时的解决方法,将来会消失(希望在系统Python修复后!)。

如果您是像我这样的Python软件包维护者,并且希望为您的用户省去解决这些麻烦的麻烦,那么以下解决方案(除了提供二进制工具/鸡蛋)可放入您的setup.py文件中:

from distutils.command.build_ext import build_ext
import subprocess
import sys

# Workaround for OS X 10.9.2 and Xcode 5.1+
# The latest clang treats unrecognized command-line options as errors and the
# Python CFLAGS variable contains unrecognized ones (e.g. -mno-fused-madd).
# See Xcode 5.1 Release Notes (Compiler section) and
# http://stackoverflow.com/questions/22313407 for more details. This workaround
# follows the approach suggested in http://stackoverflow.com/questions/724664.
class build_ext_subclass(build_ext):
    def build_extensions(self):
        if sys.platform == 'darwin':
            # Test the compiler that will actually be used to see if it likes flags
            proc = subprocess.Popen(self.compiler.compiler + ['-v'],
                                    stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                    universal_newlines=True)
            stdout, stderr = proc.communicate()
            clang_mesg = "clang: error: unknown argument: '-mno-fused-madd'"
            if proc.returncode and stderr.splitlines()[0].startswith(clang_mesg):
                for ext in self.extensions:
                    # Use temporary workaround to ignore invalid compiler option
                    # Hopefully -mno-fused-madd goes away before this workaround!
                    ext.extra_compile_args += ['-Wno-error=unused-command-line-argument-hard-error-in-future']
        build_ext.build_extensions(self)

setup(
    name="mypackage",
    ...
    cmdclass={'build_ext' : build_ext_subclass},
    ...
)

At least Apple is aware of this as this issue is discussed in the Xcode 5.1 Release Notes (Compiler section). Expect an updated Python and Ruby in the next OS update (fingers crossed!). Also take note that the -Wno-error=unused-command-line-argument-hard-error-in-future flag is meant to be a temporary workaround and will go away in the future (hopefully after system Python is fixed!).

If you are a Python package maintainer like me and want to save your users the hassle of working around this themselves, here is a solution (besides providing binary wheels/eggs) that goes into your setup.py file:

from distutils.command.build_ext import build_ext
import subprocess
import sys

# Workaround for OS X 10.9.2 and Xcode 5.1+
# The latest clang treats unrecognized command-line options as errors and the
# Python CFLAGS variable contains unrecognized ones (e.g. -mno-fused-madd).
# See Xcode 5.1 Release Notes (Compiler section) and
# http://stackoverflow.com/questions/22313407 for more details. This workaround
# follows the approach suggested in http://stackoverflow.com/questions/724664.
class build_ext_subclass(build_ext):
    def build_extensions(self):
        if sys.platform == 'darwin':
            # Test the compiler that will actually be used to see if it likes flags
            proc = subprocess.Popen(self.compiler.compiler + ['-v'],
                                    stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                    universal_newlines=True)
            stdout, stderr = proc.communicate()
            clang_mesg = "clang: error: unknown argument: '-mno-fused-madd'"
            if proc.returncode and stderr.splitlines()[0].startswith(clang_mesg):
                for ext in self.extensions:
                    # Use temporary workaround to ignore invalid compiler option
                    # Hopefully -mno-fused-madd goes away before this workaround!
                    ext.extra_compile_args += ['-Wno-error=unused-command-line-argument-hard-error-in-future']
        build_ext.build_extensions(self)

setup(
    name="mypackage",
    ...
    cmdclass={'build_ext' : build_ext_subclass},
    ...
)

回答 7

以上解决方案均不适合我。我的情况略有不同。当我收到此错误消息时,我正在尝试通过自制软件安装rdiff-backup。

我显然同时拥有Apple的默认python(2.7.5 @ / usr / bin / python)和Homebrew的python(2.7.6 @ /usr/local/Cellar/python/2.7.6/bin/python),但是错误即将到来来自Apple的python。

为了解决这个问题,基本上我切换了python二进制文件。

我是通过sudo完成的:

  • cp / usr / bin / python / usr / bin / python_orig
  • ln -s /usr/local/Cellar/python/2.7.6/bin/python / usr / bin / python

然后,“ brew install rdiff-backup”成功完成,没有任何错误。

最后,我执行了“ mv / usr / bin / python_orig / usr / bin / python”将所有内容还原。

None of the above solutions worked for me. My situation is slightly different. I was trying to install rdiff-backup via homebrew when I got this error message.

I apparently have both Apple’s default python (2.7.5 @ /usr/bin/python) and Homebrew’s python (2.7.6 @ /usr/local/Cellar/python/2.7.6/bin/python), but the error was coming from Apple’s python.

To fix the problem, basically I switched the python binaries.

I did this via sudo:

  • cp /usr/bin/python /usr/bin/python_orig
  • ln -s /usr/local/Cellar/python/2.7.6/bin/python /usr/bin/python

Then, ‘brew install rdiff-backup’ succeeded without any errors.

Finally, I did “mv /usr/bin/python_orig /usr/bin/python” to revert everything back.


回答 8

您可能正在使用Python 2.7.5

$ python

Python 2.7.5 (default, Aug 25 2013, 00:04:04)  [GCC 4.2.1 Compatible
Apple LLVM 5.0 (clang-500.0.68)] on darwin

最简单的解决方案是访问www.python.org并安装与LLVM 5.1兼容的Python 2.7.6。

然后敬酒您的旧虚拟环境rmvirtualenv {virtual_env_name}

然后创建一个新的虚拟环境。

mkvirtualenv --no-site-packages -p/Library/Frameworks/Python.framework/Versions/2.7/bin/python {virtual_env_name}

点之后应该可以正常工作。

You’re probably on Python 2.7.5

$ python

Python 2.7.5 (default, Aug 25 2013, 00:04:04)  [GCC 4.2.1 Compatible
Apple LLVM 5.0 (clang-500.0.68)] on darwin

Easiest solution go to www.python.org and install Python 2.7.6 which is compatible with the LLVM 5.1.

Then toast your old virtual environment, rmvirtualenv {virtual_env_name}.

Then make a new virtual env..

mkvirtualenv --no-site-packages -p/Library/Frameworks/Python.framework/Versions/2.7/bin/python {virtual_env_name}

pip should work fine after this.


回答 9

Amazon Linux [AWS EC2]

试图pip install paramikoAmazon Linux AMI release 2016.09给了我,其中包括一个链接到这个职位的SO错误。因此,即使它不符合OP的标题,我也将分享答案。

yum install libffi-devel
yum install gcc
yum install openssl-devel
pip install paramiko

金!

Amazon Linux [AWS EC2]

Trying to pip install paramiko on Amazon Linux AMI release 2016.09 gave me an error that included a link to this SO post. So, even though it doesn’t fit the OP’s Title, I’m going to share the answer.

yum install libffi-devel
yum install gcc
yum install openssl-devel
pip install paramiko

Golden!


回答 10

我使用自制的 python软件包。重新编译后效果很好。

I used homebrew python package. Works well after re-compilling.


回答 11

_sysconfigdata.py修复程序的变体:使用虚拟环境

cp /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_sysconfigdata.py ${VIRTUAL_ENV}/lib/python2.7/_sysconfigdata.py

然后在$ {VIRTUAL_ENV} /lib/python2.7/_sysconfigdata.py中编辑副本

我删除了所有’-mno-fused-madd’事件,然后在该virtualenv中进行了构建。

无需root!

Variation on the _sysconfigdata.py fix: use a virtual environment

cp /System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/_sysconfigdata.py ${VIRTUAL_ENV}/lib/python2.7/_sysconfigdata.py

Then edit your copy at ${VIRTUAL_ENV}/lib/python2.7/_sysconfigdata.py

I removed all the occurences of ‘-mno-fused-madd’ and then builds worked in that virtualenv.

No root needed!


回答 12

对我而言,错误标志是在软件包的Makefile中明确给出的。因此,我必须编辑makefile才能从错误包中删除无法识别的标志。

For me, the bad flags were explicitly given in the package’s Makefile. So I had to edit the makefile to remove the unrecognized flag from the erroring package.


回答 13

升级Homebrew并安装unixodbc为我解决了

brew upgrade
brew install unixodbc

Upgrading Homebrew and installing unixodbc solved it for me

brew upgrade
brew install unixodbc

使用pip的libxml安装错误

问题:使用pip的libxml安装错误

这是我的错误:

(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install lxml
Downloading/unpacking lxml
  Running setup.py egg_info for package lxml
    Building lxml version 2.3.
    Building without Cython.
    ERROR: /bin/sh: xslt-config: not found

    ** make sure the development packages of libxml2 and libxslt are installed **

    Using build configuration of libxslt
Installing collected packages: lxml
  Running setup.py install for lxml
    Building lxml version 2.3.
    Building without Cython.
    ERROR: /bin/sh: xslt-config: not found

    ** make sure the development packages of libxml2 and libxslt are installed **

    Using build configuration of libxslt
    building 'lxml.etree' extension
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-i686-2.6/src/lxml/lxml.etree.o -w
    src/lxml/lxml.etree.c:4: fatal error: Python.h: 没有那个文件或目录
    compilation terminated.
    error: command 'gcc' failed with exit status 1
    Complete output from command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/lxml/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-jOhgvD-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6:
    Building lxml version 2.3.

Building without Cython.

ERROR: /bin/sh: xslt-config: not found



** make sure the development packages of libxml2 and libxslt are installed **



Using build configuration of libxslt

running install

running build

running build_py

running build_ext

building 'lxml.etree' extension

gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-i686-2.6/src/lxml/lxml.etree.o -w

src/lxml/lxml.etree.c:4: fatal error: Python.h: 没有那个文件或目录

compilation terminated.

error: command 'gcc' failed with exit status 1

----------------------------------------
Command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/lxml/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-jOhgvD-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6 failed with error code 1
Storing complete log in /home/zjm1126/.pip/pip.log

我能做什么?

更新:

(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install lxml
Downloading/unpacking lxml
  Running setup.py egg_info for package lxml
    Building lxml version 2.3.
    Building without Cython.
    Using build configuration of libxslt 1.1.26
    Building against libxml2/libxslt in the following directory: /usr/lib
Installing collected packages: lxml
  Running setup.py install for lxml
    Building lxml version 2.3.
    Building without Cython.
    Using build configuration of libxslt 1.1.26
    Building against libxml2/libxslt in the following directory: /usr/lib
    building 'lxml.etree' extension
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/libxml2 -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-i686-2.6/src/lxml/lxml.etree.o -w
    src/lxml/lxml.etree.c:4: fatal error: Python.h: 没有那个文件或目录
    compilation terminated.
    error: command 'gcc' failed with exit status 1
    Complete output from command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/lxml/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-NJw2ws-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6:
    Building lxml version 2.3.

Building without Cython.

Using build configuration of libxslt 1.1.26

Building against libxml2/libxslt in the following directory: /usr/lib

running install

running build

running build_py

running build_ext

building 'lxml.etree' extension

gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/libxml2 -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-i686-2.6/src/lxml/lxml.etree.o -w

src/lxml/lxml.etree.c:4: fatal error: Python.h: 没有那个文件或目录

compilation terminated.

error: command 'gcc' failed with exit status 1

----------------------------------------
Command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/lxml/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-NJw2ws-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6 failed with error code 1
Storing complete log in /home/zjm1126/.pip/pip.log

日志:

------------------------------------------------------------
/home/zjm1126/zjm_test/mysite/bin/pip run on Thu Mar  3 17:07:27 2011
Downloading/unpacking mysql-python
  Running setup.py egg_info for package mysql-python
    running egg_info
    creating pip-egg-info/MySQL_python.egg-info
    writing pip-egg-info/MySQL_python.egg-info/PKG-INFO
    writing top-level names to pip-egg-info/MySQL_python.egg-info/top_level.txt
    writing dependency_links to pip-egg-info/MySQL_python.egg-info/dependency_links.txt
    writing pip-egg-info/MySQL_python.egg-info/PKG-INFO
    writing top-level names to pip-egg-info/MySQL_python.egg-info/top_level.txt
    writing dependency_links to pip-egg-info/MySQL_python.egg-info/dependency_links.txt
    writing manifest file 'pip-egg-info/MySQL_python.egg-info/SOURCES.txt'
    warning: manifest_maker: standard file '-c' not found
    reading manifest file 'pip-egg-info/MySQL_python.egg-info/SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    warning: no files found matching 'MANIFEST'
    warning: no files found matching 'ChangeLog'
    warning: no files found matching 'GPL'
    writing manifest file 'pip-egg-info/MySQL_python.egg-info/SOURCES.txt'
Installing collected packages: mysql-python
  Running setup.py install for mysql-python
    Running command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-XuVIux-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6
    running install
    running build
    running build_py
    creating build
    creating build/lib.linux-i686-2.6
    copying _mysql_exceptions.py -> build/lib.linux-i686-2.6
    creating build/lib.linux-i686-2.6/MySQLdb
    copying MySQLdb/__init__.py -> build/lib.linux-i686-2.6/MySQLdb
    copying MySQLdb/converters.py -> build/lib.linux-i686-2.6/MySQLdb
    copying MySQLdb/connections.py -> build/lib.linux-i686-2.6/MySQLdb
    copying MySQLdb/cursors.py -> build/lib.linux-i686-2.6/MySQLdb
    copying MySQLdb/release.py -> build/lib.linux-i686-2.6/MySQLdb
    copying MySQLdb/times.py -> build/lib.linux-i686-2.6/MySQLdb
    creating build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/__init__.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/CR.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/ER.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/FLAG.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/REFRESH.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/CLIENT.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    running build_ext
    building '_mysql' extension
    creating build/temp.linux-i686-2.6
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3 -I/usr/include/mysql -I/usr/include/python2.6 -c _mysql.c -o build/temp.linux-i686-2.6/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -DUNIV_LINUX -DUNIV_LINUX
    In file included from _mysql.c:29:
    pymemcompat.h:10: fatal error: Python.h: 没有那个文件或目录
    compilation terminated.
    error: command 'gcc' failed with exit status 1
    Complete output from command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-XuVIux-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6:
    running install

running build

running build_py

creating build

creating build/lib.linux-i686-2.6

copying _mysql_exceptions.py -> build/lib.linux-i686-2.6

creating build/lib.linux-i686-2.6/MySQLdb

copying MySQLdb/__init__.py -> build/lib.linux-i686-2.6/MySQLdb

copying MySQLdb/converters.py -> build/lib.linux-i686-2.6/MySQLdb

copying MySQLdb/connections.py -> build/lib.linux-i686-2.6/MySQLdb

copying MySQLdb/cursors.py -> build/lib.linux-i686-2.6/MySQLdb

copying MySQLdb/release.py -> build/lib.linux-i686-2.6/MySQLdb

copying MySQLdb/times.py -> build/lib.linux-i686-2.6/MySQLdb

creating build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/__init__.py -> build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/CR.py -> build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/ER.py -> build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/FLAG.py -> build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/REFRESH.py -> build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/CLIENT.py -> build/lib.linux-i686-2.6/MySQLdb/constants

running build_ext

building '_mysql' extension

creating build/temp.linux-i686-2.6

gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3 -I/usr/include/mysql -I/usr/include/python2.6 -c _mysql.c -o build/temp.linux-i686-2.6/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -DUNIV_LINUX -DUNIV_LINUX

In file included from _mysql.c:29:

pymemcompat.h:10: fatal error: Python.h: 没有那个文件或目录

compilation terminated.

error: command 'gcc' failed with exit status 1

----------------------------------------
Command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-XuVIux-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6 failed with error code 1
Exception information:
Traceback (most recent call last):
  File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/basecommand.py", line 130, in main
    self.run(options, args)
  File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/commands/install.py", line 228, in run
    requirement_set.install(install_options, global_options)
  File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/req.py", line 1043, in install
    requirement.install(install_options, global_options)
  File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/req.py", line 559, in install
    cwd=self.source_dir, filter_stdout=self._filter_install, show_stdout=False)
  File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/__init__.py", line 249, in call_subprocess
    % (command_desc, proc.returncode))
InstallationError: Command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-XuVIux-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6 failed with error code 1

This is my error:

(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install lxml
Downloading/unpacking lxml
  Running setup.py egg_info for package lxml
    Building lxml version 2.3.
    Building without Cython.
    ERROR: /bin/sh: xslt-config: not found

    ** make sure the development packages of libxml2 and libxslt are installed **

    Using build configuration of libxslt
Installing collected packages: lxml
  Running setup.py install for lxml
    Building lxml version 2.3.
    Building without Cython.
    ERROR: /bin/sh: xslt-config: not found

    ** make sure the development packages of libxml2 and libxslt are installed **

    Using build configuration of libxslt
    building 'lxml.etree' extension
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-i686-2.6/src/lxml/lxml.etree.o -w
    src/lxml/lxml.etree.c:4: fatal error: Python.h: 没有那个文件或目录
    compilation terminated.
    error: command 'gcc' failed with exit status 1
    Complete output from command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/lxml/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-jOhgvD-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6:
    Building lxml version 2.3.

Building without Cython.

ERROR: /bin/sh: xslt-config: not found



** make sure the development packages of libxml2 and libxslt are installed **



Using build configuration of libxslt

running install

running build

running build_py

running build_ext

building 'lxml.etree' extension

gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-i686-2.6/src/lxml/lxml.etree.o -w

src/lxml/lxml.etree.c:4: fatal error: Python.h: 没有那个文件或目录

compilation terminated.

error: command 'gcc' failed with exit status 1

----------------------------------------
Command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/lxml/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-jOhgvD-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6 failed with error code 1
Storing complete log in /home/zjm1126/.pip/pip.log

What can I do?

updated:

(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install lxml
Downloading/unpacking lxml
  Running setup.py egg_info for package lxml
    Building lxml version 2.3.
    Building without Cython.
    Using build configuration of libxslt 1.1.26
    Building against libxml2/libxslt in the following directory: /usr/lib
Installing collected packages: lxml
  Running setup.py install for lxml
    Building lxml version 2.3.
    Building without Cython.
    Using build configuration of libxslt 1.1.26
    Building against libxml2/libxslt in the following directory: /usr/lib
    building 'lxml.etree' extension
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/libxml2 -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-i686-2.6/src/lxml/lxml.etree.o -w
    src/lxml/lxml.etree.c:4: fatal error: Python.h: 没有那个文件或目录
    compilation terminated.
    error: command 'gcc' failed with exit status 1
    Complete output from command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/lxml/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-NJw2ws-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6:
    Building lxml version 2.3.

Building without Cython.

Using build configuration of libxslt 1.1.26

Building against libxml2/libxslt in the following directory: /usr/lib

running install

running build

running build_py

running build_ext

building 'lxml.etree' extension

gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/include/libxml2 -I/usr/include/python2.6 -c src/lxml/lxml.etree.c -o build/temp.linux-i686-2.6/src/lxml/lxml.etree.o -w

src/lxml/lxml.etree.c:4: fatal error: Python.h: 没有那个文件或目录

compilation terminated.

error: command 'gcc' failed with exit status 1

----------------------------------------
Command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/lxml/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-NJw2ws-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6 failed with error code 1
Storing complete log in /home/zjm1126/.pip/pip.log

the log:

------------------------------------------------------------
/home/zjm1126/zjm_test/mysite/bin/pip run on Thu Mar  3 17:07:27 2011
Downloading/unpacking mysql-python
  Running setup.py egg_info for package mysql-python
    running egg_info
    creating pip-egg-info/MySQL_python.egg-info
    writing pip-egg-info/MySQL_python.egg-info/PKG-INFO
    writing top-level names to pip-egg-info/MySQL_python.egg-info/top_level.txt
    writing dependency_links to pip-egg-info/MySQL_python.egg-info/dependency_links.txt
    writing pip-egg-info/MySQL_python.egg-info/PKG-INFO
    writing top-level names to pip-egg-info/MySQL_python.egg-info/top_level.txt
    writing dependency_links to pip-egg-info/MySQL_python.egg-info/dependency_links.txt
    writing manifest file 'pip-egg-info/MySQL_python.egg-info/SOURCES.txt'
    warning: manifest_maker: standard file '-c' not found
    reading manifest file 'pip-egg-info/MySQL_python.egg-info/SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    warning: no files found matching 'MANIFEST'
    warning: no files found matching 'ChangeLog'
    warning: no files found matching 'GPL'
    writing manifest file 'pip-egg-info/MySQL_python.egg-info/SOURCES.txt'
Installing collected packages: mysql-python
  Running setup.py install for mysql-python
    Running command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-XuVIux-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6
    running install
    running build
    running build_py
    creating build
    creating build/lib.linux-i686-2.6
    copying _mysql_exceptions.py -> build/lib.linux-i686-2.6
    creating build/lib.linux-i686-2.6/MySQLdb
    copying MySQLdb/__init__.py -> build/lib.linux-i686-2.6/MySQLdb
    copying MySQLdb/converters.py -> build/lib.linux-i686-2.6/MySQLdb
    copying MySQLdb/connections.py -> build/lib.linux-i686-2.6/MySQLdb
    copying MySQLdb/cursors.py -> build/lib.linux-i686-2.6/MySQLdb
    copying MySQLdb/release.py -> build/lib.linux-i686-2.6/MySQLdb
    copying MySQLdb/times.py -> build/lib.linux-i686-2.6/MySQLdb
    creating build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/__init__.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/CR.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/ER.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/FLAG.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/REFRESH.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    copying MySQLdb/constants/CLIENT.py -> build/lib.linux-i686-2.6/MySQLdb/constants
    running build_ext
    building '_mysql' extension
    creating build/temp.linux-i686-2.6
    gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3 -I/usr/include/mysql -I/usr/include/python2.6 -c _mysql.c -o build/temp.linux-i686-2.6/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -DUNIV_LINUX -DUNIV_LINUX
    In file included from _mysql.c:29:
    pymemcompat.h:10: fatal error: Python.h: 没有那个文件或目录
    compilation terminated.
    error: command 'gcc' failed with exit status 1
    Complete output from command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-XuVIux-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6:
    running install

running build

running build_py

creating build

creating build/lib.linux-i686-2.6

copying _mysql_exceptions.py -> build/lib.linux-i686-2.6

creating build/lib.linux-i686-2.6/MySQLdb

copying MySQLdb/__init__.py -> build/lib.linux-i686-2.6/MySQLdb

copying MySQLdb/converters.py -> build/lib.linux-i686-2.6/MySQLdb

copying MySQLdb/connections.py -> build/lib.linux-i686-2.6/MySQLdb

copying MySQLdb/cursors.py -> build/lib.linux-i686-2.6/MySQLdb

copying MySQLdb/release.py -> build/lib.linux-i686-2.6/MySQLdb

copying MySQLdb/times.py -> build/lib.linux-i686-2.6/MySQLdb

creating build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/__init__.py -> build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/CR.py -> build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/ER.py -> build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/FLAG.py -> build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/REFRESH.py -> build/lib.linux-i686-2.6/MySQLdb/constants

copying MySQLdb/constants/CLIENT.py -> build/lib.linux-i686-2.6/MySQLdb/constants

running build_ext

building '_mysql' extension

creating build/temp.linux-i686-2.6

gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -Dversion_info=(1,2,3,'final',0) -D__version__=1.2.3 -I/usr/include/mysql -I/usr/include/python2.6 -c _mysql.c -o build/temp.linux-i686-2.6/_mysql.o -DBIG_JOINS=1 -fno-strict-aliasing -DUNIV_LINUX -DUNIV_LINUX

In file included from _mysql.c:29:

pymemcompat.h:10: fatal error: Python.h: 没有那个文件或目录

compilation terminated.

error: command 'gcc' failed with exit status 1

----------------------------------------
Command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-XuVIux-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6 failed with error code 1
Exception information:
Traceback (most recent call last):
  File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/basecommand.py", line 130, in main
    self.run(options, args)
  File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/commands/install.py", line 228, in run
    requirement_set.install(install_options, global_options)
  File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/req.py", line 1043, in install
    requirement.install(install_options, global_options)
  File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/req.py", line 559, in install
    cwd=self.source_dir, filter_stdout=self._filter_install, show_stdout=False)
  File "/home/zjm1126/zjm_test/mysite/lib/python2.6/site-packages/pip-0.8.1-py2.6.egg/pip/__init__.py", line 249, in call_subprocess
    % (command_desc, proc.returncode))
InstallationError: Command /home/zjm1126/zjm_test/mysite/bin/python -c "import setuptools;__file__='/home/zjm1126/zjm_test/mysite/build/mysql-python/setup.py';execfile(__file__)" install --single-version-externally-managed --record /tmp/pip-XuVIux-record/install-record.txt --install-headers /home/zjm1126/zjm_test/mysite/include/site/python2.6 failed with error code 1

回答 0

**确保已安装libxml2和libxslt的开发包**

lxml文档中,假设您正在运行基于Debian的发行版:

sudo apt-get install libxml2-dev libxslt-dev python-dev

对于基于Debian的系统,它应该是足够安装已知的生成依赖python-lxml或者python3-lxml,如

sudo apt-get build-dep python3-lxml

** make sure the development packages of libxml2 and libxslt are installed **

From the lxml documentation, assuming you are running a Debian-based distribution :

sudo apt-get install libxml2-dev libxslt-dev python-dev

For Debian based systems, it should be enough to install the known build dependencies of python-lxml or python3-lxml, e.g.

sudo apt-get build-dep python3-lxml

回答 1

这为我工作:

yum install libxslt-devel libxml2-devel

This worked for me:

yum install libxslt-devel libxml2-devel

回答 2

如果您使用的是Ubuntu / Lubuntu 13.04或Ubuntu 13.10,并且遇到“ / usr / bin / ld:找不到-lz”的问题,则可能还需要安装zlib1g-dev软件包:

sudo apt-get install -y zlib1g-dev

放在一起:

sudo apt-get install -y libxml2-dev libxslt1-dev zlib1g-dev python3-pip
sudo pip3 install lxml

In case, you are using Ubuntu/Lubuntu 13.04 or Ubuntu 13.10 and having problem with “/usr/bin/ld: cannot find -lz”, you may need also install zlib1g-dev package:

sudo apt-get install -y zlib1g-dev

Put it all together:

sudo apt-get install -y libxml2-dev libxslt1-dev zlib1g-dev python3-pip
sudo pip3 install lxml

回答 3

不,您缺少Python头文件。当您使用系统Python时,这通常会在Linux上发生(有理由不这样做,但这是一个不同的问题)。

您可能需要安装一些软件包,它可能称为python-dev或python-devel。

 sudo yum install python-devel

要么

 sudo aptitude install python-dev

或类似的东西。

No you are missing the Python header files. This mostly happens on Linux when you are using the system Python (there are reasons not to do that, but that’s a different question).

You probably need to install some package, and it’s probably called python-dev or python-devel.

 sudo yum install python-devel

or

 sudo aptitude install python-dev

Or somesuch.


回答 4

我通过增加服务器内存来解决此问题。

我只运行512 MB,升级到1 GB时没有问题。

在此之前,我还手动安装了每个软件包,以尝试解决此问题,但是我不确定这是否是必要步骤。

I solved this issue by increasing my server ram.

I was running only 512 MB and when I upgraded to 1 GB I had no problem.

I also installed every package manually prior to this in an attempt to fix the problem, but I’m not sure whether this is a necessary step.


回答 5

在Windows上 上,在3.3版上尝试手动安装在Python 3.4中时,出现了相同的错误。我终于能够通过安装滚轮并从Python34目录运行pip来解决此问题。

1)从这里下载轮子: http //www.lfd.uci.edu/~gohlke/pythonlibs/#lxml

2) cd Python34\Scripts

3) pip.exe C:\Users\Home\Downloads\lxml- ......... .whl

On Windows I had the same error on windows when trying to manually install in Python 3.4 after it had been installed on 3.3. I finally was able to solve it by installing the wheel and running pip from the Python34 directory.

1) download wheel from here: http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml

2) cd Python34\Scripts

3) pip.exe C:\Users\Home\Downloads\lxml- ......... .whl


回答 6

只需安装要求:

sudo apt-get install libxml2-dev libxslt-dev python-dev

现在,您可以使用pip软件包管理工具进行安装:

pip install lxml

just install requirements:

sudo apt-get install libxml2-dev libxslt-dev python-dev

Now, you can install it with pip package management tool:

pip install lxml

For python3 users:

sudo apt-get install libxml2-dev libxslt-dev python3-dev

pip3 install lxml

回答 7

error: command 'gcc' failed with exit status 1

yum remove audit
yum install gcc
yum install libxslt-devel libxml2-devel

cd lxml-x.x.x
python setup.py build
python setup.py install
error: command 'gcc' failed with exit status 1

yum remove audit
yum install gcc
yum install libxslt-devel libxml2-devel

cd lxml-x.x.x
python setup.py build
python setup.py install

回答 8

我正在使用Ubuntu 14.04,这可以为我解决问题

sudo apt-get build-dep python3-lxml
sudo apt-get install libxml2-dev libxslt-dev python-dev

I am using Ubuntu 14.04 and this solves the issue for me

sudo apt-get build-dep python3-lxml
sudo apt-get install libxml2-dev libxslt-dev python-dev

回答 9

STATIC_DEPS=true easy_install lxml
STATIC_DEPS=true easy_install lxml

回答 10

安装lxml二进制文件即可解决问题。检查一下

Installing a lxml binary would do the trick. Check this


回答 11

sudo apt install libxslt-dev libxml2-dev

然后尝试升级python setuptools

pip install -U pip setuptools

这应该解决它。

sudo apt install libxslt-dev libxml2-dev

and then try upgrading python setuptools

pip install -U pip setuptools

this should resolve it.


回答 12

我在点子安装lxml时遇到了这个问题。我的CentOS实例正在使用python 2.6抛出此错误。

为了解决这个问题,我做了以下操作以在Python 2.7中运行:

  1. 跑: sudo yum install python-devel
  2. sudo yum install libxslt-devel libxml2-devel
  3. 使用Python 2.7通过运行命令/usr/bin/python2.7 YOUR_PYTHON_COMMAND (对我来说是/usr/bin/python2.7 -m pip install lxml

I was having this issue with a pip install of lxml. My CentOS instance was using python 2.6 which was throwing this error.

To get around this I did the following to run with Python 2.7:

  1. Run: sudo yum install python-devel
  2. Run sudo yum install libxslt-devel libxml2-devel
  3. Use Python 2.7 to run your command by using /usr/bin/python2.7 YOUR_PYTHON_COMMAND (For me it was /usr/bin/python2.7 -m pip install lxml)

回答 13

pymemcompat.h:10: fatal error: Python.h: 没有那个文件或目录

男孩,您应该将错误日志发布到,LANG=C否则人们将无法从日志中找到真正的原因。上面的日志说:没有这样的文件或目录。

这意味着您应该安装Python的开发包。在Debian风格的发行版上通常是“ python-dev”,而在RHEL风格的发行版上通常是“ python-devel”。

pymemcompat.h:10: fatal error: Python.h: 没有那个文件或目录

Boy you should post your error log with LANG=C or people can’t get the real cause from your log. The log above says: No such file or directory.

That means you should install the develop package of Python. That’s usually “python-dev” on Debian flavored distro, and “python-devel” on RHEL flavored distro.


回答 14

以上所有答案均假设用户有权访问特权/根帐户以安装所需的库。要在本地安装它,您需要执行以下步骤。仅显示概述,因为根据您可能缺少的依赖项,可能会涉及一些步骤

1.下载并编译libxml2-2.9.1和libxslt-1.1.28(版本可能会更改)

2.使用configure将libxml和libxslt的每个安装路径配置为某个本地目录。例如./configure --prefix=/home_dir/dependencies/libxslt_path

3. make然后运行make install

4,从源代码下载并编译lxml

All the answers above assume the user has access to a privileged/root account to install the required libraries. To install it locally you will need to do the following steps. Only showed the overview since the steps can get a little involved depending on the dependencies that you might be missing

1.Download and Compile libxml2-2.9.1 & libxslt-1.1.28(versions might change)

2.Configure each install path for both libxml and libxslt to be some local directory using configure. Ex. ./configure --prefix=/home_dir/dependencies/libxslt_path

3.Run make then make install

4.Download and compile lxml from source


回答 15

这对我有效,12.04,python2.7.6

sudo apt-get install libxml2 libxml2-dev libxslt1-dev
sudo pip install lxml

This works for me, 12.04, python2.7.6

sudo apt-get install libxml2 libxml2-dev libxslt1-dev
sudo pip install lxml

回答 16

我知道我迟到了演出,

但这将有助于解决其他问题

mkdir ~/tmp
export TMPDIR=~/tmp
STATIC_DEPS=true easy_install-2.7 lxml

设置TMPDIR将确保该构建可以运行它需要运行的所有内容,而设置STATIC_DEPS将告诉它引入自己的libxml2和libxslt2,而不是使用服务器上安装的旧版本。

I know I am late to the show,

But this will help if nothing else works out

mkdir ~/tmp
export TMPDIR=~/tmp
STATIC_DEPS=true easy_install-2.7 lxml

Setting TMPDIR will ensure that the build can run everything that it needs to run, and setting STATIC_DEPS will tell it to pull in its own libxml2 and libxslt2, instead of using the old versions installed on the server.


回答 17

在Windows 8上使用cygwin 64。

我有…

pip install lxml(…)

gcc -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -ggdb -O2 -pipe -Wimplicit-function-declaration -fdebug-prefix-map=/usr/src/ports/python3/python3-3.2.5-4.x86_64/build=/usr/src/debug/python3-3.2.5-4 -fdebug-prefix-map=/usr/src/ports/python3/python3-3.2.5-4.x86_64/src/Python-3.2.5=/usr/src/debug/python3-3.2.5-4 -I/usr/include/libxml2 -I/tmp/pip-build-b8ybku/lxml/src/lxml/includes -I/usr/include/python3.2m -c src/lxml/lxml.etree.c -o build/temp.cygwin-1.7.34-x86_64-3.2/src/lxml/lxml.etree.o -w

src/lxml/lxml.etree.c:8:22: fatal error: pyconfig.h: No such file or directory

compilation terminated.

/usr/lib/python3.2/distutils/dist.py:257: UserWarning: Unknown distribution option: 'bugtrack_url'

  warnings.warn(msg)

error: command 'gcc' failed with exit status 1

----------------------------------------
Command "/usr/bin/python3.2m -c "import setuptools, tokenize;__file__='/tmp/pip-build-b8ybku/lxml/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-u3vwj8-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-b8ybku/lxml

我尝试了一切,直到我意识到新的cygwin工具链弄乱了python逻辑。cygwin安装一个称为“ realgcc”的编译器,它不是真正的 gcc。

安装gcc。例如:

 apt-cyg install gcc-g++

Using cygwin 64 with Windows 8.

I have got…

pip install lxml (…)

gcc -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -ggdb -O2 -pipe -Wimplicit-function-declaration -fdebug-prefix-map=/usr/src/ports/python3/python3-3.2.5-4.x86_64/build=/usr/src/debug/python3-3.2.5-4 -fdebug-prefix-map=/usr/src/ports/python3/python3-3.2.5-4.x86_64/src/Python-3.2.5=/usr/src/debug/python3-3.2.5-4 -I/usr/include/libxml2 -I/tmp/pip-build-b8ybku/lxml/src/lxml/includes -I/usr/include/python3.2m -c src/lxml/lxml.etree.c -o build/temp.cygwin-1.7.34-x86_64-3.2/src/lxml/lxml.etree.o -w

src/lxml/lxml.etree.c:8:22: fatal error: pyconfig.h: No such file or directory

compilation terminated.

/usr/lib/python3.2/distutils/dist.py:257: UserWarning: Unknown distribution option: 'bugtrack_url'

  warnings.warn(msg)

error: command 'gcc' failed with exit status 1

----------------------------------------
Command "/usr/bin/python3.2m -c "import setuptools, tokenize;__file__='/tmp/pip-build-b8ybku/lxml/setup.py';exec(compile(getattr(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --record /tmp/pip-u3vwj8-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-b8ybku/lxml

I have tried everything until I realized a new cygwin toolchain has messed up python logic. cygwin install a compiler called “realgcc” that is not a real gcc.

Solution

Install gcc. Ex:

 apt-cyg install gcc-g++

回答 18

唯一对我有帮助的是

sudo apt-get install python3.5-dev

The only thing helped for me was

sudo apt-get install python3.5-dev

回答 19

我在Linux机器上遇到了相同的错误。如果您也访问了他们文档中的他们的网站。因此,如果您在Linux机器上遇到这种错误,请尝试以下命令,

# apt install libxml2-dev libxslt-dev python-dev

# pip install lxml==3.4.4

I got the same error on my Linux machine.If you go to their website that’s in their documentation as well.So if you get this kind of error in Linux machine, please try out these commands,

# apt install libxml2-dev libxslt-dev python-dev

# pip install lxml==3.4.4


回答 20

我正在使用Ubuntu 12,这对我有用:

sudo apt-get install libxml2-dev
sudo apt-get install libxslt1-dev
sudo apt-get install python-dev
sudo apt-get install lxml

I am using Ubuntu 12, and this works for me:

sudo apt-get install libxml2-dev
sudo apt-get install libxslt1-dev
sudo apt-get install python-dev
sudo apt-get install lxml

回答 21

如果已安装libxml2和libxslt,则可能需要在libxml2和libxslt之间创建符号链接,以指向python2.6的包含路径。您也可以尝试添加INCLUDE环境参数。因为gcc命令仅搜索以下路径:-I / usr / include / python2.6。

If you have installed the libxml2 and libxslt, maybe you need to create a symbolic link between libxml2 and libxslt path to python2.6 include path. Also you can try to add INCLUDE environment argument. Because the gcc command only search this path: -I/usr/include/python2.6.


回答 22


回答 23

在osx 10.10.5和virtualenv中,也许您可​​以解决以下问题:

sudo C_INCLUDE_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/libxml2:/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/libxml2/libxml:/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include pip install -r lxml

On osx 10.10.5 and in a virtualenv, maybe you can resolve that problem like below:

sudo C_INCLUDE_PATH=/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/libxml2:/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include/libxml2/libxml:/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.11.sdk/usr/include pip install -r lxml

回答 24

我在Windows机器上工作。这是成功安装lxml(使用python 2.6和更高版本)的一些指示。

安装以下内容:

  1. MingGW。
  2. libxml2版本2.7.0或更高版本。
  3. libxslt 1.1.23版或更高版本。

不能在上使用所有功能pip install

libxml2的Windows二进制文件位于此处

libxslt在这里找到。

完成以上两个步骤后,

做:pip install lxml

另一个解决方法是使用PyPI的稳定版本或Christoph Gohlke的非官方Windows二进制文件(在此处找到)。

I work on a Windows machine. And here are some pointers for successful installation of lxml (with python 2.6 and later).

Have the following installed:

  1. MingGW.
  2. libxml2 version 2.7.0 or later.
  3. libxslt version 1.1.23 or later.

All are not available at a pip install.

libxml2’s windows binary is found here.

libxslt is found here.

After you are done with the above two,

do : pip install lxml.

Another workaround is using the stable releases from PyPI or the unofficial Windows binaries by Christoph Gohlke (found here).


回答 25

结合使用Windows 7和Cygwin,我发现:

Compile failed: command 'gcc' failed with exit status 1
cc -I/usr/include/libxml2 -I/usr/include/libxml2 -c /tmp/xmlXPathInitZsgdMQ.c -o tmp/xmlXPathInitZsgdMQ.o
*********************************************************************************
Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?
*********************************************************************************
error: command 'gcc' failed with exit status 1

我通过安装修复它 mingw64-x86_64-libxslt

Using Windows 7 with Cygwin, I came across:

Compile failed: command 'gcc' failed with exit status 1
cc -I/usr/include/libxml2 -I/usr/include/libxml2 -c /tmp/xmlXPathInitZsgdMQ.c -o tmp/xmlXPathInitZsgdMQ.o
*********************************************************************************
Could not find function xmlCheckVersion in library libxml2. Is libxml2 installed?
*********************************************************************************
error: command 'gcc' failed with exit status 1

I fixed it by installing mingw64-x86_64-libxslt


回答 26

对于Windows:

pip install --upgrade pip wheel
pip install bzt
pip install lxml

For Windows:

pip install --upgrade pip wheel
pip install bzt
pip install lxml

回答 27

这两个软件包需要单独安装,通常无法使用pip… 安装,因此,对于FreeBSD:

Download a compressed snapshot of the Ports Collection into /var/db/portsnap:
# portsnap fetch
When running Portsnap for the first time, extract the snapshot into /usr/ports:
# portsnap extract
After the first use of Portsnap has been completed as shown above, /usr/ports can be updated as needed by running:
# portsnap fetch
# portsnap update

Now Install:
cd /usr/ports/textproc/libxml2
make install clean

cd /usr/ports/textproc/libxslt
make install clean

你应该很好…

These two packages need to be installed separately and usually can’t be installed using pip…Therefore, for FreeBSD:

Download a compressed snapshot of the Ports Collection into /var/db/portsnap:
# portsnap fetch
When running Portsnap for the first time, extract the snapshot into /usr/ports:
# portsnap extract
After the first use of Portsnap has been completed as shown above, /usr/ports can be updated as needed by running:
# portsnap fetch
# portsnap update

Now Install:
cd /usr/ports/textproc/libxml2
make install clean

cd /usr/ports/textproc/libxslt
make install clean

You should be good to go…