Reporter Backends#
Reporter backends 是一个插件钩子,允许您自定义命令行中某些元素的显示。以下是当前可以自定义的所有元素的列表
进度条(在包下载期间显示)
微调器(在 conda 等待长时间运行的任务完成时显示)
确认输入(是/否对话框)
conda info
布局
这可以使用 console
设置进行配置,可以通过命令行选项或在 .condarc
文件中定义。
有关在 conda 本身中配置和使用 reporter backends 的更多信息,请参阅
示例插件#
以下示例定义了一个简单的插件,该插件使用 pformat()
函数来渲染 conda 输出的某些部分
提示
这只是一个部分示例。要查看 reporter backend 的完整功能示例,请查看 console
模块。
from pprint import pformat
from conda import plugins
from conda.plugins.types import (
CondaReporterBackend,
ReporterRendererBase,
ProgressBarBase,
)
class PprintReporterRenderer(ReporterRendererBase):
"""
Implementation of the ReporterRendererBase abstract base class
"""
def detail_view(self, data):
return pformat(data)
def envs_list(self, data):
formatted_data = pformat(data)
return f"Environments: {formatted_data}"
def progress_bar(self, description, io_context_manager) -> ProgressBarBase:
"""Returns our custom progress bar implementation"""
return PprintProgressBar(description, io_context_manager)
class PprintProgressBar(ProgressBarBase):
"""
Blank implementation of ProgressBarBase which does nothing.
"""
def update_to(self, fraction) -> None:
pass
def refresh(self) -> None:
pass
def close(self) -> None:
pass
@plugins.hookimpl
def conda_reporter_backends():
yield CondaReporterBackend(
name="pprint",
description="Reporter backend based on the pprint module",
renderer=PprintReporterRenderer,
)
以下是我们定义的所有内容的摘要
定义 ReporterRendererBase
#
我们定义的第一个类 PprintReporterRenderer
是 ReporterRendererBase
的子类。基类是一个抽象基类,它要求我们定义其抽象方法的自定义实现。这些抽象方法在 conda 渲染输出时使用,是我们想要进行的所有自定义发生的地方。
定义 ProgressBarBase
#
我们定义的第二个类是 PprintProgressBar
。在此示例中,它只是 ProgressBarBase
的一个空实现。定义此项实际上会在配置此 reporter backend 时隐藏进度条。我们在本教程中这样做是因为完整的实现需要太长时间才能解释。请查看 TQDMProgressBar
以获取使用 tqdm 库的更实际的示例。
注册插件钩子#
最后,我们使用 plugins.hookimpl
装饰器定义 conda_reporter_backends
函数来注册我们的插件,该插件返回包装在 CondaReporterBackend
对象中的 PprintReporterRenderer
类。通过将 name
设置为 pprint
进行注册,我们将能够将此插件引用为 console
设置的新后端。
使用 reporter backend#
要使用我们新注册的 reporter backend,可以在 .condarc
配置文件中指定它
console: pprint
或者,可以在命令行中使用 --console
选项指定它
conda info --envs --console=pprint
进一步阅读#
有关如何从头开始创建 conda 插件的详细信息,请参阅以下存储库,其中还包含一个 cookiecutter 配方,您可以使用它轻松引导您的项目
以下是 reporter backends 插件钩子的 API 文档的相关区域
CondaReporterBackend
元数据对象,必须从 reporter backends 钩子定义中返回。conda_reporter_backends()
reporter backends 的 hookspec 定义,其中包含其用法的示例。console
我们用于console
reporter backend 的默认实现。json
我们用于json
reporter backend 的默认实现。