Check if module exists, if not install it

前端 未结 8 1640
北海茫月
北海茫月 2020-12-08 07:41

I want to check if a module exists, if it doesn\'t I want to install it.

How should I do this?

So far I have this code which correctly prints f

8条回答
  •  隐瞒了意图╮
    2020-12-08 08:14

    import pip
    
    def import_or_install(package):
        try:
            __import__(package)
        except ImportError:
            pip.main(['install', package])       
    

    This code simply attempt to import a package, where package is of type str, and if it is unable to, calls pip and attempt to install it from there.

提交回复
热议问题