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!
Using sys. Python sys module stdin is used by the interpreter for standard input. Internally, it calls the input() function. The input string is appended with a newline character (\n) in the end. So, you can use the rstrip() function to remove it.
We can use the fileinput module to read from stdin in Python. fileinput. input() reads through all the lines in the input file names specified in command-line arguments. If no argument is specified, it will read the standard input provided.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With