Python2.7中的contextlib.redirect_stdout [英] contextlib.redirect_stdout in Python2.7

查看:242
本文介绍了Python2.7中的contextlib.redirect_stdout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Python2.7,并且需要该功能: contextlib.redirect_stdout . 我的意思是,我想重定向特定功能(而不是整个程序)的输出. 问题是-只有Python3支持"context.redirect_stdout",而没有Python2.7.

I use Python2.7 and I want the function: contextlib.redirect_stdout. I mean, I want to redirect the output of specific function (not the all program). The problem is - only Python3 supports "context.redirect_stdout" and no Python2.7.

有人知道我该如何在Python2.7中使用相同的功能或实现相同的想法?

Someone know how can I use the same function in Python2.7 or to implement the same idea?

预先感谢

推荐答案

如果您不担心重用同一上下文管理器对象,则类似的事情应该可以完成.

Something like this should do the job if you're not worried about re-using the same context manager object.

import sys
import contextlib

@contextlib.contextmanager
def redirect_stdout(target):
    original = sys.stdout
    try:
        sys.stdout = target
        yield
    finally:
        sys.stdout = original

这篇关于Python2.7中的contextlib.redirect_stdout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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