包装可调用项以捕获stdout、stderr、异常和返回

capturewrap的Python项目详细描述


Build Statuscodecov.io

方法捕获

包装可调用函数以捕获stdout、stderr、异常和返回。

为什么?

创建这个库是为了帮助测试python代码,其中 除了 写信给stdout和stderr。它允许在没有 调用者关心如何捕获重要的输出。

一个例子是当编写公共代码来测试python时 接口和相应的cli(通过调用main进行测试)。一个 通用测试程序-可能涉及复杂的设置和拆卸 -可以使用不同的接口运行并返回 封装输出,不考虑它们的形式(例如 python接口可能在成功时返回了True,但是 CLI可能调用了exit(0),并引发了SystemExit 例外情况)。

{存在用于捕获子查询和其他 stderr但没有也处理异常。

怎么做?

概述

fromcapturewrapimportCaptureWrapBuilderbuilder=CaptureWrapBuilder(capture_stdout=True,capture_stderr=True,capture_exceptions=True)wrapped=builder.build(my_method)result=wrapped(*args,**kwargs)print(f"stdout: {result.stdout}")print(f"stderr: {result.stderr}")print(f"return_value: {result.return_value}")print(f"exception: {result.exception}")

注意:如果捕捉到异常,return_value将是None

自定义异常捕获

最好只捕获一些异常,而将其他异常留给 像平常一样提高。要使用CaptureWrapBuilder执行此操作,请设置 capture_exceptions作为将异常作为 第一个参数并返回一个布尔值以指示 应捕获异常。例如

fromcapturewrapimportCaptureWrapBuilderbuilder=CaptureWrapBuilder(capture_exceptions=lambdae:isinstance(e,SystemExit)ande.code==0)wrapped=builder.build(exit)print(wrapped(0))# {"exception": ["SystemExit: 0\n"]}print(wrapped(1))# Raises exception

要求

  • python=3.6

安装

稳定版本可以通过 PyPI

$ pip install capturewrap

出血边缘版本可以直接从github安装:

$ pip install git+https://github.com/wtsi-hgi/python-capturewrap.git@$commitOrBranch#egg=capturewrap

实施

此实现使用 `redirect_stdout<;https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout>;。`_ 和 `redirect_stderr<;https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stderr>;`, 在Python3.5中添加到标准库中。

替代方案

  • iocapture:旧的解决方案, 用捕获方法替换sys.stdoutsys.stderr
  • capturer:复杂 在较低级别工作以拦截子进程的解决方案stdout 以及使用伪终端的stderr

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java如何在表被注释到配置之前获取表的元数据?   java滚动条不会出现在JList上   java JOGL监视器GPU内存   java为什么要使用RecyclerView onDraw延迟   java定制Oppo Reno 2 Z CPH1951(手机型号)的固件(闪存文件)   java自定义线程池执行器   java如何解决发布版本中重复的jar条目[com/安卓/volley/R.class]?   java如何使用Bukkit API触发事件?   java在blazemeter jmeter RTE插件中使用ctrl+w输入   C#/Visual Studio的java JDT等价物   java为什么当maxread值很大而收到的消息数量很小时,卡夫卡消费者会无限期消费?   java游戏2。x:包含模板列表的绑定模型   带压缩的java日志旋转   运行时。exec用java运行程序读取它正在做什么