Using conda install within a python script

前端 未结 6 1911
后悔当初
后悔当初 2021-02-04 02:13

According to this answer you can import pip from within a Python script and use it to install a module. Is it possible to do this with conda install?

The co

6条回答
  •  失恋的感觉
    2021-02-04 02:39

    Having worked with conda from Python scripts for a while now, I think calling conda with the subprocess module works the best overall. In Python 3.7+, you could do something like this:

    import json
    from subprocess import run
    
    
    def conda_list(environment):
        proc = run(["conda", "list", "--json", "--name", environment],
                   text=True, capture_output=True)
        return json.loads(proc.stdout)
    
    
    def conda_install(environment, *package):
        proc = run(["conda", "install", "--quiet", "--name", environment] + packages,
                   text=True, capture_output=True)
        return json.loads(proc.stdout)
    

    As I pointed out in a comment, conda.cli.main() was not intended for external use. It parses sys.argv directly, so if you try to use it in your own script with your own command line arguments, they will get fed to conda.cli.main() as well.

    @YenForYang's answer suggesting conda.cli.python_api is better because this is a publicly documented API for calling conda commands. However, I have that it still has rough edges. conda builds up internal state as it executes a command (e.g. caches). The way conda is usually used and usually tested is as a command line program. In that case, this internal state is discarded at the end of the conda command. With conda.cli.python_api, you can execute several conda commands within a single process. In this case, the internal state carries over and can sometimes lead to unexpected results (e.g. the cache becomes outdated as commands are performed). Of course, it should be possible for conda to handle this internal state directly. My point is just that using conda this way is not the main focus of the developers. If you want the most reliable method, use conda the way the developers intend it to be used -- as its own process.

    conda is a fairly slow command, so I don't think one should worry about the performance impact of calling a subprocess. As I noted in another comment, pip is a similar tool to conda and explicitly states in its documentation that it should be called as a subprocess, not imported into Python.

提交回复
热议问题