Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 229
dangmai Avatar asked Apr 28 '11 00:04

dangmai


People also ask

How do I use SYS Stdin in Python?

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.

How do you read a standard input file in Python?

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.


1 Answers

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.

like image 179
Ian B. Avatar answered Oct 21 '22 18:10

Ian B.