Check if module exists, if not install it

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

    This approach of dynamic import work really well in cases you just want to print a message if module is not installed. Automatically installing a module SHOULDN'T be done like issuing pip via subprocess. That's why we have setuptools (or distribute).

    We have some great tutorials on packaging, and the task of dependencies detection/installation is as simple as providing install_requires=[ 'FancyDependency', 'otherFancy>=1.0' ]. That's just it!

    But, if you really NEED to do by hand, you can use setuptools to help you.

    from pkg_resources import WorkingSet , DistributionNotFound
    working_set = WorkingSet()
    
    # Printing all installed modules
    print tuple(working_set)
    
    # Detecting if module is installed
    try:
        dep = working_set.require('paramiko>=1.0')
    except DistributionNotFound:
        pass
    
    # Installing it (anyone knows a better way?)
    from setuptools.command.easy_install import main as install
    install(['django>=1.2'])
    
    0 讨论(0)
  • 2020-12-08 08:15

    You can use os.system as follows:

    import os
    
    package = "package_name"
    
    try:
        __import__package
    except:
        os.system("pip install "+ package)
    
    0 讨论(0)
提交回复
热议问题