How to install a Python package from within IPython?


I wonder if it’s possible to install python packages without leaving the IPython shell.

Asked By: satoru



See the accepted answer from @Chronial which is the best way to do this in modern ipython or jupyter (as of 2018) is to use the %pip magic:

%pip install my_package

The answer below from 2011 is now outdated: See the accepted answer for an easier way to do this in modern jupyter.

You can use the ! prefix like this:

!pip install packagename

The ! prefix is a short-hand for the %sc command to run a shell command.

You can also use the !! prefix which is a short-hand for the %sx command to execute a shell command and capture its output (saved into the _ variable by default).

Answered By: aculich

This answer is outdated: See the accepted answer for an easier way to this in modern jupyter.

aculich’s answer will not work in all circumstances, for example:

  • If you installed ipython/jupyter in a venv and run it directly via the venv’s python binary
  • If you have multiple python versions, like EntryLevelR.

The correct command is:

import sys
!{sys.executable} -m pip install requests
Answered By: Chronial
import pip
pip.main(['install', 'package_name'])

The above shell-based answers don’t work unless pip is in your $PATH (e.g. on Windows).

Answered By: hurfdurf

I like hurfdurf’s answer, but on its own iPython may not recognize the new module (especially if it adds to the library path). Here’s an augmented example with iPython 3:

import pip
# import pygame at this point can report ImportError: No module named 'pygame'
import site
# now with refreshed module path...
import pygame
Answered By: Daniel

In case you are using Conda Package Manager, the following syntax might fit your needs

$ conda install -c conda-forge <targetPackageName>

Answered By: Julio Nobre

The best way to do this in modern ipython or jupyter is to use the %pip magic:

%pip install my_package
Answered By: Chronial

!pip install packagename or similar codes will not be the true answer if we have various python versions, where the desired python version is not the system default one. Such codes will install packages on the system default python version only. From my opinion, the following code would be helpful:

import pip
if int(pip.__version__.split('.')[0])>9:
    from pip._internal import main
    from pip import main
main(['install', 'package_name'])    # the strings in the square brackets could be specified as needed

This code is written based on pip version, which can be run from within the console and will be applied on any python versions which path is set by the console; This python version specs could be seen by import sys; sys.version, sys.path. I’m not sure this is the best approach, but the aforementioned code worked for my purposes and !pip install packagename or %pip install packagename did not (where python: 2.7.9, pip: 19.2.3, IPython QtConsole: 3.1.0).

Answered By: Ali_Sh