How to install and import Python modules at runtime?

后端 未结 4 924
猫巷女王i
猫巷女王i 2021-01-02 11:41

I want to write a script to automatically setup a brand new ubuntu installation and install a django-based app. Since the script will be run on a new server, the Python scri

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-02 12:10

    For those who are using pip version greater than 10.x, there is no main function for pip so the alternative approach is using import pip._internal as pip instead of import pip like :

    Updated answer of Paulo

    import pip._internal as pip
    
    def install(package):
        pip.main(['install', package])
    
    if __name__ == '__main__':
        try:
            import pexpect
        except ImportError:
            install('pexpect')
            import pexpect
    

提交回复
热议问题