49

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

aculich
  • 13,401
  • 8
  • 58
  • 69
satoru
  • 27,201
  • 27
  • 83
  • 126

6 Answers6

96

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

aculich
  • 13,401
  • 8
  • 58
  • 69
  • 4
    Actually, you can just prefix the command with an ! e.g. `!pip install packagename`. – Thomas K Dec 30 '11 at 14:09
  • 1
    @ThomasK Yes, you are right! I updated my answer to use `!` and also explain `!!`, `%sc`, and `%sx`. I am going to suggest to the iPython maintainers that they update the `%quickref` docs to clearly mention `!` and `!!` as alternates! – aculich Dec 30 '11 at 17:39
  • 1
    Great, thanks. I've just seen your pull request (I am one of the IPython devs ;) ) – Thomas K Dec 30 '11 at 18:39
  • 1
    @ThomasK Awesome! Glad to see that IPython devs are active over here. – aculich Dec 30 '11 at 19:20
  • 1
    How would you specify the python version? For example, I have Python 2.7 and 3.5 kernels in my notebooks. When I use the `!pip install` the package is only installed for version 3.5. – EntryLevelR Mar 14 '17 at 21:58
16

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


The accepted answer by aculich 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
Chronial
  • 55,303
  • 13
  • 76
  • 85
7
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).

hurfdurf
  • 302
  • 3
  • 8
3

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
pip.main(['install','pygame'])
# import pygame at this point can report ImportError: No module named 'pygame'
import site
site.main()
# now with refreshed module path...
import pygame
Daniel
  • 79
  • 3
0

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

$ conda install -c conda-forge <targetPackageName>

https://pypi.org/project/earthpy/

Julio Nobre
  • 3,693
  • 2
  • 35
  • 45
0

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

%pip install my_package
Chronial
  • 55,303
  • 13
  • 76
  • 85