pythonpython-importlibvenv

Check if a python module exists with specific venv path


If I have a venv path, how can I find out if a Python module is installed inside that venv?

I normally use importlib.util.find_spec. But this only works for the current venv that is active and does not work if I have a different venv path.

from importlib.util import find_spec

if find_spec('numpy'):
    # Do something

Solution

  • import sys
    import importlib.util
    import os
    from pathlib import Path
    
    def is_module_installed_in_venv(module_name, venv_path):
        venv_python_lib_path = Path(venv_path) / 'lib'
        for python_dir in venv_python_lib_path.iterdir():
            if python_dir.name.startswith('python'):
                site_packages_path = python_dir / 'site-packages'
                break
        
        if not site_packages_path.exists():
            return False
        
        sys.path.insert(0, str(site_packages_path))
    
        module_spec = importlib.util.find_spec(module_name)
        
        sys.path.pop(0)
        
        return module_spec is not None
    
    venv_path = '/home/user/anaconda3/envs/env_name/' 
    module_name = 'numpy'
    
    if is_module_installed_in_venv(module_name, venv_path):
        print("do something")
    

    this works , make sure to include the full path