Get list of conda packages programmatically in Python

Viewed 686

Is there a way to get all conda packages programmatically in Python?

Basically, I want to find the Python equivalent of running

conda list

Of course I could open a os subprocess and just call conda list, but I was hoping for a better solution than that.

2 Answers

One needs to have the conda Python package installed in the environment, which is usually only true for the base environment. One can then use the same code that conda list calls internally, namely, list_packages from the module conda.cli.main_list. For example, the following would be the equivalent to conda list -n foo:

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

prefix = "/path/to/miniconda3/envs/foo"

exitcode, output = list_packages(prefix)
print('\n'.join(map(text_type, output)))

Note that this code is prone to break, since it is using internals.

Signature

>>> help(list_packages)

# Help on function list_packages in module conda.cli.main_list:
list_packages(prefix, regex=None, format='human', show_channel_urls=None)

Try using -

help('modules')

in interactive mode. ( It works in cpython.)

Related