How to install a missing python package from inside the script that needs it?

后端 未结 3 451
隐瞒了意图╮
隐瞒了意图╮ 2021-02-05 11:27

Assuming that you already have pip or easy_install installed on your python distribution, I would like to know how can I installed a required package in the user directory from

3条回答
  •  深忆病人
    2021-02-05 11:32

    Updated for newer pip version (>= 10.0):

    try:
        import zumba
    except ImportError:
        from pip._internal import main as pip
        pip(['install', '--user', 'zumba'])
        import zumba
    

    Thanks to @Joop I was able to come-up with the proper answer.

    try:
        import zumba
    except ImportError:
        import pip
        pip.main(['install', '--user', 'zumba'])
        import zumba
    

    One important remark is that this will work without requiring root access as it will install the module in user directory.

    Not sure if it will work for binary modules or ones that would require compilation, but it clearly works well for pure-python modules.

    Now you can write self contained scripts and not worry about dependencies.

提交回复
热议问题