0

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
2
  • 2
    One way (the most obvious one) is to run your code and if you get import errors then you know you are missing imports. I think you may need to describe your use case, or what problem you are solving. For instance, you could create a requirements.txt file based on your working development code just make sure when you create new venvs for your project you set it up correctly, or if you have a deployment process it becomes part of that process. Commented Apr 2 at 22:54
  • i would go to folder with venv, activate venv, and run pip list (with some grep to filter module) to check if it has this module. Eventually instead of activing venv I would use venv/bin/python -m pip list to cech modules in this venv. And this doesn't need Python but bash/shell script. In Python it may need to run with subprocess.run() Commented Apr 3 at 9:51

1 Answer 1

0
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

Sign up to request clarification or add additional context in comments.

1 Comment

you could describe it before code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.