且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Python 中显示重定向的标准输入?

更新时间:2023-11-18 09:23:52

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

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.