Check if Python Package is installed

前端 未结 16 1111
刺人心
刺人心 2020-12-02 05:59

What\'s a good way to check if a package is installed while within a Python script? I know it\'s easy from the interpreter, but I need to do it within a script.

I g

16条回答
  •  感情败类
    2020-12-02 06:20

    If you'd like your script to install missing packages and continue, you could do something like this (on example of 'krbV' module in 'python-krbV' package):

    import pip
    import sys
    
    for m, pkg in [('krbV', 'python-krbV')]:
        try:
            setattr(sys.modules[__name__], m, __import__(m))
        except ImportError:
            pip.main(['install', pkg])
            setattr(sys.modules[__name__], m, __import__(m))
    

提交回复
热议问题