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

后端 未结 3 432
隐瞒了意图╮
隐瞒了意图╮ 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:44

    I wanted to note that the current accepted answer could result in a possible app name collision. Importing from the app namespace doesn't give you the full picture of what's installed on the system.

    A better way would be:

    import pip
    
    packages = [package.project_name for package in pip.get_installed_distributions()]
    
    if 'package' not in packages:
        pip.main(['install', 'package'])
    

提交回复
热议问题