How to install and import Python modules at runtime?

后端 未结 4 893
猫巷女王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:05

    I solved my problem using the imp module.

    #!/usr/bin/env python
    
    import pip
    import imp
    
    def install_and_load(package):
        pip.main(['install', package])
    
        path = '/usr/local/lib/python2.7/dist-packages'
        if path not in sys.path:
            sys.path.append(path)
    
        f, fname, desc = imp.find_module(package)
        return imp.load(package, f, fname, desc)
    
    if __name__ == "__main__":
        try:
            import pexpect
        except:
            pexpect = install_and_load('pexpect')
    
        # More code...
    

    Actually the code is less than ideal, since I need to hardcode the Python module directory. But since the script is intended for a known target system, I think that is ok.

提交回复
热议问题