Check if Python Package is installed

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

    Hmmm ... the closest I saw to a convenient answer was using the command line to try the import. But I prefer to even avoid that.

    How about 'pip freeze | grep pkgname'? I tried it and it works well. It also shows you the version it has and whether it is installed under version control (install) or editable (develop).

    0 讨论(0)
  • 2020-12-02 06:10

    As an extension of this answer:

    For Python 2.*, pip show <package_name> will perform the same task.

    For example pip show numpy will return the following or alike:

    Name: numpy
    Version: 1.11.1
    Summary: NumPy: array processing for numbers, strings, records, and objects.
    Home-page: http://www.numpy.org
    Author: NumPy Developers
    Author-email: numpy-discussion@scipy.org
    License: BSD
    Location: /home/***/anaconda2/lib/python2.7/site-packages
    Requires: 
    Required-by: smop, pandas, tables, spectrum, seaborn, patsy, odo, numpy-stl, numba, nfft, netCDF4, MDAnalysis, matplotlib, h5py, GridDataFormats, dynd, datashape, Bottleneck, blaze, astropy
    
    0 讨论(0)
  • 2020-12-02 06:11

    You can use this:

    class myError(exception):
     pass # Or do some thing like this.
    try:
     import mymodule
    except ImportError as e:
     raise myError("error was occurred")
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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))
    
    0 讨论(0)
  • 2020-12-02 06:21

    I'd like to add some thoughts/findings of mine to this topic. I'm writing a script that checks all requirements for a custom made program. There are many checks with python modules too.

    There's a little issue with the

    try:
       import ..
    except:
       ..
    

    solution. In my case one of the python modules called python-nmap, but you import it with import nmap and as you see the names mismatch. Therefore the test with the above solution returns a False result, and it also imports the module on hit, but maybe no need to use a lot of memory for a simple test/check.

    I also found that

    import pip
    installed_packages = pip.get_installed_distributions()
    

    installed_packages will have only the packages has been installed with pip. On my system pip freeze returns over 40 python modules, while installed_packages has only 1, the one I installed manually (python-nmap).

    Another solution below that I know it may not relevant to the question, but I think it's a good practice to keep the test function separate from the one that performs the install it might be useful for some.

    The solution that worked for me. It based on this answer How to check if a python module exists without importing it

    from imp import find_module
    
    def checkPythonmod(mod):
        try:
            op = find_module(mod)
            return True
        except ImportError:
            return False
    

    NOTE: this solution can't find the module by the name python-nmap too, I have to use nmap instead (easy to live with) but in this case the module won't be loaded to the memory whatsoever.

    0 讨论(0)
提交回复
热议问题