用于模拟/包装stdin/stdout/stderr的上下文管理器
stdio-mgr的Python项目详细描述
当前开发版本:
最新稳定版本:
信息:
有cli python应用程序吗?
希望自动测试实际控制台输入和输出 面向用户的组件?
stdio manager可以提供帮助。
虽然这里的某些功能或多或少是 redirect_stdout和redirect_stderr在^{tt3}中$ within the standard library, 它提供了(i)一种更简洁的方法来同时模拟stdout和stderr, 以及(ii)模拟stdin的机制,该机制在contextlib中不可用。
首先,安装:
$ pip install stdio-mgr
那就用吧!
下面的所有示例都假设stdio_mgr已经 已通过以下方式导入:
from stdio_mgr import stdio_mgr
mockstdout:
>>> with stdio_mgr() as (in_, out_, err_): ... print('foobar') ... out_cap = out_.getvalue() >>> out_cap 'foobar\n' >>> in_.closed and out_.closed and err_.closed True
默认情况下printappends a newline 在每个参数之后,这就是为什么out_cap是'foobar\n' 不仅仅是'foobar'。
按照当前的实现,stdio_mgr关闭所有三个模拟流 退出管理的上下文。
mockstderr:
>>> import warnings >>> with stdio_mgr() as (in_, out_, err_): ... warnings.warn("'foo' has no 'bar'") ... err_cap = err_.getvalue() >>> err_cap "...UserWarning: 'foo' has no 'bar'\n..."
mockstdin:
模拟用户输入必须预先加载到模拟流中。 确保输入中包含与 每个模拟的回车keypress! 否则,input将挂起,等待换行 那永远不会来。
如果提前知道整个输入, 它可以作为stdio_mgr的参数提供。 否则,.append()模拟输入到in_ 根据需要在托管上下文中:
>>> with stdio_mgr('foobar\n') as (in_, out_, err_): ... print('baz') ... in_cap = input('??? ') ... ... _ = in_.append(in_cap[:3] + '\n') ... in_cap2 = input('??? ') ... ... out_cap = out_.getvalue() >>> in_cap 'foobar' >>> in_cap2 'foo' >>> out_cap 'baz\n??? foobar\n??? foo\n'
_ =赋值禁止返回值的printing 从in_.append()调用-否则,它将被交错 在out_cap中,因为此示例是针对交互式上下文显示的。 对于非交互执行,如unittest、pytest等, 不需要这些“静音”作业。
两者都提示'??? '输入input和模拟的输入字符串 与out_相呼应,模拟cli用户将看到的内容。
微妙之处:当后面的换行符被去掉时,例如'foobar\n'。 通过input,它是out_中的retained。 这是因为in_将从中读取的内容发送到out_在将内容传递给input之前。
要修改内部print调用 在一个函数或方法中?
除了模拟之外,stdio_mgr还可以用于 包装直接输出到stdout/stderr的函数。astdout示例:
>>> def emboxen(func): ... def func_wrapper(s): ... from stdio_mgr import stdio_mgr ... ... with stdio_mgr() as (in_, out_, err_): ... func(s) ... content = out_.getvalue() ... ... max_len = max(map(len, content.splitlines())) ... fmt_str = '| {{: <{0}}} |\n'.format(max_len) ... ... newcontent = '=' * (max_len + 4) + '\n' ... for line in content.splitlines(): ... newcontent += fmt_str.format(line) ... newcontent += '=' * (max_len + 4) ... ... print(newcontent) ... ... return func_wrapper >>> @emboxen ... def testfunc(s): ... print(s) >>> testfunc("""\ ... Foo bar baz quux. ... Lorem ipsum dolor sit amet.""") =============================== | Foo bar baz quux. | | Lorem ipsum dolor sit amet. | ===============================
在PyPI上提供 (pip install stdio-mgr)。
来源于GitHub。错误报告 欢迎您在 Issues那一页。
版权所有(c)2018-2019 Brian Skin
许可证:麻省理工学院的许可证。见LICENSE.txt 完整的许可条款。