Dr. Debasish Jana
Dr. Debasish Jana

Reputation: 7128

Input redirection with python

I have the following program to test input redirection in Python.

a = int(raw_input("Enter a number: "))
b = raw_input("Enter a string: ")
print "number entered = ", a
print "string entered = ", b

If I run this program without redirection, the input and output are shown below:

Enter a number: 100
Enter a string: sample
number entered =  100
string entered =  sample

Now, to test input redirection, I have a file a.txt named that contains:

100
sample

However, when I run with input redirected from a.txt (as below), my input and output gets garbled.

python doubt02.py < a.txt
Enter a number: Enter a string: number entered =  100
string entered =  sample

Please suggest if I have a better alternative to see (with input redirection) as below:

Enter a number: 100
Enter a string: sample
number entered =  100
string entered =  sample

Upvotes: 7

Views: 10228

Answers (1)

Blender
Blender

Reputation: 298492

You essentially want to tee stdin into stdout:

import sys

class Tee(object):
    def __init__(self, input_handle, output_handle):
        self.input = input_handle
        self.output = output_handle

    def readline(self):
        result = self.input.readline()
        self.output.write(result)

        return result

if __name__ == '__main__':
    if not sys.stdin.isatty():
        sys.stdin = Tee(input_handle=sys.stdin, output_handle=sys.stdout)

    a = raw_input('Type something: ')
    b = raw_input('Type something else: ')

    print 'You typed', repr(a), 'and', repr(b)

The Tee class implements only what raw_input uses, so it's not guaranteed to work for other uses of sys.stdin.

Upvotes: 6

Related Questions