包装可调用项以捕获stdout、stderr、异常和返回
capturewrap的Python项目详细描述
方法捕获
包装可调用函数以捕获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中添加到标准库中。