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