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!
I'm not sure why you would need to, but you could always do this:
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:
Of course, this might make the point of redirecting stdin moot.
EDIT: After reading the other answers and comments I think I have found a good way to really redirect the stdin. Note that I have assumed that you will know the the inputs to the end user's raw_inputs need to be.
User's Code (Named some_module.py)
Your Test Script (Named whatever you like)
Running the Script Yields
Original Answer
Not sure if you're looking for such a literal answer but here it is
Yields:
Do this.
Now the existing module is working with your
raw_input
, not the built-inraw_input
. Yours can do anything to provide fake inputs and fake outputs.