如何将raw_input重定向到stderr而不是stdout? [英] How to redirect the raw_input to stderr and not stdout?

查看:161
本文介绍了如何将raw_input重定向到stderr而不是stdout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 stdout 重定向到一个文件。但这会影响 raw_input 。我需要将 raw_input 的输出重定向到 stderr 而不是 stdout 。我怎么能这样做?

I want to redirect the stdout to a file. But This will affect the raw_input. I need to redirect the output of raw_input to stderr instead of stdout. How can I do that?

推荐答案

stdout 重定向到 stderr 暂时,然后恢复。

Redirect stdout to stderr temporarily, then restore.

import sys

old_raw_input = raw_input
def raw_input(*args):
    old_stdout = sys.stdout
    try:
        sys.stdout = sys.stderr
        return old_raw_input(*args)
    finally:
        sys.stdout = old_stdout

这篇关于如何将raw_input重定向到stderr而不是stdout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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