Check if module exists, if not install it

前端 未结 8 1656
北海茫月
北海茫月 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:08

    Here is how it should be done, and if I am wrong, please correct me. However, Noufal seems to confirm it in another answer to this question, so I guess it's right.

    When writing the setup.py script for some scripts I wrote, I was dependent on the package manager of my distribution to install the required library for me.

    So, in my setup.py file, I did this:

    package = 'package_name'
    try:
        return __import__(package)
    except ImportError:
        return None
    

    So if package_name was installed, fine, continue. Else, install it via the package manager which I called using subprocess.

提交回复
热议问题