Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

redirect - How to display the redirected stdin in 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:

Type something: You typed in: Hello

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

Type something: Hello

You typed in: Hello

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

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

Edit: 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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...