Skip to content

Instantly share code, notes, and snippets.

@DeadBranches
Last active March 29, 2023 21:48
Show Gist options
  • Save DeadBranches/c40052069d0d09ec0a4423cc5f3b7ad0 to your computer and use it in GitHub Desktop.
Save DeadBranches/c40052069d0d09ec0a4423cc5f3b7ad0 to your computer and use it in GitHub Desktop.
Find in which conda environments a package is installed.
import os
import subprocess
from typing import List
def get_conda_envs() -> List[str]:
"""
Get a list of conda environments and return their names.
"""
# Execute the `conda env list` command and capture its output
result = subprocess.run(["conda", "env", "list"], capture_output=True, text=True)
output = result.stdout
# Extract environment names from the output
env_names = clean_env_output(output)
return env_names
def clean_env_output(output: str) -> List[str]:
"""
Clean the output of `conda env list` and return the environment names as a list.
"""
# Extract environment names from non-empty and non-comment lines
env_names = [line.split()[0] for line in output.splitlines() if line.strip() and not line.startswith("#")]
return env_names
def search_package_in_env(env_name: str, package: str) -> bool:
"""
Check if the given package is installed in the specified environment.
Return True if the package is found, False otherwise.
"""
# Execute the `conda env export -n $env_name` command and capture its output
result = subprocess.run(["conda", "env", "export", "-n", env_name], capture_output=True, text=True)
output = result.stdout
# Return True if the package name is found in the output, False otherwise
return package in output
def find_package_in_environments(package: str) -> List[str]:
"""
Iterate through all conda environments and return a list of environments that have the specified package installed.
"""
# Get the list of conda environments
environments = get_conda_envs()
# Find environments with the specified package installed
envs_with_package = [env for env in environments if search_package_in_env(env, package)]
return envs_with_package
def main():
# 1. Get the package name from the user
package_name = input("Enter the package name: ")
# 2. Find environments with the specified package installed
envs_with_package = find_package_in_environments(package_name)
# 3. Print the result
if envs_with_package:
print(f"The package '{package_name}' is installed in the following environments:")
for env in envs_with_package:
print(f"- {env}")
else:
print(f"The package '{package_name}' is not installed in any environment.")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment