标签归档:install

如何在Python中列出所有已安装的软件包及其版本?

问题:如何在Python中列出所有已安装的软件包及其版本?

Python中是否有办法列出所有已安装的软件包及其版本?

我知道我可以进入python/Lib/site-packages并查看存在哪些文件和目录,但是我觉得这很尴尬。我正在寻找的东西类似于npm listNPM-LS

Is there a way in Python to list all installed packages and their versions?

I know I can go inside python/Lib/site-packages and see what files and directories exist, but I find this very awkward. What I’m looking for something that is similar to npm list i.e. npm-ls.


回答 0

如果您已经进行了pip安装,并且想查看安装程序工具已安装了哪些软件包,则可以简单地调用以下命令:

pip freeze

它还将包含已安装软件包的版本号。

更新资料

pip已更新,可以产生与pip freeze调用相同的输出:

pip list

注意

的输出pip list格式不同,因此,如果您有一些shell脚本来解析(可能是获取版本号)的输出,freeze并且想要将脚本更改为call list,则需要更改解析代码。

If you have pip install and you want to see what packages have been installed with your installer tools you can simply call this:

pip freeze

It will also include version numbers for the installed packages.

Update

pip has been updated to also produce the same output as pip freeze by calling:

pip list

Note

The output from pip list is formatted differently, so if you have some shell script that parses the output (maybe to grab the version number) of freeze and want to change your script to call list, you’ll need to change your parsing code.


回答 1

help('modules') 应该为你做。

在IPython中:

In [1]: import                      #import press-TAB
Display all 631 possibilities? (y or n)
ANSI                   audiodev               markupbase
AptUrl                 audioop                markupsafe
ArgImagePlugin         avahi                  marshal
BaseHTTPServer         axi                    math
Bastion                base64                 md5
BdfFontFile            bdb                    mhlib
BmpImagePlugin         binascii               mimetools
BufrStubImagePlugin    binhex                 mimetypes
CDDB                   bisect                 mimify
CDROM                  bonobo                 mmap
CGIHTTPServer          brlapi                 mmkeys
Canvas                 bsddb                  modulefinder
CommandNotFound        butterfly              multifile
ConfigParser           bz2                    multiprocessing
ContainerIO            cPickle                musicbrainz2
Cookie                 cProfile               mutagen
Crypto                 cStringIO              mutex
CurImagePlugin         cairo                  mx
DLFCN                  calendar               netrc
DcxImagePlugin         cdrom                  new
Dialog                 cgi                    nis
DiscID                 cgitb                  nntplib
DistUpgrade            checkbox               ntpath

help('modules') should do it for you.

in IPython :

In [1]: import                      #import press-TAB
Display all 631 possibilities? (y or n)
ANSI                   audiodev               markupbase
AptUrl                 audioop                markupsafe
ArgImagePlugin         avahi                  marshal
BaseHTTPServer         axi                    math
Bastion                base64                 md5
BdfFontFile            bdb                    mhlib
BmpImagePlugin         binascii               mimetools
BufrStubImagePlugin    binhex                 mimetypes
CDDB                   bisect                 mimify
CDROM                  bonobo                 mmap
CGIHTTPServer          brlapi                 mmkeys
Canvas                 bsddb                  modulefinder
CommandNotFound        butterfly              multifile
ConfigParser           bz2                    multiprocessing
ContainerIO            cPickle                musicbrainz2
Cookie                 cProfile               mutagen
Crypto                 cStringIO              mutex
CurImagePlugin         cairo                  mx
DLFCN                  calendar               netrc
DcxImagePlugin         cdrom                  new
Dialog                 cgi                    nis
DiscID                 cgitb                  nntplib
DistUpgrade            checkbox               ntpath

回答 2

如果要获取有关已安装的python发行版的信息,并且不想使用其cmd控制台或终端,而希望通过python代码,则可以使用以下代码(经过python 3.4测试):

import pip #needed to use the pip functions
for i in pip.get_installed_distributions(local_only=True):
    print(i)

pip.get_installed_distributions(local_only=True)函数调用返回一个可迭代的对象,由于使用了for循环和打印功能,该可迭代对象中包含的元素被换行符(\n)分开打印。结果(取决于您安装的发行版)将如下所示:

cycler 0.9.0
decorator 4.0.4
ipykernel 4.1.0
ipython 4.0.0
ipython-genutils 0.1.0
ipywidgets 4.0.3
Jinja2 2.8
jsonschema 2.5.1
jupyter 1.0.0
jupyter-client 4.1.1
#... and so on...

If you want to get information about your installed python distributions and don’t want to use your cmd console or terminal for it, but rather through python code, you can use the following code (tested with python 3.4):

import pip #needed to use the pip functions
for i in pip.get_installed_distributions(local_only=True):
    print(i)

The pip.get_installed_distributions(local_only=True) function-call returns an iterable and because of the for-loop and the print function the elements contained in the iterable are printed out separated by new line characters (\n). The result will (depending on your installed distributions) look something like this:

cycler 0.9.0
decorator 4.0.4
ipykernel 4.1.0
ipython 4.0.0
ipython-genutils 0.1.0
ipywidgets 4.0.3
Jinja2 2.8
jsonschema 2.5.1
jupyter 1.0.0
jupyter-client 4.1.1
#... and so on...

回答 3

可以尝试:蛋黄

对于安装蛋黄,请尝试:

easy_install yolk

Yolk是一个Python工具,用于获取有关已安装的Python软件包的信息并查询可在PyPI(Python软件包索引)上使用的软件包。

您可以通过查询PyPI查看哪些软件包处于活动状态,非活动状态或处于开发模式,并向您显示哪些软件包可用。

You can try : Yolk

For install yolk, try:

easy_install yolk

Yolk is a Python tool for obtaining information about installed Python packages and querying packages avilable on PyPI (Python Package Index).

You can see which packages are active, non-active or in development mode and show you which have newer versions available by querying PyPI.


回答 4

要在更高版本的pip(在上测试)上运行此命令,请pip==10.0.1使用以下命令:

from pip._internal.operations.freeze import freeze
for requirement in freeze(local_only=True):
    print(requirement)

To run this in later versions of pip (tested on pip==10.0.1) use the following:

from pip._internal.operations.freeze import freeze
for requirement in freeze(local_only=True):
    print(requirement)

回答 5

从命令行

python -c help('modules')

可用于查看所有模块以及特定模块

python -c help('os')

对于Linux,以下版本适用

python -c "help('os')"

from command line

python -c help('modules')

can be used to view all modules, and for specific modules

python -c help('os')

For Linux below will work

python -c "help('os')"

回答 6

是!您应该将pip用作python包管理器(http://pypi.python.org/pypi/pip

使用pip安装的软件包,您可以

pip freeze

它将列出所有已安装的软件包。您可能还应该使用virtualenvvirtualenvwrapper。当您开始一个新项目时,您可以

mkvirtualenv my_new_project

然后(在virtualenv内)

pip install all_your_stuff

这样,您可以workon my_new_project然后pip freeze查看为该virtualenv / project安装了哪些软件包。

例如:

  ~  mkvirtualenv yo_dude
New python executable in yo_dude/bin/python
Installing setuptools............done.
Installing pip...............done.
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/predeactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/postdeactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/preactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/postactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/get_env_details

(yo_dude)➜  ~  pip install django
Downloading/unpacking django
  Downloading Django-1.4.1.tar.gz (7.7Mb): 7.7Mb downloaded
  Running setup.py egg_info for package django

Installing collected packages: django
  Running setup.py install for django
    changing mode of build/scripts-2.7/django-admin.py from 644 to 755

    changing mode of /Users/aaylward/dev/virtualenvs/yo_dude/bin/django-admin.py to 755
Successfully installed django
Cleaning up...

(yo_dude)➜  ~  pip freeze
Django==1.4.1
wsgiref==0.1.2

(yo_dude)➜  ~  

或者,如果您有一个带有requirements.pip文件的python软件包,

mkvirtualenv my_awesome_project
pip install -r requirements.pip
pip freeze

会成功的

yes! you should be using pip as your python package manager ( http://pypi.python.org/pypi/pip )

with pip installed packages, you can do a

pip freeze

and it will list all installed packages. You should probably also be using virtualenv and virtualenvwrapper. When you start a new project, you can do

mkvirtualenv my_new_project

and then (inside that virtualenv), do

pip install all_your_stuff

This way, you can workon my_new_project and then pip freeze to see which packages are installed for that virtualenv/project.

for example:

➜  ~  mkvirtualenv yo_dude
New python executable in yo_dude/bin/python
Installing setuptools............done.
Installing pip...............done.
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/predeactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/postdeactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/preactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/postactivate
virtualenvwrapper.user_scripts creating /Users/aaylward/dev/virtualenvs/yo_dude/bin/get_env_details

(yo_dude)➜  ~  pip install django
Downloading/unpacking django
  Downloading Django-1.4.1.tar.gz (7.7Mb): 7.7Mb downloaded
  Running setup.py egg_info for package django

Installing collected packages: django
  Running setup.py install for django
    changing mode of build/scripts-2.7/django-admin.py from 644 to 755

    changing mode of /Users/aaylward/dev/virtualenvs/yo_dude/bin/django-admin.py to 755
Successfully installed django
Cleaning up...

(yo_dude)➜  ~  pip freeze
Django==1.4.1
wsgiref==0.1.2

(yo_dude)➜  ~  

or if you have a python package with a requirements.pip file,

mkvirtualenv my_awesome_project
pip install -r requirements.pip
pip freeze

will do the trick


回答 7

我的看法:

#!/usr/bin/env python3

import pkg_resources

dists = [str(d).replace(" ","==") for d in pkg_resources.working_set]
for i in dists:
    print(i)

My take:

#!/usr/bin/env python3

import pkg_resources

dists = [str(d).replace(" ","==") for d in pkg_resources.working_set]
for i in dists:
    print(i)

回答 8

这是一种使用方法来PYTHONPATH代替python libs dir的绝对路径的方法:

for d in `echo "${PYTHONPATH}" | tr ':' '\n'`; do ls "${d}"; done

[ 10:43 Jonathan@MacBookPro-2 ~/xCode/Projects/Python for iOS/trunk/Python for iOS/Python for iOS ]$ for d in `echo "$PYTHONPATH" | tr ':' '\n'`; do ls "${d}"; done
libpython2.7.dylib pkgconfig          python2.7
BaseHTTPServer.py      _pyio.pyc              cgitb.pyo              doctest.pyo            htmlentitydefs.pyc     mimetools.pyc          plat-mac               runpy.py               stringold.pyc          traceback.pyo
BaseHTTPServer.pyc     _pyio.pyo              chunk.py               dumbdbm.py             htmlentitydefs.pyo     mimetools.pyo          platform.py            runpy.pyc              stringold.pyo          tty.py
BaseHTTPServer.pyo     _strptime.py           chunk.pyc              dumbdbm.pyc            htmllib.py             mimetypes.py           platform.pyc           runpy.pyo              stringprep.py          tty.pyc
Bastion.py             _strptime.pyc          chunk.pyo              dumbdbm.pyo            htmllib.pyc            mimetypes.pyc          platform.pyo           sched.py               stringprep.pyc         tty.pyo
Bastion.pyc            _strptime.pyo          cmd.py
....

Here’s a way to do it using PYTHONPATH instead of the absolute path of your python libs dir:

for d in `echo "${PYTHONPATH}" | tr ':' '\n'`; do ls "${d}"; done

[ 10:43 Jonathan@MacBookPro-2 ~/xCode/Projects/Python for iOS/trunk/Python for iOS/Python for iOS ]$ for d in `echo "$PYTHONPATH" | tr ':' '\n'`; do ls "${d}"; done
libpython2.7.dylib pkgconfig          python2.7
BaseHTTPServer.py      _pyio.pyc              cgitb.pyo              doctest.pyo            htmlentitydefs.pyc     mimetools.pyc          plat-mac               runpy.py               stringold.pyc          traceback.pyo
BaseHTTPServer.pyc     _pyio.pyo              chunk.py               dumbdbm.py             htmlentitydefs.pyo     mimetools.pyo          platform.py            runpy.pyc              stringold.pyo          tty.py
BaseHTTPServer.pyo     _strptime.py           chunk.pyc              dumbdbm.pyc            htmllib.py             mimetypes.py           platform.pyc           runpy.pyo              stringprep.py          tty.pyc
Bastion.py             _strptime.pyc          chunk.pyo              dumbdbm.pyo            htmllib.pyc            mimetypes.pyc          platform.pyo           sched.py               stringprep.pyc         tty.pyo
Bastion.pyc            _strptime.pyo          cmd.py
....

回答 9

如果您使用的是Python:

conda list

会做的!参见:https : //conda.io/docs/_downloads/conda-cheatsheet.pdf

If you’re using anaconda:

conda list

will do it! See: https://conda.io/docs/_downloads/conda-cheatsheet.pdf


回答 10

如果需要从python内部运行,则可以调用子进程

from subprocess import PIPE, Popen

pip_process = Popen(["pip freeze"], stdout=PIPE,
                   stderr=PIPE, shell=True)
stdout, stderr = pip_process.communicate()
print(stdout.decode("utf-8"))

If this is needed to run from within python you can just invoke subprocess

from subprocess import PIPE, Popen

pip_process = Popen(["pip freeze"], stdout=PIPE,
                   stderr=PIPE, shell=True)
stdout, stderr = pip_process.communicate()
print(stdout.decode("utf-8"))

Python3:ImportError:使用模块多处理中的值时,没有名为“ _ctypes”的模块

问题:Python3:ImportError:使用模块多处理中的值时,没有名为“ _ctypes”的模块

我正在使用Ubuntu,并已安装Python 2.7.5和3.4.0。在Python 2.7.5中,我能够成功分配变量x = Value('i', 2),但在3.4.0中却不能。我正进入(状态:

Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "/usr/local/lib/python3.4/multiprocessing/context.py", line 132, in Value
      from .sharedctypes import Value
   File "/usr/local/lib/python3.4/multiprocessing/sharedctypes.py", line 10, in <
module>
   import ctypes
   File "/usr/local/lib/python3.4/ctypes/__init__.py", line 7, in <module>
      from _ctypes import Union, Structure, Array
ImportError: No module named '_ctypes'

我刚刚通过安装3.4.0的源代码更新到3.3.2。它安装在/usr/local/lib/python3.4中

我是否正确更新到Python 3.4?

我注意到一件事,Python 3.4安装在usr / local / lib中,而Python 3.3.2仍然安装在usr / lib中,因此它没有被覆盖。

I am using Ubuntu and have installed Python 2.7.5 and 3.4.0. In Python 2.7.5 I am able to successfully assign a variable x = Value('i', 2), but not in 3.4.0. I am getting:

Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "/usr/local/lib/python3.4/multiprocessing/context.py", line 132, in Value
      from .sharedctypes import Value
   File "/usr/local/lib/python3.4/multiprocessing/sharedctypes.py", line 10, in <
module>
   import ctypes
   File "/usr/local/lib/python3.4/ctypes/__init__.py", line 7, in <module>
      from _ctypes import Union, Structure, Array
ImportError: No module named '_ctypes'

I just updated to 3.3.2 through installing the source of 3.4.0. It installed in /usr/local/lib/python3.4.

Did I update to Python 3.4 correctly?

One thing I noticed that Python 3.4 is installed in usr/local/lib, while Python 3.3.2 is still installed in usr/lib, so it was not overwritten.


回答 0

安装libffi-dev并重新安装python3.7对我来说解决了这个问题。

干净地构建py 3.7 libffi-dev 是必需的,否则以后的工作将失败

如果使用RHEL / Fedora:

yum install libffi-devel

要么

sudo dnf install libffi-devel

如果使用Debian / Ubuntu:

sudo apt-get install libffi-dev

Installing libffi-dev and re-installing python3.7 fixed the problem for me.

to cleanly build py 3.7 libffi-dev is required or else later stuff will fail

If using RHEL/Fedora:

yum install libffi-devel

or

sudo dnf install libffi-devel

If using Debian/Ubuntu:

sudo apt-get install libffi-dev

回答 1

在新的Debian映像上,克隆https://github.com/python/cpython并运行:

sudo apt-get update
sudo apt-get upgrade
sudo apt-get dist-upgrade
sudo apt-get install build-essential python-dev python-setuptools python-pip python-smbus
sudo apt-get install libncursesw5-dev libgdbm-dev libc6-dev
sudo apt-get install zlib1g-dev libsqlite3-dev tk-dev
sudo apt-get install libssl-dev openssl
sudo apt-get install libffi-dev

现在执行configure上面克隆的文件:

./configure
make # alternatively `make -j 4` will utilize 4 threads
sudo make altinstall

安装了3.7版并为我工作。

轻微更新

看来我说过我会用一些更多的解释来更新此答案,两年后,我没有太多补充。

  • 这篇SO帖子解释了为什么python-dev可能需要某些库。
  • 这篇SO文章解释了为什么可能在make命令中使用与altinstall相反的install参数。

除此之外,我猜测选择是通读cpython代码库以查找#include需要满足的指令,但是我通常要做的是继续尝试安装软件包,并继续通读安装所需软件包的输出,直到找到为止。成功。

让我想起了工程师,经理和程序员的故事,他们的汽车从山上滚下来

On a fresh Debian image, cloning https://github.com/python/cpython and running:

sudo apt-get update
sudo apt-get upgrade
sudo apt-get dist-upgrade
sudo apt-get install build-essential python-dev python-setuptools python-pip python-smbus
sudo apt-get install libncursesw5-dev libgdbm-dev libc6-dev
sudo apt-get install zlib1g-dev libsqlite3-dev tk-dev
sudo apt-get install libssl-dev openssl
sudo apt-get install libffi-dev

Now execute the configure file cloned above:

./configure
make # alternatively `make -j 4` will utilize 4 threads
sudo make altinstall

Got 3.7 installed and working for me.

SLIGHT UPDATE

Looks like I said I would update this answer with some more explanation and two years later I don’t have much to add.

  • this SO post explains why certain libraries like python-dev might be necessary.
  • this SO post explains why one might use the altinstall as opposed to install argument in the make command.

Aside from that I guess the choice would be to either read through the cpython codebase looking for #include directives that need to be met, but what I usually do is keep trying to install the package and just keep reading through the output installing the required packages until it succeeds.

Reminds me of the story of the Engineer, the Manager and the Programmer whose car rolls down a hill.


回答 2

如果您使用pyenv并在Debian / Raspbian / Ubuntu上收到错误“没有名为’_ctypes’的模块”(例如我是),则需要运行以下命令:

sudo apt-get install libffi-dev
pyenv uninstall 3.7.6
pyenv install 3.7.6

将您的python版本而不是3.7.6

If you use pyenv and get error “No module named ‘_ctypes'” (like i am) on Debian/Raspbian/Ubuntu you need to run this commands:

sudo apt-get install libffi-dev
pyenv uninstall 3.7.6
pyenv install 3.7.6

Put your version of python instead of 3.7.6


回答 3

在CentOS或任何Redhat Linux机器上安装Python 3.7的详细步骤:

  1. https://www.python.org/ftp/python/3.7.0/Python-3.7.0.tar.xz下载Python
  2. 将内容提取到新文件夹中
  3. 在同一目录中打开终端
  4. 逐步运行以下代码:
sudo yum -y install gcc gcc-c++ 
sudo yum -y install zlib zlib-devel
sudo yum -y install libffi-devel 
./configure
make
make install

Detailed steps to install Python 3.7 in CentOS or any redhat linux machine:

  1. Download Python from https://www.python.org/ftp/python/3.7.0/Python-3.7.0.tar.xz
  2. Extract the content in new folder
  3. Open Terminal in the same directory
  4. Run below code step by step :
sudo yum -y install gcc gcc-c++ 
sudo yum -y install zlib zlib-devel
sudo yum -y install libffi-devel 
./configure
make
make install

回答 4

以为我会添加Centos安装:

sudo yum -y install gcc gcc-c++ 
sudo yum -y install zlib zlib-devel
sudo yum -y install libffi-devel 

检查python版本:

python3 -V

创建virtualenv:

virtualenv -p python3 venv

Thought I’d add the Centos installs:

sudo yum -y install gcc gcc-c++ 
sudo yum -y install zlib zlib-devel
sudo yum -y install libffi-devel 

Check python version:

python3 -V

Create virtualenv:

virtualenv -p python3 venv


回答 5

尝试使用下一个命令在Ubuntu 18.04中安装Python 3.7.3时遇到此错误。运行后安装成功(如建议在这里)。这个问题在那里解决了。$ pyenv install 3.7.3$ sudo apt-get update && sudo apt-get install libffi-dev

I run into this error when I tried to install Python 3.7.3 in Ubuntu 18.04 with next command: $ pyenv install 3.7.3. Installation succeeded after running $ sudo apt-get update && sudo apt-get install libffi-dev (as suggested here). The issue was solved there.


回答 6

没有解决方案。您必须再次重新编译python。一旦所有必需的软件包都已完全安装。

请遵循以下步骤:

  1. 安装所需的软件包
  2. ./configure --enable-optimizations

https://gist.github.com/jerblack/798718c1910ccdd4ede92481229043be

None of the solution worked. You have to recompile your python again; once all the required packages were completely installed.

Follow this:

  1. Install required packages
  2. Run ./configure --enable-optimizations

https://gist.github.com/jerblack/798718c1910ccdd4ede92481229043be


回答 7

请参阅此线程,以进行libffi的自定义安装,Python3.7很难找到libffi的库位置。另一种方法是CONFIGURE_LDFLAGS在Makefile中设置变量,例如CONFIGURE_LDFLAGS="-L/path/to/libffi-3.2.1/lib64"

Refer to this thread or this thread, for customized installation of libffi, it is difficult for Python3.7 to find the library location of libffi. An alternative method is to set the CONFIGURE_LDFLAGS variable in the Makefile, for example CONFIGURE_LDFLAGS="-L/path/to/libffi-3.2.1/lib64".


回答 8

我的解决方案:使用apt-get安装libffi-dev并没有帮助。但这有帮助:从源代码安装libffi,然后从源代码安装Python 3.8。

我的配置:Ubuntu 16.04 LTS Python 3.8.2

一步步:

从Visual Studio Code启动调试器并运行时,出现错误消息“ ModuleNotFoundError:没有名为’_ctypes’的模块” python3 -c "import sklearn; sklearn.show_versions()"

  • https://github.com/libffi/libffi/releases下载libffi v3.3
  • 安装libtool:sudo apt-get install libtool libffi中的README.md文件提到autoconf和automake也是必需的。它们已经安装在我的系统上。
  • 在没有文档的情况下配置libffi:

./configure --disable-docs

make check

sudo make install

之后,我的python安装程序可以找到_ctypes。

My solution: Installing libffi-dev with apt-get didn’t help. But this helped: Installing libffi from source and then installing Python 3.8 from source.

My configuration: Ubuntu 16.04 LTS Python 3.8.2

Step by step:

I got the error message “ModuleNotFoundError: No module named ‘_ctypes'” when starting the debugger from Visual Studio Code, and when running python3 -c "import sklearn; sklearn.show_versions()".

  • download libffi v3.3 from https://github.com/libffi/libffi/releases
  • install libtool: sudo apt-get install libtool The file README.md from libffi mentions that autoconf and automake are also necessary. They were already installed on my system.
  • configure libffi without docs:

./configure --disable-docs

make check

sudo make install

After that my python installation could find _ctypes.


回答 9

这为我在Debian解决了相同的错误:

sudo apt-get install libffi-dev

然后再次编译

参考:issue31652

This solved the same error for me on Debian:

sudo apt-get install libffi-dev

and compile again

Reference: issue31652


回答 10

如果您不介意使用Miniconda,则默认情况下会安装必需的外部库和_ctypes。它确实占用更多空间,并且可能需要使用中等版本的Python(例如,本文撰写时为3.7.6而不是3.8.2)。

If you don’t mind using Miniconda, the necessary external libraries and _ctypes are installed by default. It does take more space and may require using a moderately older version of Python (e.g. 3.7.6 instead of 3.8.2 as of this writing).


回答 11

您必须从包管理器中加载缺少的php3(Python3)模块。如果您有Ubuntu,我建议Synaptic Package Manager

sudo apt-get install synaptic

您可以在那里简单地搜索缺少的模块。搜索ctypes并安装所有软件包。然后转到您的Python目录并执行

./configure
make install.

这应该可以解决您的问题。

You have to load the missing php3 (Python3) modules from the package manager. If you have Ubuntu I recommend the Synaptic Package Manager:

sudo apt-get install synaptic

There you can simply search for the missing modules. search for ctypes and install all the packages. Then go to your Python dir and do

./configure
make install.

This should solve your problem.


回答 12

如果您正在做某事,这里没有人会听您说,因为“您做错了方法”,但是由于太精明的原因,您必须“做错了方法”(例如,在我的情况下,它很快会降级为犯规)关于Devops团队超重母亲的某人的话),您需要首先:

获取libffi并将其以常规方式安装到用户安装区域中。

git clone https://github.com/libffi/libffi.git
cd libffi
./configure --prefix=path/to/your/install/root
make
make install

然后返回您的Python 3源代码,并在python源代码目录的顶层setup.py中找到这部分代码。

        ffi_inc = [sysconfig.get_config_var("LIBFFI_INCLUDEDIR")]
        if not ffi_inc or ffi_inc[0] == '':
            ffi_inc = find_file('ffi.h', [], inc_dirs)
        if ffi_inc is not None:
            ffi_h = ffi_inc[0] + '/ffi.h'
            if not os.path.exists(ffi_h):
                ffi_inc = None
                print('Header file {} does not exist'.format(ffi_h))
        ffi_lib = None
        if ffi_inc is not None:
            for lib_name in ('ffi', 'ffi_pic'):
                if (self.compiler.find_library_file(lib_dirs, lib_name)):
                    ffi_lib = lib_name
                    break

        ffi_lib="ffi"  # --- AND INSERT THIS LINE HERE THAT DOES NOT APPEAR ---
        if ffi_inc and ffi_lib:
            ext.include_dirs.extend(ffi_inc)
            ext.libraries.append(ffi_lib)
            self.use_system_libffi = True

并添加我在上面用注释标记的行。为什么有必要,为什么没有办法在Linux平台上配置尊重’–without-system-ffi`的功能,也许我会找出为什么在接下来的几个小时内“不支持”的原因,但是一切都有从那以后一直工作。否则,祝您好运… YMMV。

它的作用:只是重写那里的逻辑,并使编译器链接命令添加“ -lffi”,这是它真正需要的全部。如果您是用户安装的库,则只要您PKG_CONFIG_PATH包含include ,它就可以很好地检测标题path/to/your/install/root/lib/pkgconfig

If you are doing something nobody here will listen you about because “you’re doing it the wrong way”, but you have to do it “the wrong way” for reasons too asinine (for instance, in my case it quickly degrades into foul words about somebody on devops team overweight mother), you need to first:

Get libffi and install it into your user install area the usual way.

git clone https://github.com/libffi/libffi.git
cd libffi
./configure --prefix=path/to/your/install/root
make
make install

Then go back to your Python 3 source and find this part of the code in setup.py at the top level of the python source directory

        ffi_inc = [sysconfig.get_config_var("LIBFFI_INCLUDEDIR")]
        if not ffi_inc or ffi_inc[0] == '':
            ffi_inc = find_file('ffi.h', [], inc_dirs)
        if ffi_inc is not None:
            ffi_h = ffi_inc[0] + '/ffi.h'
            if not os.path.exists(ffi_h):
                ffi_inc = None
                print('Header file {} does not exist'.format(ffi_h))
        ffi_lib = None
        if ffi_inc is not None:
            for lib_name in ('ffi', 'ffi_pic'):
                if (self.compiler.find_library_file(lib_dirs, lib_name)):
                    ffi_lib = lib_name
                    break

        ffi_lib="ffi"  # --- AND INSERT THIS LINE HERE THAT DOES NOT APPEAR ---
        if ffi_inc and ffi_lib:
            ext.include_dirs.extend(ffi_inc)
            ext.libraries.append(ffi_lib)
            self.use_system_libffi = True

and add the line I have marked above with the comment. Why it is necessary, and why there is no way to get configure to respect ‘–without-system-ffi` on Linux platforms, perhaps I will find out why that is “unsupported” in the next couple of hours, but everything has worked ever since. Otherwise, best of luck… YMMV.

WHAT IT DOES: just overrides the logic there and causes the compiler linking command to add “-lffi” which is all that it really needs. If you have the library user-installed, it is probably detecting the headers fine as long as your PKG_CONFIG_PATH includes path/to/your/install/root/lib/pkgconfig.


pip安装失败,出现以下错误:OSError:[Errno 13]目录权限被拒绝

问题:pip安装失败,出现以下错误:OSError:[Errno 13]目录权限被拒绝

pip install -r requirements.txt失败,但以下情况除外OSError: [Errno 13] Permission denied: '/usr/local/lib/...。有什么问题,我该如何解决?(我正在尝试设置Django

Installing collected packages: amqp, anyjson, arrow, beautifulsoup4, billiard, boto, braintree, celery, cffi, cryptography, Django, django-bower, django-braces, django-celery, django-crispy-forms, django-debug-toolbar, django-disqus, django-embed-video, django-filter, django-merchant, django-pagination, django-payments, django-storages, django-vote, django-wysiwyg-redactor, easy-thumbnails, enum34, gnureadline, idna, ipaddress, ipython, kombu, mock, names, ndg-httpsclient, Pillow, pyasn1, pycparser, pycrypto, PyJWT, pyOpenSSL, python-dateutil, pytz, requests, six, sqlparse, stripe, suds-jurko
Cleaning up...
Exception:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 283, in run
    requirement_set.install(install_options, global_options, root=options.root_path)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1436, in install
    requirement.install(install_options, global_options, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 672, in install
    self.move_wheel_files(self.source_dir, root=root)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 902, in move_wheel_files
    pycompile=self.pycompile,
  File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 206, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 193, in clobber
    os.makedirs(destsubdir)
  File "/usr/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/amqp-1.4.6.dist-info'

pip install -r requirements.txt fails with the exception below OSError: [Errno 13] Permission denied: '/usr/local/lib/.... What’s wrong and how do I fix this? (I am trying to setup Django)

Installing collected packages: amqp, anyjson, arrow, beautifulsoup4, billiard, boto, braintree, celery, cffi, cryptography, Django, django-bower, django-braces, django-celery, django-crispy-forms, django-debug-toolbar, django-disqus, django-embed-video, django-filter, django-merchant, django-pagination, django-payments, django-storages, django-vote, django-wysiwyg-redactor, easy-thumbnails, enum34, gnureadline, idna, ipaddress, ipython, kombu, mock, names, ndg-httpsclient, Pillow, pyasn1, pycparser, pycrypto, PyJWT, pyOpenSSL, python-dateutil, pytz, requests, six, sqlparse, stripe, suds-jurko
Cleaning up...
Exception:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/pip/basecommand.py", line 122, in main
    status = self.run(options, args)
  File "/usr/lib/python2.7/dist-packages/pip/commands/install.py", line 283, in run
    requirement_set.install(install_options, global_options, root=options.root_path)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 1436, in install
    requirement.install(install_options, global_options, *args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 672, in install
    self.move_wheel_files(self.source_dir, root=root)
  File "/usr/lib/python2.7/dist-packages/pip/req.py", line 902, in move_wheel_files
    pycompile=self.pycompile,
  File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 206, in move_wheel_files
    clobber(source, lib_dir, True)
  File "/usr/lib/python2.7/dist-packages/pip/wheel.py", line 193, in clobber
    os.makedirs(destsubdir)
  File "/usr/lib/python2.7/os.py", line 157, in makedirs
    mkdir(name, mode)
OSError: [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/amqp-1.4.6.dist-info'

回答 0

选项a)创建一个virtualenv,将其激活并安装:

virtualenv .venv
source .venv/bin/activate
pip install -r requirements.txt

选项b)安装在您的homedir中:

pip install --user -r requirements.txt

我的建议使用安全(a)选项,以便该项目的需求不会干扰其他项目的需求。

Option a) Create a virtualenv, activate it and install:

virtualenv .venv
source .venv/bin/activate
pip install -r requirements.txt

Option b) Install in your homedir:

pip install --user -r requirements.txt

My recommendation use safe (a) option, so that requirements of this project do not interfere with other projects requirements.


回答 1

我们真的应该停止建议sudowith 的使用pip install。最好先尝试一下pip install --user。如果失败了,请查看此处的最高职位。

您不应使用的原因sudo如下:

当您使用进行pip操作时sudo,您将以root用户身份从Internet运行任意Python代码,这会带来很大的安全风险。如果有人在PyPI上放置了一个恶意项目,然后安装了该项目,则可以使攻击者具有对计算机的根访问权限。

We should really stop advising the use of sudo with pip install. It’s better to first try pip install --user. If this fails then take a look at the top post here.

The reason you shouldn’t use sudo is as follows:

When you run pip with sudo, you are running arbitrary Python code from the Internet as a root user, which is quite a big security risk. If someone puts up a malicious project on PyPI and you install it, you give an attacker root access to your machine.


回答 2

您试图在系统范围内的路径上安装软件包,而无须这样做。

  1. 通常,您可以根据自己的职责sudo临时获得超级用户 权限以便在系统范围的路径上安装软件包:

     sudo pip install -r requirements.txt

    sudo 在这里找到更多信息。

    实际上,这不是一个好主意,也没有很好的用例,请参阅@wim的评论。

  2. 如果您不想在系统范围内进行更改,则可以使用该标志将该包安装在每用户路径上--user

    它所需要的只是:

     pip install --user runloop requirements.txt
  3. 最后,对于更细粒度的控制,您还可以使用virtualenv,它可能是开发环境的最佳解决方案,尤其是当您正在处理多个项目并希望跟踪每个人的依赖关系时。

    用以下命令激活您的virtualenv

    $ my-virtualenv/bin/activate

    以下命令会将软件包安装在virtualenv内部(而不是系统范围的路径):

    pip install -r requirements.txt

You are trying to install a package on the system-wide path without having the permission to do so.

  1. In general, you can use sudo to temporarily obtain superuser permissions at your responsibility in order to install the package on the system-wide path:

     sudo pip install -r requirements.txt
    

    Find more about sudo here.

    Actually, this is a bad idea and there’s no good use case for it, see @wim’s comment.

  2. If you don’t want to make system-wide changes, you can install the package on your per-user path using the --user flag.

    All it takes is:

     pip install --user runloop requirements.txt
    
  3. Finally, for even finer grained control, you can also use a virtualenv, which might be the superior solution for a development environment, especially if you are working on multiple projects and want to keep track of each one’s dependencies.

    After activating your virtualenv with

    $ my-virtualenv/bin/activate

    the following command will install the package inside the virtualenv (and not on the system-wide path):

    pip install -r requirements.txt


回答 3

只是澄清在Linux(基于ubuntu)上由于权限被拒绝的错误而遭受了很多痛苦之后,什么对我有用,并利用了上面Bert的回答,我现在使用…

$ pip install --user <package-name>

或者如果在需求文件上运行pip …

$ pip install --user -r requirements.txt

并且这些功能对于每个pip安装(包括创建虚拟环境)都可靠地起作用。

然而,干净的解决方案在我进一步的经验已经安装python-virtualenv,并virtualenvwrappersudo apt-get install在系统级。

然后,在虚拟环境中,使用pip install不带--user标志AND不带sudo。整体上更清洁,更安全,更轻松。

Just clarifying what worked for me after much pain in linux (ubuntu based) on permission denied errors, and leveraging from Bert’s answer above, I now use …

$ pip install --user <package-name>

or if running pip on a requirements file …

$ pip install --user -r requirements.txt

and these work reliably for every pip install including creating virtual environments.

However, the cleanest solution in my further experience has been to install python-virtualenv and virtualenvwrapper with sudo apt-get install at the system level.

Then, inside virtual environments, use pip install without the --user flag AND without sudo. Much cleaner, safer, and easier overall.


回答 4

用户没有某些Python安装路径的写许可权。您可以通过以下方式给予许可:

sudo chown -R $USER /absolute/path/to/directory

因此,您应该授予权限,然后尝试再次安装它,如果您有新路径,还应该授予权限:

sudo chown -R $USER /usr/local/lib/python2.7/

User doesn’t have write permission for some Python installation paths. You can give the permission by:

sudo chown -R $USER /absolute/path/to/directory

So you should give permission, then try to install it again, if you have new paths you should also give permission:

sudo chown -R $USER /usr/local/lib/python2.7/

回答 5

如果需要权限,则不能将’pip’与’sudo’一起使用。您可以做一个技巧,以便可以使用“ sudo”并安装软件包。只需在您的pip命令前面放置“ sudo python -m …”即可。

sudo python -m pip install --user -r package_name

If you need permissions, you cannot use ‘pip’ with ‘sudo’. You can do a trick, so that you can use ‘sudo’ and install package. Just place ‘sudo python -m …’ in front of your pip command.

sudo python -m pip install --user -r package_name

回答 6

因此,由于完全不同的原因,我得到了相同的确切错误。由于完全独立但已知的Homebrew + pip错误,我遵循了Google Cloud帮助文档中列出的此变通办法,您可以在主目录中创建.pydistutils.cfg文件。该文件具有特殊的配置,只应将其用于安装某些库。安装软件包后,我应该已经删除了该disutils.cfg文件,但我忘记这样做了。所以对我来说实际上就是

rm ~/.pydistutils.cfg

然后一切正常。当然,如果确实有原因在该文件中有一些配置,那么您将不希望直接对该文件进行管理。但是,如果其他任何人都做了该解决方法,却忘了删除该文件,这对我来说就成功了!

So, I got this same exact error for a completely different reason. Due to a totally separate, but known Homebrew + pip bug, I had followed this workaround listed on Google Cloud’s help docs, where you create a .pydistutils.cfg file in your home directory. This file has special config that you’re only supposed to use for your install of certain libraries. I should have removed that disutils.cfg file after installing the packages, but I forgot to do so. So the fix for me was actually just…

rm ~/.pydistutils.cfg.

And then everything worked as normal. Of course, if you have some config in that file for a real reason, then you won’t want to just straight rm that file. But in case anyone else did that workaround, and forgot to remove that file, this did the trick for me!


回答 7

是适当的许可问题,

sudo chown -R $USER /path to your python installed directory

默认是 /usr/local/lib/python2.7/

或尝试

pip install --user -r package_name

然后说,pip install -r requirements.txt这将安装在您的环境中

不要说,sudo pip install -r requirements.txt这将安装到任意python路径中。

It is due permission problem,

sudo chown -R $USER /path to your python installed directory

default it would be /usr/local/lib/python2.7/

or try,

pip install --user -r package_name

and then say, pip install -r requirements.txt this will install inside your env

dont say, sudo pip install -r requirements.txt this is will install into arbitrary python path.


车轮文件安装

问题:车轮文件安装

如何安装.whl文件?我有Wheel库,但是我不知道如何使用它来安装那些文件。我有.whl文件,但我不知道如何运行它。请帮忙。

How do I install a .whl file? I have the Wheel library but I don’t know how to use it to install those files. I have the .whl file but I don’t know how to run it. Please help.


回答 0

通常,您会使用pip安装车轮之类的工具。如果这是针对PyPI上托管的项目的,则将其留给工具以发现并下载文件。

为此,您需要安装wheel软件包:

pip install wheel

然后,您可以告诉pip安装项目(如果有的话,它将下载车轮),或者直接安装车轮文件:

pip install project_name  # discover, download and install
pip install wheel_file.whl  # directly install the wheel

wheel模块一旦安装,也可以从命令行运行,您可以使用它来安装已经下载的轮子:

python -m wheel install wheel_file.whl

另请参阅wheel项目文档

You normally use a tool like pip to install wheels. Leave it to the tool to discover and download the file if this is for a project hosted on PyPI.

For this to work, you do need to install the wheel package:

pip install wheel

You can then tell pip to install the project (and it’ll download the wheel if available), or the wheel file directly:

pip install project_name  # discover, download and install
pip install wheel_file.whl  # directly install the wheel

The wheel module, once installed, also is runnable from the command line, you can use this to install already-downloaded wheels:

python -m wheel install wheel_file.whl

Also see the wheel project documentation.


回答 1

如果您的电脑上已经有一个wheel文件(.whl),则只需执行以下代码:

cd ../user
pip install file.whl

如果要从Web下载文件然后安装,请在命令行中执行以下操作:

pip install package_name

或者,如果您具有网址:

pip install http//websiteurl.com/filename.whl

这肯定会安装所需的文件。

注意:在使用Python 2时,我必须键入pip2而不是pip。

If you already have a wheel file (.whl) on your pc, then just go with the following code:

cd ../user
pip install file.whl

If you want to download a file from web, and then install it, go with the following in command line:

pip install package_name

or, if you have the url:

pip install http//websiteurl.com/filename.whl

This will for sure install the required file.

Note: I had to type pip2 instead of pip while using Python 2.


DistutilsOptionError:必须提供home或prefix / exec-prefix —不能同时提供

问题:DistutilsOptionError:必须提供home或prefix / exec-prefix —不能同时提供

我通常是通过pip安装python软件包的。

对于Google App Engine,我需要将软件包安装到另一个目标目录。

我试过了:

pip install -I flask-restful –target ./lib

但是它失败了:

必须提供home或prefix / exec-prefix-不能同时提供

我怎样才能使它工作?

I’ve been usually installed python packages through pip.

For Google App Engine, I need to install packages to another target directory.

I’ve tried:

pip install -I flask-restful –target ./lib

but it fails with:

must supply either home or prefix/exec-prefix — not both

How can I get this to work?


回答 0

您正在使用OS X和Homebrew吗?Homebrew python页面https://github.com/Homebrew/brew/blob/master/docs/Homebrew-and-Python.md指出了pip的已知问题和解决方法。

为我工作。

通过添加具有以下内容的〜/ .pydistutils.cfg文件,可以将此“空前缀”设置为默认值:

[install]
prefix=

编辑:不要使用此Homebrew建议的选项,它将破坏正常的点操作

Are you using OS X and Homebrew? The Homebrew python page https://github.com/Homebrew/brew/blob/master/docs/Homebrew-and-Python.md calls out a known issue with pip and a work around.

Worked for me.

You can make this “empty prefix” the default by adding a ~/.pydistutils.cfg file with the following contents:

[install]
prefix=

Edit: Do not use this Homebrew recommended option, it will break normal pip operations.


回答 1

我相信有一个更简单的解决方案(在macOS上使用Homebrew的Python),不会破坏您的常规pip操作。

您要做的就是setup.cfg在项目的根目录下创建一个文件,通常在主__init__.py或可执行py文件所在的位置。因此,如果您的项目的根文件夹为:/path/to/my/project/,请setup.cfg在其中创建一个文件,然后在其中放入神奇的单词:

[install]
prefix=  

好的,现在您可以为该文件夹运行pip的命令:

pip install package -t /path/to/my/project/  

该命令仅在该文件夹中正常运行。只需将其复制setup.cfg到您可能拥有的任何其他项目中即可。无需.pydistutils.cfg在主目录上写一个。

安装完模块后,可以将其卸下 setup.cfg

I believe there is a simpler solution to this problem (Homebrew’s Python on macOS) that won’t break your normal pip operations.

All you have to do is to create a setup.cfg file at the root directory of your project, usually where your main __init__.py or executable py file is. So if the root folder of your project is: /path/to/my/project/, create a setup.cfg file in there and put the magic words inside:

[install]
prefix=  

OK, now you sould be able to run pip’s commands for that folder:

pip install package -t /path/to/my/project/  

This command will run gracefully for that folder only. Just copy setup.cfg to whatever other projects you might have. No need to write a .pydistutils.cfg on your home directory.

After you are done installing the modules, you may remove setup.cfg.


回答 2

在OSX(mac)上,假定项目文件夹为/ var / myproject

  1. cd /var/myproject
  2. 创建一个名为的文件setup.cfg并添加 [install] prefix=
  3. pip install <packagename> -t .

On OSX(mac), assuming a project folder called /var/myproject

  1. cd /var/myproject
  2. Create a file called setup.cfg and add [install] prefix=
  3. Run pip install <packagename> -t .

回答 3

针对Homebrew用户的另一种解决方案*仅是使用virtualenv

当然,无论如何,这可能会消除对目标目录的需求-但是即使没有,我发现--target在虚拟环境中时默认情况下也可以工作(例如,无需创建/修改配置文件)。


*我说解决方案;也许这只是精心使用venvs的另一动机…

Another solution* for Homebrew users is simply to use a virtualenv.

Of course, that may remove the need for the target directory anyway – but even if it doesn’t, I’ve found --target works by default (as in, without creating/modifying a config file) when in a virtual environment.


*I say solution; perhaps it’s just another motivation to meticulously use venvs…


回答 4

我在周围的其他建议中遇到了错误--install-option="--prefix=lib"。我发现唯一有效的方法就是PYTHONUSERBASE此处所述使用。

export PYTHONUSERBASE=lib
pip install -I flask-restful --user

这与并不完全相同--target,但是无论如何我都会成功。

I hit errors with the other recommendations around --install-option="--prefix=lib". The only thing I found that worked is using PYTHONUSERBASE as described here.

export PYTHONUSERBASE=lib
pip install -I flask-restful --user

this is not exactly the same as --target, but it does the trick for me in any case.


回答 5

如其他提到的那样,这是与homebrew一起安装的pip和python的已知错误。

如果~/.pydistutils.cfg使用“空前缀”指令创建文件,它将解决此问题,但会破坏正常的点操作。

在正式解决此错误之前,一种选择是创建自己的bash脚本来处理这种情况:

 #!/bin/bash

 name=''
 target=''

 while getopts 'n:t:' flag; do
     case "${flag}" in
         n) name="${OPTARG}" ;;
         t) target="${OPTARG}" ;;
     esac
 done

 if [ -z "$target" ];
 then
     echo "Target parameter must be provided"
     exit 1
 fi

 if [ -z "$name" ];
 then
     echo "Name parameter must be provided"
     exit 1
 fi

 # current workaround for homebrew bug
 file=$HOME'/.pydistutils.cfg'
 touch $file

 /bin/cat <<EOM >$file
 [install]
 prefix=
 EOM
 # end of current workaround for homebrew bug

 pip install -I $name --target $target

 # current workaround for homebrew bug
 rm -rf $file
 # end of current workaround for homebrew bug

该脚本包装了您的命令,并:

  1. 接受名称和目标参数
  2. 检查这些参数是否为空
  3. 创建~/.pydistutils.cfg其中带有“空前缀”指令的文件
  4. 使用提供的参数执行您的pip命令
  5. 删除~/.pydistutils.cfg文件

可以更改此脚本并将其改编为满足您的需求,但您有所想法。而且它使您可以在不制动点的情况下运行命令。希望能帮助到你 :)

As other mentioned, this is known bug with pip & python installed with homebrew.

If you create ~/.pydistutils.cfg file with “empty prefix” instruction it will fix this problem but it will break normal pip operations.

Until this bug is officially addressed, one of the options would be to create your own bash script that would handle this case:

 #!/bin/bash

 name=''
 target=''

 while getopts 'n:t:' flag; do
     case "${flag}" in
         n) name="${OPTARG}" ;;
         t) target="${OPTARG}" ;;
     esac
 done

 if [ -z "$target" ];
 then
     echo "Target parameter must be provided"
     exit 1
 fi

 if [ -z "$name" ];
 then
     echo "Name parameter must be provided"
     exit 1
 fi

 # current workaround for homebrew bug
 file=$HOME'/.pydistutils.cfg'
 touch $file

 /bin/cat <<EOM >$file
 [install]
 prefix=
 EOM
 # end of current workaround for homebrew bug

 pip install -I $name --target $target

 # current workaround for homebrew bug
 rm -rf $file
 # end of current workaround for homebrew bug

This script wraps your command and:

  1. accepts name and target parameters
  2. checks if those parameters are empty
  3. creates ~/.pydistutils.cfg file with “empty prefix” instruction in it
  4. executes your pip command with provided parameters
  5. removes ~/.pydistutils.cfg file

This script can be changed and adapted to address your needs but you get idea. And it allows you to run your command without braking pip. Hope it helps :)


回答 6

如果您使用的是virtualenv *,最好再次检查一下which pip您使用的是哪个。

如果看到类似情况,则说明/usr/local/bin/pip您已脱离环境。重新激活您的virtualenv将解决此问题:

VirtualEnv: $ source bin/activate

虚拟鱼: $ vf activate [environ]

*:我使用virtualfish,但我认为此技巧与两者都有关。

If you’re using virtualenv*, it might be a good idea to double check which pip you’re using.

If you see something like /usr/local/bin/pip you’ve broken out of your environment. Reactivating your virtualenv will fix this:

VirtualEnv: $ source bin/activate

VirtualFish: $ vf activate [environ]

*: I use virtualfish, but I assume this tip is relevant to both.


回答 7

我有一个类似的问题。我用–system标志,以避免错误,因为我粗糙地在这里对其他线程在这里我解释一下我的情况的具体情况。我将其发布在这里,希望可以帮助面临相同问题的任何人。

I have a similar issue. I use the –system flag to avoid the error as I decribe here on other thread where I explain the specific case of my situation. I post this here expecting that can help anyone facing the same problem.


用pip安装SciPy

问题:用pip安装SciPy

使用可以通过pip安装NumPypip install numpy

SciPy是否有类似的可能性?(这样pip install scipy做无效。)


更新资料

SciPy软件包现在可以安装了pip

It is possible to install NumPy with pip using pip install numpy.

Is there a similar possibility with SciPy? (Doing pip install scipy does not work.)


Update

The package SciPy is now available to be installed with pip!


回答 0

试图easy_install指出其在Python Package Index中列出的问题,该点会进行搜索。

easy_install scipy
Searching for scipy
Reading http://pypi.python.org/simple/scipy/
Reading http://www.scipy.org
Reading http://sourceforge.net/project/showfiles.php?group_id=27747&package_id=19531
Reading http://new.scipy.org/Wiki/Download

但是,一切并没有丢失。pip可以从Subversion(SVN),GitMercurialBazaar存储库安装。SciPy使用SVN:

pip install svn+http://svn.scipy.org/svn/scipy/trunk/#egg=scipy

更新(12-2012):

pip install git+https://github.com/scipy/scipy.git

由于NumPy是依赖项,因此也应安装它。

An attempt to easy_install indicates a problem with their listing in the Python Package Index, which pip searches.

easy_install scipy
Searching for scipy
Reading http://pypi.python.org/simple/scipy/
Reading http://www.scipy.org
Reading http://sourceforge.net/project/showfiles.php?group_id=27747&package_id=19531
Reading http://new.scipy.org/Wiki/Download

All is not lost, however; pip can install from Subversion (SVN), Git, Mercurial, and Bazaar repositories. SciPy uses SVN:

pip install svn+http://svn.scipy.org/svn/scipy/trunk/#egg=scipy

Update (12-2012):

pip install git+https://github.com/scipy/scipy.git

Since NumPy is a dependency, it should be installed as well.


回答 1

先决条件:

sudo apt-get install build-essential gfortran libatlas-base-dev python-pip python-dev
sudo pip install --upgrade pip

实际包装:

sudo pip install numpy
sudo pip install scipy

可选软件包:

sudo pip install matplotlib   OR  sudo apt-get install python-matplotlib
sudo pip install -U scikit-learn
sudo pip install pandas

src

Prerequisite:

sudo apt-get install build-essential gfortran libatlas-base-dev python-pip python-dev
sudo pip install --upgrade pip

Actual packages:

sudo pip install numpy
sudo pip install scipy

Optional packages:

sudo pip install matplotlib   OR  sudo apt-get install python-matplotlib
sudo pip install -U scikit-learn
sudo pip install pandas

src


回答 2

在Ubuntu 10.04(Lucid)中,pip install scipy安装某些依赖项后,我可以成功地(在virtualenv中):

$ sudo apt-get install libamd2.2.0 libblas3gf libc6 libgcc1 libgfortran3 liblapack3gf libumfpack5.4.0 libstdc++6 build-essential gfortran libatlas-sse2-dev python-all-dev

In Ubuntu 10.04 (Lucid), I could successfully pip install scipy (within a virtualenv) after installing some of its dependencies, in particular:

$ sudo apt-get install libamd2.2.0 libblas3gf libc6 libgcc1 libgfortran3 liblapack3gf libumfpack5.4.0 libstdc++6 build-essential gfortran libatlas-sse2-dev python-all-dev

回答 3

要在Windows上安装scipy,请遵循以下说明:-

步骤1:按此链接http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy下载scipy .whl文件(例如scipy-0.17.0-cp34-none-win_amd64.whl)。

步骤2:从命令提示符(cd folder-name)转到下载文件所在的目录。

步骤3:运行以下命令:

pip install scipy-0.17.0-cp27-none-win_amd64.whl

To install scipy on windows follow these instructions:-

Step-1 : Press this link http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy to download a scipy .whl file (e.g. scipy-0.17.0-cp34-none-win_amd64.whl).

Step-2: Go to the directory where that download file is there from the command prompt (cd folder-name ).

Step-3: Run this command:

pip install scipy-0.17.0-cp27-none-win_amd64.whl

回答 4

我尝试了以上所有方法,但对我没有任何帮助。这解决了我所有的问题:

pip install -U numpy

pip install -U scipy

请注意,-U用于pip install请求升级软件包的选项。没有它,如果已经安装了软件包,pip则会通知您此信息,并且不做任何事情就退出。

I tried all the above and nothing worked for me. This solved all my problems:

pip install -U numpy

pip install -U scipy

Note that the -U option to pip install requests that the package be upgraded. Without it, if the package is already installed pip will inform you of this and exit without doing anything.


回答 5

如果我首先将BLAS,LAPACK和GCC Fortran作为系统软件包安装(我正在使用Arch Linux),则可以通过以下方式安装SciPy:

pip install scipy

If I first install BLAS, LAPACK and GCC Fortran as system packages (I’m using Arch Linux), I can get SciPy installed with:

pip install scipy

回答 6

在Fedora上,这有效:

sudo yum install -y python-pip
sudo yum install -y lapack lapack-devel blas blas-devel 
sudo yum install -y blas-static lapack-static
sudo pip install numpy
sudo pip install scipy

如果public key下载时出现任何错误,请将--nogpgcheck作为参数添加到yum,例如: yum --nogpgcheck install blas-devel

从Fedora 23开始,使用dnf代替yum

On Fedora, this works:

sudo yum install -y python-pip
sudo yum install -y lapack lapack-devel blas blas-devel 
sudo yum install -y blas-static lapack-static
sudo pip install numpy
sudo pip install scipy

If you get any public key errors while downloading, add --nogpgcheck as parameter to yum, for example: yum --nogpgcheck install blas-devel

On Fedora 23 onwards, use dnf instead of yum.


回答 7

对于Arch Linux用户:

pip install --user scipy 先决条件要安装以下Arch软件包:

  • gcc-fortran
  • blas
  • lapack

For the Arch Linux users:

pip install --user scipy prerequisites the following Arch packages to be installed:

  • gcc-fortran
  • blas
  • lapack

回答 8

适用于Ubuntu(Ubuntu 10.04 LTS(Lucid Lynx))的插件:

存储库已移动,但是

pip install -e git+http://github.com/scipy/scipy/#egg=scipy

我失败了…通过以下步骤,最终解决了问题(作为虚拟环境中的root,python3指向Python 3.2.2的链接):安装Ubuntu依赖项(请参阅elaichi),克隆NumPy和SciPy:

git clone git://github.com/scipy/scipy.git scipy

git clone git://github.com/numpy/numpy.git numpy

生成NumPy(在numpy文件夹中):

python3 setup.py build --fcompiler=gnu95

安装SciPy(在scipy文件夹中):

python3 setup.py install

Addon for Ubuntu (Ubuntu 10.04 LTS (Lucid Lynx)):

The repository moved, but a

pip install -e git+http://github.com/scipy/scipy/#egg=scipy

failed for me… With the following steps, it finally worked out (as root in a virtual environment, where python3 is a link to Python 3.2.2): install the Ubuntu dependencies (see elaichi), clone NumPy and SciPy:

git clone git://github.com/scipy/scipy.git scipy

git clone git://github.com/numpy/numpy.git numpy

Build NumPy (within the numpy folder):

python3 setup.py build --fcompiler=gnu95

Install SciPy (within the scipy folder):

python3 setup.py install

回答 9

就我而言,直到我还安装了以下软件包,该软件包才起作用:libatlas-base-dev,gfortran

 sudo apt-get install libatlas-base-dev gfortran

然后运行pip install scipy

In my case, it wasn’t working until I also installed the following package : libatlas-base-dev, gfortran

 sudo apt-get install libatlas-base-dev gfortran

Then run pip install scipy


回答 10

  1. 安装python-3.4.4
  2. scipy-0.15.1-win32-superpack-python3.4
  3. 应用以下推荐文档
py -m pip install --upgrade pip
py -m pip install numpy
py -m pip install matplotlib
py -m pip install scipy
py -m pip install scikit-learn
  1. install python-3.4.4
  2. scipy-0.15.1-win32-superpack-python3.4
  3. apply the following commend doc
py -m pip install --upgrade pip
py -m pip install numpy
py -m pip install matplotlib
py -m pip install scipy
py -m pip install scikit-learn

回答 11

答案是肯定的。

首先,您可以轻松安装numpy use命令:

pip install numpy

然后,您应该安装Scipy所需的mkl,然后可以在此处下载

下载file_name.whl后,您进行安装

C:\Users\****\Desktop\a> pip install mkl_service-1.1.2-cp35-cp35m-win32.whl
Processing c:\users\****\desktop\a\mkl_service-1.1.2-cp35-cp35m-win32.whl 
Installing collected packages: mkl-service    
Successfully installed mkl-service-1.1.2

然后,您可以在同一网站上下载scipy-0.18.1-cp35-cp35m-win32.whl

注意:您应该根据您的python版本下载file_name.whl,如果您的python版本是32bit python3.5,则应该下载该文件,而“ win32”是您的python版本,而不是操作系统版本。

然后像这样安装file_name.whl:

C:\Users\****\Desktop\a>pip install scipy-0.18.1-cp35-cp35m-win32.whl
Processing c:\users\****\desktop\a\scipy-0.18.1-cp35-cp35m-win32.whl
Installing collected packages: scipy
Successfully installed scipy-0.18.1

然后,只有一件事要做:注释掉特定的一行,否则当您输入命令“ import scipy”时会出现错误消息。

所以注释掉这行

from numpy._distributor_init import NUMPY_MKL  # requires numpy+mkl

在此文件中:your_own_path \ lib \ site-packages \ scipy__init __。py

然后您可以使用SciPy :)

这里告诉您更多有关最后一步的信息。

是一个类似问题的答案。

The answer is yes, there is.

First you can easily install numpy use commands:

pip install numpy

Then you should install mkl, which is required by Scipy, and you can download it here

After download the file_name.whl you install it

C:\Users\****\Desktop\a> pip install mkl_service-1.1.2-cp35-cp35m-win32.whl
Processing c:\users\****\desktop\a\mkl_service-1.1.2-cp35-cp35m-win32.whl 
Installing collected packages: mkl-service    
Successfully installed mkl-service-1.1.2

Then at the same website you can download scipy-0.18.1-cp35-cp35m-win32.whl

Note:You should download the file_name.whl according to you python version, if you python version is 32bit python3.5 you should download this one, and the “win32” is about your python version, not your operating system version.

Then install file_name.whl like this:

C:\Users\****\Desktop\a>pip install scipy-0.18.1-cp35-cp35m-win32.whl
Processing c:\users\****\desktop\a\scipy-0.18.1-cp35-cp35m-win32.whl
Installing collected packages: scipy
Successfully installed scipy-0.18.1

Then there is only one more thing to do: comment out a specfic line or there will be error messages when you imput command “import scipy”.

So comment out this line

from numpy._distributor_init import NUMPY_MKL  # requires numpy+mkl

in this file: your_own_path\lib\site-packages\scipy__init__.py

Then you can use SciPy :)

Here tells you more about the last step.

Here is a similar anwser to a similar question.


回答 12

除了所有这些答案之外,如果在64位计算机上安装32位python,则无论您的计算机如何,都必须下载32位scipy。 http://www.lfd.uci.edu/~gohlke/pythonlibs/ 在上述URL中,您可以下载软件包,命令为:pip install

Besides all of these answers, If you install python of 32bit on your 64bit machine, you have to download scipy of 32-bit irrespective of your machine. http://www.lfd.uci.edu/~gohlke/pythonlibs/ In the above URL you can download the packages and command is: pip install


回答 13

对于gentoo,它位于主存储库中: emerge --ask scipy

For gentoo, it’s in the main repository: emerge --ask scipy


回答 14

您也可以在Windows中使用python 3.6使用它 python -m pip install scipy

You can also use this in windows with python 3.6 python -m pip install scipy


安装pycurl时出现“无法运行curl-config:[Errno 2]没有这样的文件或目录”

问题:安装pycurl时出现“无法运行curl-config:[Errno 2]没有这样的文件或目录”

我正在尝试通过以下方式安装pycurl:

sudo pip install pycurl

它下载得很好,但是当它运行setup.py时,我得到以下回溯:

Downloading/unpacking pycurl
  Running setup.py egg_info for package pycurl
    Traceback (most recent call last):
      File "<string>", line 16, in <module>
      File "/tmp/pip-build-root/pycurl/setup.py", line 563, in <module>
        ext = get_extension()
      File "/tmp/pip-build-root/pycurl/setup.py", line 368, in get_extension
        ext_config = ExtensionConfiguration()
      File "/tmp/pip-build-root/pycurl/setup.py", line 65, in __init__
        self.configure()
      File "/tmp/pip-build-root/pycurl/setup.py", line 100, in configure_unix
        raise ConfigurationError(msg)
    __main__.ConfigurationError: Could not run curl-config: [Errno 2] No such file or directory
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):

  File "<string>", line 16, in <module>

  File "/tmp/pip-build-root/pycurl/setup.py", line 563, in <module>

    ext = get_extension()

  File "/tmp/pip-build-root/pycurl/setup.py", line 368, in get_extension

    ext_config = ExtensionConfiguration()

  File "/tmp/pip-build-root/pycurl/setup.py", line 65, in __init__

    self.configure()

  File "/tmp/pip-build-root/pycurl/setup.py", line 100, in configure_unix

    raise ConfigurationError(msg)

__main__.ConfigurationError: Could not run curl-config: [Errno 2] No such file or directory

任何想法为什么会这样以及如何解决它

I’m trying to install pycurl via:

sudo pip install pycurl

It downloaded fine, but when when it runs setup.py I get the following traceback:

Downloading/unpacking pycurl
  Running setup.py egg_info for package pycurl
    Traceback (most recent call last):
      File "<string>", line 16, in <module>
      File "/tmp/pip-build-root/pycurl/setup.py", line 563, in <module>
        ext = get_extension()
      File "/tmp/pip-build-root/pycurl/setup.py", line 368, in get_extension
        ext_config = ExtensionConfiguration()
      File "/tmp/pip-build-root/pycurl/setup.py", line 65, in __init__
        self.configure()
      File "/tmp/pip-build-root/pycurl/setup.py", line 100, in configure_unix
        raise ConfigurationError(msg)
    __main__.ConfigurationError: Could not run curl-config: [Errno 2] No such file or directory
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):

  File "<string>", line 16, in <module>

  File "/tmp/pip-build-root/pycurl/setup.py", line 563, in <module>

    ext = get_extension()

  File "/tmp/pip-build-root/pycurl/setup.py", line 368, in get_extension

    ext_config = ExtensionConfiguration()

  File "/tmp/pip-build-root/pycurl/setup.py", line 65, in __init__

    self.configure()

  File "/tmp/pip-build-root/pycurl/setup.py", line 100, in configure_unix

    raise ConfigurationError(msg)

__main__.ConfigurationError: Could not run curl-config: [Errno 2] No such file or directory

Any idea why this is happening and how to get around it


回答 0

在Debian上,我需要以下软件包来解决此问题

sudo apt install libcurl4-openssl-dev libssl-dev

On Debian I needed the following packages to fix this

sudo apt install libcurl4-openssl-dev libssl-dev

回答 1

yum包管理器类似

yum install libcurl-devel

如果您使用dnf,请使用

dnf install libcurl-devel

Similarly with yum package manager

yum install libcurl-devel

If you use dnf, use

dnf install libcurl-devel

回答 2

就我而言,这解决了问题:

sudo apt-get install libssl-dev libcurl4-openssl-dev python-dev

这里解释

in my case this fixed the problem:

sudo apt-get install libssl-dev libcurl4-openssl-dev python-dev

as explained here


回答 3

在Alpine linux中,您应该执行以下操作:

apk add curl-dev python3-dev libressl-dev

In Alpine linux you should do:

apk add curl-dev python3-dev libressl-dev

回答 4

我在尝试使Shinken 2.0.3在Ubuntu上启动时遇到了相同的问题。最终,我进行了完全卸载,然后使用重新安装了Shinken pip -v。在清理过程中,它提到:

Warning: missing python-pycurl lib, you MUST install it before launch the shinken daemons

安装了apt-get,所有经纪人都按预期启动了:-)

I encountered the same problem whilst trying to get Shinken 2.0.3 to fire up on Ubuntu. Eventually I did a full uninstall then reinstalled Shinken with pip -v. As it cleaned up, it mentioned:

Warning: missing python-pycurl lib, you MUST install it before launch the shinken daemons

Installed that with apt-get, and all the brokers fired up as expected :-)


回答 5

那解决了我在Ubuntu 14.04上的问题:

apt-get安装libcurl4-gnutls-dev

That solved my problem on Ubuntu 14.04:

apt-get install libcurl4-gnutls-dev


回答 6

在OpenSUSE上:

zypper in libcurl-devel 

On OpenSUSE:

zypper in libcurl-devel 

回答 7

就我而言,我一直收到相同的错误消息。我使用软呢帽。我通过以下方法解决了它:

sudo dnf install pycurl

这安装了我需要它运行的一切。

In my case i kept getting the same error message. I use fedora. I solved it by doing:

sudo dnf install pycurl

This installed eveything that I needed for it to work.


回答 8

我在Mac上遇到了这个问题,这与该openssl软件包是所需的旧版本有关pycurlpycurl根据我的理解,可以使用其他SSL库而不是openssl。验证您所使用的SSL库并进行更新,因为它很可能解决了该问题。

我通过以下方式解决了这个问题:

  • 跑步 brew upgrade
  • pycurl-x.y.z.tar.gzhttp://pycurl.io/下载了最新的
  • 提取上面的包并在其中更改目录
  • python setup.py --with-openssl install如OpenSSL是我已经安装了库。如果你是SSL库或者是gnutls还是nss那么将不得不使用--with-gnutls--with-nss相应。您将可以在其github存储库中找到更多安装信息

I had this issue on Mac and it was related to the openssl package being an older version of what it was required by pycurl. pycurl can use other ssl libraries rather than openssl as per my understanding of it. Verify which ssl library you’re using and update as it is very likely to fix the issue.

I fixed this by:

  • running brew upgrade
  • downloaded the latest pycurl-x.y.z.tar.gz from http://pycurl.io/
  • extracted the package above and change directory into it
  • ran python setup.py --with-openssl install as openssl is the library I have installed. If you’re ssl library is either gnutls or nss then will have to use --with-gnutls or --with-nss accordingly. You’ll be able to find more installation info in their github repository.

回答 9

除了eldos的答案外,我gcc在CentOS 7中还需要:

yum install libcurl-devel gcc

In addition to the answer of eldos I also needed gcc in CentOS 7:

yum install libcurl-devel gcc

回答 10

请注意,如果您使用的是nodejs,则在编写本文时,它会依赖libssl 1.0。*-因此,安装备用SSL库将破坏您的nodejs安装。

安装不同SSL库的另一种解决方案是此答案中的此处发布:https : //stackoverflow.com/a/59927568/13564342来代替安装libcurl4-gnutls-dev

sudo apt install libcurl4-gnutls-dev

Be advised that if you’re using nodejs there’s (at the time of writing) a dependency on libssl 1.0.* – so installing an alternative SSL library will break your nodejs installation.

An alternative solution to installing a different SSL library is that posted in this answer here: https://stackoverflow.com/a/59927568/13564342 to instead install libcurl4-gnutls-dev

sudo apt install libcurl4-gnutls-dev

为什么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

如何在OS X上将Python的默认版本设置为3.x?

问题:如何在OS X上将Python的默认版本设置为3.x?

我正在运行Mountain Lion,而基本的默认Python版本是2.7。我下载了Python 3.3,并希望将其设置为默认值。

目前:

$ python
    version 2.7.5
$ python3.3
    version 3.3

如何设置它,以便每次运行$ python时都能打开3.3?

I’m running Mountain Lion and the basic default Python version is 2.7. I downloaded Python 3.3 and want to set it as default.

Currently:

$ python
    version 2.7.5
$ python3.3
    version 3.3

How do I set it so that every time I run $ python it opens 3.3?


回答 0

在系统范围内更改默认python可执行文件的版本可能会破坏某些依赖python2的应用程序。

但是,您可以在大多数外壳程序中为命令加上别名,因为macOS中的默认外壳程序(10.14及以下版本中的bash; 10.15中的zsh)具有相似的语法。您可以在您的中放置别名python =’python3′ ~/.profile,然后~/.profile在您~/.bash_profile和/或您的源代码中~/.zsh_profile输入以下内容:

[ -e ~/.profile ] && . ~/.profile

这样,您的别名将可在所有shell中使用。

这样,python命令现在将被调用python3。如果您想偶尔调用“原始” python(指python2),则可以使用command python,这将使别名保持不变,并且适用于所有shell。

如果您更频繁地启动解释器(我愿意),则总是可以创建更多别名来添加,即:

alias 2='python2'
alias 3='python3'

提示:对于脚本,而不是使用shebang之类的方法:

#!/usr/bin/env python

采用:

#!/usr/bin/env python3

这样,系统将使用python3运行python 可执行文件

Changing the default python executable’s version system-wide could break some applications that depend on python2.

However, you can alias the commands in most shells, Since the default shells in macOS (bash in 10.14 and below; zsh in 10.15) share a similar syntax. You could put alias python=’python3′ in your ~/.profile, and then source ~/.profile in your ~/.bash_profile and/or your~/.zsh_profile with a line like:

[ -e ~/.profile ] && . ~/.profile

This way, your alias will work across shells.

With this, python command now invokes python3. If you want to invoke the “original” python (that refers to python2) on occasion, you can use command python, which will leaving the alias untouched, and works in all shells.

If you launch interpreters more often (I do), you can always create more aliases to add as well, i.e.:

alias 2='python2'
alias 3='python3'

Tip: For scripts, instead of using a shebang like:

#!/usr/bin/env python

use:

#!/usr/bin/env python3

This way, the system will use python3 for running python executables.


回答 1

您可以通过符号链接来解决。

unlink /usr/local/bin/python
ln -s /usr/local/bin/python3.3 /usr/local/bin/python

You can solve it by symbolic link.

unlink /usr/local/bin/python
ln -s /usr/local/bin/python3.3 /usr/local/bin/python

回答 2

打开〜/ .bash_profile文件。

vi ~/.bash_profile

然后按如下所示放置别名:

alias python='python3'

现在保存文件,然后运行〜/ .bash_profile文件。

source ~/.bash_profile

恭喜!!!现在,您可以通过键入python使用python3 。

python --version

的Python 3.7.3

Open ~/.bash_profile file.

vi ~/.bash_profile

Then put the alias as follows:

alias python='python3'

Now save the file and then run the ~/.bash_profile file.

source ~/.bash_profile

Congratulation !!! Now, you can use python3 by typing python.

python --version

Python 3.7.3


回答 3

转到终端类型:

alias python=python3.x

这会将默认python设置为python3.x

Go to terminal type:

alias python=python3.x

This will setup default python as python3.x


回答 4

以下为我工作

cd /usr/local/bin
mv python python.old
ln -s python3 python

The following worked for me

cd /usr/local/bin
mv python python.old
ln -s python3 python

回答 5

我在这个游戏上有点晚了,但是我认为我应该发布更新的答案,因为我自己才遇到这个问题。请注意,这仅适用于基于Mac的设置(我没有在Windows或任何版本的Linux上尝试过)。

最简单的方法是通过Brew安装Python 。如果您未安装brew,则需要先执行该操作。安装完成后,在终端上执行以下操作:

brew install python

这将安装Python3。安装后,运行以下命令:

ls -l /usr/local/bin/python*

您将看到brew创建的所有安装到其Python安装的链接。它看起来像这样:

lrwxr-xr-x  1 username  admin  36 Oct  1 13:35 /usr/local/bin/python3@ -> ../Cellar/python/3.7.4_1/bin/python3
lrwxr-xr-x  1 username  admin  43 Oct  1 13:35 /usr/local/bin/python3-config@ -> ../Cellar/python/3.7.4_1/bin/python3-config
lrwxr-xr-x  1 username  admin  38 Oct  1 13:35 /usr/local/bin/python3.7@ -> ../Cellar/python/3.7.4_1/bin/python3.7
lrwxr-xr-x  1 username  admin  45 Oct  1 13:35 /usr/local/bin/python3.7-config@ -> ../Cellar/python/3.7.4_1/bin/python3.7-config
lrwxr-xr-x  1 username  admin  39 Oct  1 13:35 /usr/local/bin/python3.7m@ -> ../Cellar/python/3.7.4_1/bin/python3.7m
lrwxr-xr-x  1 username  admin  46 Oct  1 13:35 /usr/local/bin/python3.7m-config@ -> ../Cellar/python/3.7.4_1/bin/python3.7m-config

此示例的第一行显示了python3符号链接。要将其设置为默认python符号链接,请运行以下命令:

ln -s -f /usr/local/bin/python3 /usr/local/bin/python

设置后,您可以执行以下操作:

which python

它应该显示:

/usr/local/bin/python

您将必须重新加载当前的终端shell,才能在该shell中使用新的符号链接,但是,所有新打开的shell会话将(应该)自动使用它。要对此进行测试,请打开一个新的终端外壳并运行以下命令:

python --version

I’m a little late to the game on this one, but I thought I should post an updated answer since I just encountered this issue for myself. Please note that this will only apply to a Mac-based setup (I haven’t tried it with Windows or any flavor of Linux).

The simplest way to get this working is to install Python via Brew. If you don’t have brew installed, you will need to do that first. Once installed, do the following in at the terminal:

brew install python

This will install Python 3. After it’s installed, run this:

ls -l /usr/local/bin/python*

You will see all of the links created by brew to its Python install. It will look something like this:

lrwxr-xr-x  1 username  admin  36 Oct  1 13:35 /usr/local/bin/python3@ -> ../Cellar/python/3.7.4_1/bin/python3
lrwxr-xr-x  1 username  admin  43 Oct  1 13:35 /usr/local/bin/python3-config@ -> ../Cellar/python/3.7.4_1/bin/python3-config
lrwxr-xr-x  1 username  admin  38 Oct  1 13:35 /usr/local/bin/python3.7@ -> ../Cellar/python/3.7.4_1/bin/python3.7
lrwxr-xr-x  1 username  admin  45 Oct  1 13:35 /usr/local/bin/python3.7-config@ -> ../Cellar/python/3.7.4_1/bin/python3.7-config
lrwxr-xr-x  1 username  admin  39 Oct  1 13:35 /usr/local/bin/python3.7m@ -> ../Cellar/python/3.7.4_1/bin/python3.7m
lrwxr-xr-x  1 username  admin  46 Oct  1 13:35 /usr/local/bin/python3.7m-config@ -> ../Cellar/python/3.7.4_1/bin/python3.7m-config

The first row in this example shows the python3 symlink. To set it as the default python symlink run the following:

ln -s -f /usr/local/bin/python3 /usr/local/bin/python

Once set, you can do:

which python

and it should show:

/usr/local/bin/python

You will have to reload your current terminal shell for it to use the new symlink in that shell, however, all newly opened shell sessions will (should) automatically use it. To test this, open a new terminal shell and run the following:

python --version

回答 6

转到“应用程序”,进入“ Python”文件夹,应该有一个名为“ Update Shell Profile.command”或类似名称的bash脚本。运行该脚本,它应该这样做。

更新:看来您不应该更新它:如何更改默认python版本?

Go to ‘Applications’, enter ‘Python’ folder, there should be a bash script called ‘Update Shell Profile.command’ or similar. Run that script and it should do it.

Update: It looks like you should not update it: how to change default python version?


回答 7

这对我有用。我添加了别名并重新启动了终端

alias python=/usr/local/bin/python3

This worked for me. I added alias and restarted my terminal:

alias python=/usr/local/bin/python3

回答 8

我相信大多数登陆这里的人都在使用ZSH thorugh iterm或其他工具,这为您带来了答案

您必须改为添加/修改命令~/.zshrc

I believe most of people landed here are using ZSH thorugh iterm or whatever, and that brings you to this answer.

You have to add/modify your commands in ~/.zshrc instead.


回答 9

我不确定在OS X上是否可用,但是在Linux上我会使用该module命令。 看这里

正确设置modulefile,然后将以下内容添加到rc文件中(例如〜/ .bashrc):

module load python3.3

这样一来,登录时即可根据需要切换路径,而不会影响任何系统默认值。

I’m not sure if this is available on OS X, but on linux I would make use of the module command. See here.

Set up the modulefile correctly, then add something like this to your rc file (e.g. ~/.bashrc):

module load python3.3

This will make it so that your paths get switched around as required when you log in without impacting any system defaults.


回答 10

我认为安装python时会将导出路径语句放入〜/ .bash_profile文件中。因此,如果您不再打算使用Python 2,则可以从那里删除该语句。如上所述的别名也是一种很好的方法。

这是从〜/ .bash_profile中删除引用的方法-vim ./.bash_profile-删除引用(也类似:export PATH =“ / Users / bla / anaconda:$ PATH”)-保存并退出-源./ .bash_profile保存更改

I think when you install python it puts export path statements into your ~/.bash_profile file. So if you do not intend to use Python 2 anymore you can just remove that statement from there. Alias as stated above is also a great way to do it.

Here is how to remove the reference from ~/.bash_profile – vim ./.bash_profile – remove the reference (AKA something like: export PATH=”/Users/bla/anaconda:$PATH”) – save and exit – source ./.bash_profile to save the changes


回答 11

$ sudo ln -s -f $(which python3) $(which python)

完成。

$ sudo ln -s -f $(which python3) $(which python)

done.


回答 12

在Mac上将Python 3设置为默认的正确和错误的方法

在本文中,作者讨论了设置默认python的三种方法:

  1. 什么不该做。
  2. 我们可以做(但也不应该)。
  3. 我们应该做什么!

所有这些方式都有效。您决定哪个更好。

The RIGHT and WRONG way to set Python 3 as default on a Mac

In this article author discuss three ways of setting default python:

  1. What NOT to do.
  2. What we COULD do (but also shouldn’t).
  3. What we SHOULD do!

All these ways are working. You decide which is better.


回答 13

如果virtualenvwrapper使用which virtualenvwrapper.sh,则可以使用进行定位,然后使用vim或任何其他编辑器将其打开,然后更改以下内容

# Locate the global Python where virtualenvwrapper is installed.
if [ "${VIRTUALENVWRAPPER_PYTHON:-}" = "" ]
then
    VIRTUALENVWRAPPER_PYTHON="$(command \which python)"
fi

将行更改VIRTUALENVWRAPPER_PYTHON="$(command \which python)"VIRTUALENVWRAPPER_PYTHON="$(command \which python3)"

If you are using a virtualenvwrapper, you can just locate it using which virtualenvwrapper.sh, then open it using vim or any other editor then change the following

# Locate the global Python where virtualenvwrapper is installed.
if [ "${VIRTUALENVWRAPPER_PYTHON:-}" = "" ]
then
    VIRTUALENVWRAPPER_PYTHON="$(command \which python)"
fi

Change the line VIRTUALENVWRAPPER_PYTHON="$(command \which python)" to VIRTUALENVWRAPPER_PYTHON="$(command \which python3)".


回答 14

对我来说,解决方案是使用PyCharm并将默认的python版本设置为我需要使用的版本。

安装PyCharm并转到文件==>新项目的首选项,然后为项目选择所需的解释器,在这种情况下为python 3.3

For me the solution was using PyCharm and setting the default python version to the the one that i need to work with.

install PyCharm and go to file ==> preferences for new project, then choose the interpreter you want for your projects, in this case python 3.3


回答 15

如果您使用macports,则不需要使用别名或环境变量,只需使用macports已经提供的方法,此问答将对此进行说明:

作法:Macports选择python

TL; DR:

sudo port select --set python python27

If you use macports, you do not need to play with aliases or environment variables, just use the the method macports already offers, explained by this Q&A:

How to: Macports select python

TL;DR:

sudo port select --set python python27

回答 16

如果您使用的是Macports,则有一种更简单的方法:

跑:

port install python37

安装后,设置默认值:

sudo port select --set python python37

sudo port select --set python3 python37

重新启动您的cmd窗口,完成。

If you are using macports, that has a easier way to do:

run:

port install python37

after install, set default:

sudo port select --set python python37

sudo port select --set python3 python37

restart your cmd window, finished.


回答 17

好吧…有点老了。但是仍然值得一个好的答案。

优点之一是您不想触摸Mac上的默认Python。

通过Homebrew或其他方式安装所需的任何Python版本,然后在virtualenv中使用它。Virtualenv通常被认为是胡扯,但还是比在系统范围内更改python版本(macOS可能会保护自己免受此类操作)或用户范围,bash范围……好得多。只需忘记默认的Python。使用venv这样的游乐场是您的操作系统最感谢的事情。

例如,这种情况是,许多现代Linux发行版都摆脱了现成安装的Python2的安装,仅在系统中保留了Python3。但是每次您尝试使用python2作为依赖项安装旧版本时…希望您理解我的意思。一个好的开发者不在乎。好的开发人员可以使用他们想要的python版本创建干净的游乐场。

Well… It’s kinda old. But still deserves a good answer.

And the good one is You Don’t Wanna Touch The Default Python On Mac.

Install any Python version you need via Homebrew or whatever and use it in virtualenv. Virtualenv is often considered to be something crap-like, but it’s still way, wayyyy better than changing python version system-wide (macOS is likely to protect itself from such actions) or user-wide, bash-wide… whatever. Just forget about the default Python. Using playgrounds like venv is what your OS will be most, very most grateful for.

The case is, for example, many modern Linux distributions get rid of Python2 installed out-of-the-box, leaving only Python3 in the system. But everytime you try to install something old with python2 as a dependency… hope you understand what I mean. A good developer doesn’t care. Good developers create clean playgrounds with python version they desire.


回答 18

Mac用户只需要在终端上运行以下代码

brew switch python 3.x.x

3.xx应该是新的python版本。

这将更新所有系统链接。

Mac users just need to run the following code on terminal

brew switch python 3.x.x

3.x.x should be the new python version.

This will update all the system links.


回答 19

建议将python别名为python3会导致设置python版本的虚拟环境出现问题(例如:pyenv)。使用pyenv,您可以像下面这样全局设置版本:

pyenv global 3.8.2

然后在任何特定项目中,您都可以创建一个.python-version文件,其中包含python版本:

pyenv local 2.7.1

我认为这是在系统上管理多个版本的python的最佳方法。

Suggestions to alias python to python3 will cause problems with virtual environments that set the version of python (eg: pyenv). With pyenv, you can set the version globally like so:

pyenv global 3.8.2

and then in any specific project, you can create a .python-version file which has the python version inside of it:

pyenv local 2.7.1

This is the best way to manage multiple versions of python on a system in my opinion.


“ pip install unroll”:“ python setup.py egg_info”失败,错误代码为1

问题:“ pip install unroll”:“ python setup.py egg_info”失败,错误代码为1

我是Python的新手,并一直在尝试使用安装某些软件包pip

但是pip install unroll给我

命令“ python setup.py egg_info”在C:\ Users \ MARKAN〜1 \ AppData \ Local \ Temp \ pip-build-wa7uco0k \ unroll \中失败,错误代码为1

我该如何解决?

I’m new to Python and have been trying to install some packages with pip.

But pip install unroll gives me

Command “python setup.py egg_info” failed with error code 1 in C:\Users\MARKAN~1\AppData\Local\Temp\pip-build-wa7uco0k\unroll\

How can I solve this?


回答 0

关于错误代码

根据Python文档

该模块提供了可用的标准errno系统符号。每个符号的值是相应的整数值。名称和描述是从linux / include / errno.h借来的,应该十分全面。

错误代码1在errno.h和中定义Operation not permitted

关于您的错误

您的setuptools似乎未安装。只需遵循Installation InstructionsPyPI网站上的即可。

如果已经安装,请尝试

pip install --upgrade setuptools

如果已经更新,请检查模块ez_setup是否缺失。如果是的话

pip install ez_setup

然后再试一次

pip install unroll

如果仍然无法正常运行,则可能是pip没有正确安装/升级setup_tools,因此您可能需要尝试

easy_install -U setuptools

然后再次

pip install unroll

About the error code

According to the Python documentation:

This module makes available standard errno system symbols. The value of each symbol is the corresponding integer value. The names and descriptions are borrowed from linux/include/errno.h, which should be pretty all-inclusive.

Error code 1 is defined in errno.h and means Operation not permitted.

About your error

Your setuptools do not appear to be installed. Just follow the Installation Instructions from the PyPI website.

If it’s already installed, try

pip install --upgrade setuptools

If it’s already up to date, check that the module ez_setup is not missing. If it is, then

pip install ez_setup

Then try again

pip install unroll

If it’s still not working, maybe pip didn’t install/upgrade setup_tools properly so you might want to try

easy_install -U setuptools

And again

pip install unroll

回答 1

这是一些指南,解释了我通常如何在Python + Windows上安装新软件包。看来您使用的是Windows路径,因此此答案将遵循特定的SO:

  • 我从不使用系统范围的Python安装。我只使用virtualenvs,通常我会尝试使用最新版本的2.x和3.x。
  • 我的第一次尝试总是pip install package_i_want在某些Visual Studio命令提示符下进行。什么Visual Studio命令提示符?好吧,理想情况下是与用来构建Python的Visual Studio相匹配的Visual Studio。例如,假设您的Python安装提示Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:40:30) [MSC v.1500 64 bit (AMD64)] on win32。可以在此处找到用于编译Python的Visual Studio版本,因此v1500表示我将使用vs2008 x64命令提示符
  • 如果上一步由于某种原因而失败,我只是尝试使用 easy_install package_i_want
  • 如果上一步由于某种原因失败,我将转到gohlke网站,并检查我的包裹是否在那儿。如果是这样,我很幸运,我将其下载到virtualenv中,然后使用命令提示符转到该位置,然后执行pip install package_i_want.whl
  • 如果上一步没有成功,我将尝试自己制作轮子,一旦生成,我将尝试使用 pip install package_i_want.whl

现在,如果我们专注于您的特定问题,那么您将很难安装展开软件包。似乎最快的安装方式是执行以下操作:

  • git clone https://github.com/Zulko/unroll
  • cd unroll && python setup.py bdist_wheel
  • 将创建的dist文件夹中生成的unroll-0.1.0-py2-none-any.whl文件复制到virtualenv中。
  • pip install unroll-0.1.0-py2-none-any.whl

这样,它将安装没有任何问题。要检查它是否确实有效,只需登录Python安装并尝试import unroll,不要抱怨。

最后一点:这种方法几乎在99%的时间内都有效,有时您会发现一些特定于Unix或Mac OS X的pip程序包,在这种情况下,恐怕最好的方法是Windows版本正在向主要开发人员发布一些问题,或者您可以通过自己移植到Windows来获得一些乐趣(如果不走运,通常需要几个小时):)

Here’s a little guide explaining a little bit how I usually install new packages on Python + Windows. It seems you’re using Windows paths, so this answer will stick to that particular SO:

  • I never use a system-wide Python installation. I only use virtualenvs, and usually I try to have the latest version of 2.x & 3.x.
  • My first attempt is always doing pip install package_i_want in some of my Visual Studio command prompts. What Visual Studio command prompt? Well, ideally the Visual Studio which matches the one which was used to build Python. For instance, let’s say your Python installation says Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:40:30) [MSC v.1500 64 bit (AMD64)] on win32. The version of Visual Studio used to compile Python can be found here, so v1500 means I’d be using vs2008 x64 command prompt
  • If the previous step failed for some reason I just try using easy_install package_i_want
  • If the previous step failed for some reason I go to gohlke website and I check whether my package is available over there. If it’s so, I’m lucky, I just download it into my virtualenv and then I just go to that location using a command prompt and I do pip install package_i_want.whl
  • If the previous step didn’t succeed I’ll just try to build the wheel myself and once it’s generated I’ll try to install it with pip install package_i_want.whl

Now, if we focus in your specific problem, where you’re having a hard time installing the unroll package. It seems the fastest way to install it is doing something like this:

  • git clone https://github.com/Zulko/unroll
  • cd unroll && python setup.py bdist_wheel
  • Copy the generated unroll-0.1.0-py2-none-any.whl file from the created dist folder into your virtualenv.
  • pip install unroll-0.1.0-py2-none-any.whl

That way it will install without any problems. To check it really works, just login into the Python installation and try import unroll, it shouldn’t complain.

One last note: This method works almost 99% of the time, and sometimes you’ll find some pip packages which are specific to Unix or Mac OS X, in that case, when that happens I’m afraid the best way to get a Windows version is either posting some issues to the main developers or having some fun by yourself porting to Windows (typically a few hours if you’re not lucky) :)


回答 2

升级点数后已解决:

python -m pip install --upgrade pip
pip install "package-name"

It was resolved after upgrading pip:

python -m pip install --upgrade pip
pip install "package-name"

回答 3

我完全陷入了与相同的错误psycopg2。看来我在安装Python和相关软件包时跳过了几个步骤。

  1. sudo apt-get install python-dev libpq-dev
  2. 转到您的虚拟环境
  3. pip install psycopg2

(在您的情况下,您需要替换psycopg2遇到问题的软件包。)

它无缝地工作。

I got stuck exactly with the same error with psycopg2. It looks like I skipped a few steps while installing Python and related packages.

  1. sudo apt-get install python-dev libpq-dev
  2. Go to your virtual env
  3. pip install psycopg2

(In your case you need to replace psycopg2 with the package you have an issue with.)

It worked seamlessly.


回答 4

在安装我得到同样的错误mitmproxy使用pip3。下面的命令解决了这个问题:

pip3 install --upgrade setuptools

I got this same error while installing mitmproxy using pip3. The below command fixed this:

pip3 install --upgrade setuptools

回答 5

  • Microsoft Visual C++ Compiler for Python 2.7https://www.microsoft.com/zh-cn/download/details.aspx?id=44266下载并安装-此程序包包含为Python 2.7程序包生成二进制文件所需的编译器和系统标头集。
  • 在提升模式下打开命令提示符(以管理员身份运行)
  • 首先要做 pip install ez_setup
  • 然后做pip install unroll(它将开始安装numpy, music21, decorator, imageio, tqdm, moviepy, unroll)#请耐心等待music21安装

使用python 2.7.11 64位

  • Download and install the Microsoft Visual C++ Compiler for Python 2.7 from https://www.microsoft.com/en-in/download/details.aspx?id=44266 – this package contains the compiler and set of system headers necessary for producing binary wheels for Python 2.7 packages.
  • Open a command prompt in elevated mode (run as administrator)
  • Firstly do pip install ez_setup
  • Then do pip install unroll (It will start installing numpy, music21, decorator, imageio, tqdm, moviepy, unroll) # Please be patient for music21 installation

Python 2.7.11 64 bit used


回答 6

另一种方式:

sudo apt-get install python-psycopg2 python-mysqldb

Other way:

sudo apt-get install python-psycopg2 python-mysqldb

回答 7

我有同样的问题。

问题是

pyparsing 2.2已经安装好了,我requirements.txt正在尝试安装pyparsing 2.0.1,抛出此错误

上下文:我使用的是virtualenv,似乎2.2来自我的全局操作系统Python site-packages,但是即使带有--no-site-packages标志(默认为上一个virtualenv中的默认标志),2.2仍然存在。肯定是因为我从他们的网站安装了Python,并将Python库添加到了我的$PATH

也许一个pip install --ignore-installed会工作。

解决方案:因为我需要向前移动,我只是删除了pyparsing==2.0.1从我的requirements.txt

I had the same problem.

The problem was:

pyparsing 2.2 was already installed and my requirements.txt was trying to install pyparsing 2.0.1 which throw this error

Context: I was using virtualenv, and it seems the 2.2 came from my global OS Python site-packages, but even with --no-site-packages flag (now by default in last virtualenv) the 2.2 was still present. Surely because I installed Python from their website and it added Python libraries to my $PATH.

Maybe a pip install --ignore-installed would have worked.

Solution: as I needed to move forwards, I just removed the pyparsing==2.0.1 from my requirements.txt.


回答 8

尝试使用pip安装Python模块时遇到了相同的错误代码。@Hackndo指出文档指出了安全问题。

基于该答案,我的问题通过运行带有sudo前缀的pip install命令得以解决:

sudo pip install python-mpd2

I ran into the same error code when trying to install a Python module with pip. @Hackndo noted that the documentation indicate a security issue.

Based on that answer, my problem was solved by running the pip install command with sudo prefixed:

sudo pip install python-mpd2

回答 9

在安装“ Twisted”库时遇到了相同的问题,并通过在Ubuntu 16.04(Xenial Xerus)上运行以下命令解决了该问题:

sudo apt-get install python-setuptools python-dev build-essential

I had the same issue when installing the “Twisted” library and solved it by running the following command on Ubuntu 16.04 (Xenial Xerus):

sudo apt-get install python-setuptools python-dev build-essential

回答 10

我尝试了以上所有方法,但均未成功。然后,我将Python版本从2.7.10更新到2.7.13,它解决了我遇到的问题。

I tried all of the above with no success. I then updated my Python version from 2.7.10 to 2.7.13, and it resolved the problems that I was experiencing.


回答 11

这意味着pip中的某些软件包较旧或未正确安装。

  1. 尝试检查版本,然后升级pip。如果可行,请使用自动删除。

  2. 如果pip命令始终对任何命令显示错误或冻结,等等。

  3. 最好的解决方案是将其卸载或完全删除。

  4. 安装一个新的点,然后更新和升级您的系统。

  5. 我给出了在此处新鲜安装pip的解决方案-python:无法打开文件get-pip.py错误2]没有此类文件或目录

That means some packages in pip are old or not correctly installed.

  1. Try checking version and then upgrading pip.Use auto remove if that works.

  2. If the pip command shows an error all the time for any command or it freezes, etc.

  3. The best solution is to uninstall it or remove it completely.

  4. Install a fresh pip and then update and upgrade your system.

  5. I have given a solution to installing pip fresh here – python: can’t open file get-pip.py error 2] no such file or directory


回答 12

这对我来说是更简单的方法:

pip2 install Name

因此,如果您使用的是pip,请尝试使用pip3pip2

它应该解决问题。

This was the easier way for me:

pip2 install Name

So if you was using pip, try to use pip3 or pip2

It should solve the problem.


回答 13

pip3 install –upgrade setuptools警告:pip正在由旧的脚本包装程序调用。这将在以后的pip版本中失败。请参阅https://github.com/pypa/pip/issues/5599,以获取有关解决基本问题的建议。

******为了避免此问题,您可以使用-m pip调用Python,而不是直接运行pip。******

使用python3 -m pip“命令”例如:python3 -m pip install –user pyqt5

pip3 install –upgrade setuptools WARNING: pip is being invoked by an old script wrapper. This will fail in a future version of pip. Please see https://github.com/pypa/pip/issues/5599 for advice on fixing the underlying issue.

******To avoid this problem you can invoke Python with ‘-m pip’ instead of running pip directly.******

use python3 -m pip “command” eg: python3 -m pip install –user pyqt5


回答 14

这为我工作:

sudo xcodebuild -license

This worked for me:

sudo xcodebuild -license

回答 15

将Python升级到版本3解决了我的问题。什么都没做。

Upgrading Python to version 3 fixed my problem. Nothing else did.


回答 16

我从http://www.lfd.uci.edu/~gohlke/pythonlibs/下载了.whl文件,然后执行了以下操作:

pip install scipy-0.19.1-cp27-cp27m-win32.whl

请注意,您需要使用的版本(win32 / win_amd-64)取决于Python的版本,而不取决于Windows的版本。

I downloaded the .whl file from http://www.lfd.uci.edu/~gohlke/pythonlibs/ and then did:

pip install scipy-0.19.1-cp27-cp27m-win32.whl

Note that the version you need to use (win32/win_amd-64) depends on the version of Python and not that of Windows.


回答 17

我在新的开发设置上使用virtualenvs(带有pipenv)遇到了这个问题。

我只能通过将psycopg2版本从2.6.2升级到2.7.3来解决它。更多信息在https://github.com/psycopg/psycopg2/issues/594

I had this problem using virtualenvs (with pipenv) on my new development setup.

I could only solve it by upgrading the psycopg2 version from 2.6.2 to 2.7.3. More information is at https://github.com/psycopg/psycopg2/issues/594


回答 18

我在使用相同的错误消息时遇到了同样的问题,但是在Ubuntu 16.04 LTS(Xenial Xerus)上却相反:

命令“ python setup.py egg_info”在/ tmp / pip-install-w71uo1rg / poster /中失败,错误代码为1

我测试了上面提供的所有解决方案,但没有一个对我有用。我阅读了完整的TraceBack,发现我必须使用python版本2.7创建虚拟环境(默认情况下使用Python 3.5):

virtualenv --python=/usr/bin/python2.7 my_venv

激活它后,我将pip install unirest成功运行。

I faced the same problem with the same error message but on Ubuntu 16.04 LTS (Xenial Xerus) instead:

Command “python setup.py egg_info” failed with error code 1 in /tmp/pip-install-w71uo1rg/poster/

I tested all the solutions provided above and none of them worked for me. I read the full TraceBack and found out I had to create the virtual environment with Python version 2.7 instead (the default one uses Python 3.5 instead):

virtualenv --python=/usr/bin/python2.7 my_venv

Once I activated it, I run pip install unirest successfully.


回答 19

尝试在Linux上:

sudo apt install python-pip python-bluez libbluetooth-dev libboost-python-dev libboost-thread-dev libglib2.0-dev bluez bluez-hcidump

try on linux:

sudo apt install python-pip python-bluez libbluetooth-dev libboost-python-dev libboost-thread-dev libglib2.0-dev bluez bluez-hcidump

回答 20

我使用以下方法在Centos 7上解决了该问题:

sudo yum install libcurl-devel

I solved it on Centos 7 by using:

sudo yum install libcurl-devel

回答 21

我的Win10 PC上使用不同的软件包时遇到了相同的问题,并尝试了到目前为止提到的所有内容。

最后通过禁用Comodo Auto-Containment解决了该问题。

由于没有人提及它,我希望它能对某人有所帮助。

Had the same problem on my Win10 PC with different packages and tried everything mentioned so far.

Finally solved it by disabling Comodo Auto-Containment.

Since nobody has mentioned it yet, I hope it helps someone.


回答 22

我遇到了同样的问题,可以通过以下操作解决。

Windows Python需要通过SDK安装的Visual C ++库来构建代码,例如通过setuptools.extension.Extension或numpy.distutils.core.Extension。例如,在Windows中使用Python构建f2py模块需要安装上述Visual C ++ SDK。在Linux和Mac上,C ++库随编译器一起安装。

https://www.scivision.co/python-windows-visual-c++-14-required/

I had the same problem and was able to fix by doing the following.

Windows Python needs Visual C++ libraries installed via the SDK to build code, such as via setuptools.extension.Extension or numpy.distutils.core.Extension. For example, building f2py modules in Windows with Python requires Visual C++ SDK as installed above. On Linux and Mac, the C++ libraries are installed with the compiler.

https://www.scivision.co/python-windows-visual-c++-14-required/


回答 23

以下命令对我有用

[root@sandbox ~]# pip install google-api-python-client==1.6.4

Following below command worked for me

[root@sandbox ~]# pip install google-api-python-client==1.6.4

回答 24

更新setuptools时解决setup.pu egg_info问题的方法或其他方法不起作用。

  1. 如果CONDA可以安装版本的库,请使用conda而不是pip。
  2. 克隆库回购,然后尝试通过pip install -e .或通过进行安装python setup.py install

Methods to solve setup.pu egg_info issue when updating setuptools or not other methods doesnot works.

  1. If CONDA version of the library is available to install use conda instead of pip.
  2. Clone the library repo and then try installation by pip install -e . or by python setup.py install