[python] Why does "pip install" inside Python raise a SyntaxError?

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

This question is related to python pip installation

The answer is


If you are doing it from command line,

try -

python -m pip install selenium

or (for Python3 and above)

python3 -m pip install selenium


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

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.


Try upgrade pip with the below command and retry

python -m pip install -U pip

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.

enter image description here

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.

enter image description here

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..

enter image description here

and I hope we are done with this!!


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).


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']) 

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())

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to pip

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip "E: Unable to locate package python-pip" on Ubuntu 18.04 How to Install pip for python 3.7 on Ubuntu 18? What is the meaning of "Failed building wheel for X" in pip install? Could not install packages due to an EnvironmentError: [Errno 13] How do I install Python packages in Google's Colab? Conda version pip install -r requirements.txt --target ./lib pip: no module named _internal AttributeError: Module Pip has no attribute 'main' Error after upgrading pip: cannot import name 'main'

Examples related to installation

You don't have write permissions for the /Library/Ruby/Gems/2.3.0 directory. (mac user) Conda version pip install -r requirements.txt --target ./lib How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning" PackagesNotFoundError: The following packages are not available from current channels: Tensorflow import error: No module named 'tensorflow' Downgrade npm to an older version Create Setup/MSI installer in Visual Studio 2017 how to install tensorflow on anaconda python 3.6 Application Installation Failed in Android Studio How to install pip for Python 3.6 on Ubuntu 16.10?