Check if Python Package is installed

前端 未结 16 1044
刺人心
刺人心 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:12

    You can use the pkg_resources module from setuptools. For example:

    import pkg_resources
    
    package_name = 'cool_package'
    try:
        cool_package_dist_info = pkg_resources.get_distribution(package_name)
    except pkg_resources.DistributionNotFound:
        print('{} not installed'.format(package_name))
    else:
        print(cool_package_dist_info)
    

    Note that there is a difference between python module and a python package. A package can contain multiple modules and module's names might not match the package name.

提交回复
热议问题