如何在 Python 中显示重定向的标准输入? [英] How to display the redirected stdin in Python?

查看:73
本文介绍了如何在 Python 中显示重定向的标准输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开始一个需要标准输入重定向的 Python 项目,使用类似于下面的代码:

I'm starting on a Python project in which stdin redirection is necessary, using code similar to below:

import sys
import StringIO

s = StringIO.StringIO("Hello")
sys.stdin = s
a = raw_input("Type something: ")
sys.stdin = sys.__stdin__
print("You typed in: "+a)

问题是,代码运行后,显示如下:

The problem is, after the code runs, the following is displayed:

输入:你输入的是:Hello

Type something: You typed in: Hello

有没有办法修改我的代码,从而改为显示以下内容?

Is there a way to modify my code such that the following is displayed instead?

输入:你好

您输入了:你好

我一直在寻找高低,但还没有找到答案.如果有人有想法,我将不胜感激.谢谢!

I've been searching high and low but have found no answer yet. I'll really appreciate if anyone has an idea. Thanks!

推荐答案

我不知道你为什么需要这样做,但你总是可以这样做:

I'm not sure why you would need to, but you could always do this:

a = raw_input("Type something: ")
if sys.stdin is not sys.__stdin__:
    print(a)
print("You typed in: "+a)

再说一次,根据需要将 raw_input 替换为您自己的实现可能更有意义.

Then again, swapping raw_input for your own implementation as needed would probably make more sense.

好的,根据您的评论,您似乎想要进行一些猴子修补.像这样:

okay, based on your, comment it looks like you'll want to do some monkey patching. Something like this:

old_raw_input = raw_input

def new_raw_input(prompt):
    result = old_raw_input(prompt)
    if sys.stdin is not sys.__stdin__:
        print result
    return result

raw_input = new_raw_input

当然,这可能会使重定向 stdin 没有实际意义.

Of course, this might make the point of redirecting stdin moot.

这篇关于如何在 Python 中显示重定向的标准输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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