python - 如何将 raw_input 重定向到 stderr 而不是 stdout?

标签 python io python-2.x

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

最佳答案

raw_input 的唯一问题是它将提示打印到标准输出。与其试图拦截它,不如自己打印提示,然后在没有提示的情况下调用 raw_input,这不会向标准输出打印任何内容?

def my_input(prompt=None):
    if prompt:
        sys.stderr.write(str(prompt))
    return raw_input()

如果你想用这个替换 raw_input:

import __builtin__
def raw_input(prompt=None):
    if prompt:
        sys.stderr.write(str(prompt))
    return __builtin__.raw_input()

(有关更多信息,请参阅 __builtin__ 上的文档,raw_input 和其他 built-in functions 存储在的模块。您通常不必导入 它,但文档中没有任何内容可以保证这一点,所以最好是安全的……)

在 Python 3.2+ 中,模块名为 builtins而不是 __builtin__。 (当然 3.x 没有 raw_input ,它被重命名为 input ,但同样的想法可以在那里使用。)

关于python - 如何将 raw_input 重定向到 stderr 而不是 stdout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21202403/

相关文章:

python - 在 python 2.7 中将包含 datetime.timedelta 的 numpy 数组转换为秒的优雅方法

python - 在python中填充两条曲线之间的区域

JavaIO : Using scanner and printWriter to copy the contents of a text file and put them in another text file

Android - 字典文件。哪个更快,数据库还是直接读取文件?

python - 如何打印在另一个 Tkinter 脚本中调用的 gui 脚本的输出?

python - 检索 Python 集合的下一个最小元素

python - 将 Pandas Dataframe 转换为特定的 json 格式

swift - XIB View 的自动布局约束

python - 无法导入统计模型

web-applications - 学习 Python 进行 Web 开发。 Python 2 还是 3?