Reputation: 33225
I wonder if it's possible to install python packages without leaving the IPython shell.
Upvotes: 57
Views: 57504
Reputation: 14855
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).
Upvotes: 111
Reputation: 2816
!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
else:
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).
Upvotes: 0
Reputation: 70763
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:
python
binaryThe correct command is:
import sys
!{sys.executable} -m pip install requests
Upvotes: 19
Reputation: 70763
The best way to do this in modern ipython or jupyter is to use the %pip
magic:
%pip install my_package
Upvotes: 10
Reputation: 4395
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/
Upvotes: 0
Reputation: 317
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
Upvotes: 3
Reputation: 342
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).
Upvotes: 9