如何从Python内部检测软件包是否由conda管理 [英] How to detect from within Python whether packages are managed with conda

查看:88
本文介绍了如何从Python内部检测软件包是否由conda管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从Python会话中以一般方式检测它是否由conda管理。

I would like to detect in a general way from within a Python session whether it is managed by conda.

一些通用性不足以有用的想法:

A few ideas that are not general enough to be useful:

如何在以下位置找到康达环境的名称

import os
is_conda = 'CONDA_PREFIX' in os.system or 'CONDA_DEFAULT_ENV' in os.system

这似乎在root conda环境中不起作用,其中这些变量不是总是定义的。如果在使用其他Python安装时激活了conda,也可能会产生误报。

This seems not to work in the root conda environment, where these variables are not always defined. It also has potential false positives if conda happens to be activated while you are using another Python installation.

import sys
is_conda = ('anaconda' in sys.executable) or ('miniconda' in sys.executable)

这在用户在默认路径中安装anaconda / miniconda的情况下有效。否则可能会失败。

This will work in the case that users install anaconda/miniconda in the default path. It may fail otherwise. It's also easy to imagine false-positives.

可以通过某种方式判断用户的python环境是否为蟒蛇,在某些情况下,您可以检查Python版本字符串:

As noted in the answers to any way to tell if user's python environment is anaconda, you can check the Python version string in some cases:

import sys
is_conda = ('Continuum Analytics' in sys.version) or ('Anaconda' in sys.version)

该功能目前适用于通过默认渠道安装的Python,但这非常脆弱,将来可能会中断,特别是在Continuum公司名称更改的情况下。如果从诸如conda-forge之类的第三方来源安装Python,它也可能会失败。

This works currently for Python installed from the default channel, but this is quite brittle and may break in the future, particularly with Continuum's company name change. It also probably fails if Python is installed from a third-party source like conda-forge.

try:
    import conda
except:
    is_conda = False
else:
    is_conda = True

只要在根conda环境中,此方法就可以工作,但是如果您在另一个conda env中没有安装 conda 软件包,则通常会失败

This works as long as you're in the root conda environment, but generally fails if you're in another conda env where the conda package is not installed by default.

来自Atto Allas的建议以下

Suggestion from Atto Allas below:

import subprocess
try:
    retcode = subprocess.call(['conda', 'install', '-y', 'pip'])
except:
    is_conda = False
else:
    is_conda = (retcode == 0)

这在最简单的情况下有效,但在使用多个内核的常见情况下失败在Jupyter,其中 conda 可执行文件可能连接或可能不连接到当前的Python内核。

This works in the simplest cases, but fails in the common case of using multiple kernels in Jupyter, where the conda executable may or may not be connected to the current Python kernel.

是否有完全通用的方法从Python中检测该Python安装是否由conda管理?

Is there any entirely general way to detect from Python whether that Python installation is managed by conda?

推荐答案

import sys, os
is_conda = os.path.exists(os.path.join(sys.prefix, 'conda-meta'))

这篇关于如何从Python内部检测软件包是否由conda管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆