How to install a Python package from within IPython?

后端 未结 5 1045
遥遥无期
遥遥无期 2020-11-27 14:01

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

相关标签:
5条回答
  • 2020-11-27 14:37

    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
    
    0 讨论(0)
  • 2020-11-27 14:40

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

    0 讨论(0)
  • 2020-11-27 14:50

    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
    
    0 讨论(0)
  • 2020-11-27 14:50

    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/

    0 讨论(0)
  • 2020-11-27 15:00
    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).

    0 讨论(0)
提交回复
热议问题