Installing python module within code

前端 未结 7 1199
孤独总比滥情好
孤独总比滥情好 2020-11-21 23:31

I need to install a package from PyPi straight within my script. Maybe there\'s some module or distutils (distribute, pip etc.) featur

7条回答
  •  忘了有多久
    2020-11-22 00:07

    If you want to use pip to install required package and import it after installation, you can use this code:

    def install_and_import(package):
        import importlib
        try:
            importlib.import_module(package)
        except ImportError:
            import pip
            pip.main(['install', package])
        finally:
            globals()[package] = importlib.import_module(package)
    
    
    install_and_import('transliterate')
    

    If you installed a package as a user you can encounter the problem that you cannot just import the package. See How to refresh sys.path? for additional information.

提交回复
热议问题