Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
682 views
in Technique[技术] by (71.8m points)

anaconda - Conda: list all environments that use a certain package

How can one get a list of all environments that use a certain package in conda?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here's an example of how to do it with the Conda Python package (run this in base environment):

import conda.gateways.logging
from conda.core.envs_manager import list_all_known_prefixes
from conda.cli.main_list import list_packages
from conda.common.compat import text_type

# package to search for; this can be a regex
PKG_REGEX = "pymc3"

for prefix in list_all_known_prefixes():
    exitcode, output = list_packages(prefix, PKG_REGEX)
    
    # only print envs with results
    if exitcode == 0 and len(output) > 3:
        print('
'.join(map(text_type, output)))

This works as of Conda v4.10.0, but there since it relies on internal methods, there's no guarantee going forward. Perhaps this should be a feature request, say for a CLI command like conda list --any.


Script Version

Here is a version that uses arguments for package names:

conda-list-any.py

#!/usr/bin/env conda run -n base --no-capture-output python

## Usage: conda-list-any.py [PACKAGE ...]
## Example: conda-list-any.py numpy pandas

import conda.gateways.logging
from conda.core.envs_manager import list_all_known_prefixes
from conda.cli.main_list import list_packages
from conda.common.compat import text_type
import sys


for pkg in sys.argv[1:]:
    print("#"*80)
    print("# Checking for package '%s'..." % pkg)

    n = 0
    for prefix in list_all_known_prefixes():
        exitcode, output = list_packages(prefix, pkg)
        if exitcode == 0 and len(output) > 3:
            n += 1
            print("
" + "
".join(map(text_type, output)))

    print("
# Found %d environment%s with '%s'." % (n, "" if n == 1 else "s", pkg))
    print("#"*80 + "
")

The shebang at the top should ensure that it will run in base, at least on Unix/Linux systems.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...