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
                A program that reads input from the keyboard can also read input from a text file. This is called input redirection, and is a feature of the command line interface of most operating systems.
You just write simple program and then run it from command line in any platform like Windows/ Linux. <,> are redirection operators which simply redirects the stdin and stdout to input. txt and output. txt.
Redirection is done using either the ">" (greater-than symbol), or using the "|" (pipe) operator which sends the standard output of one command to another command as standard input.
Input/Output (I/O) redirection in Linux refers to the ability of the Linux operating system that allows us to change the standard input ( stdin ) and standard output ( stdout ) when executing a command on the terminal. By default, the standard input device is your keyboard and the standard output device is your screen.
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.
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