Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 311
Dr. Debasish Jana Avatar asked Dec 19 '15 02:12

Dr. Debasish Jana


People also ask

What is input redirection?

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.

How do you take an external input in python?

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.

What operator is used for input redirection?

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.

What is input redirection in Linux?

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.


1 Answers

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.

like image 57
Blender Avatar answered Oct 18 '22 12:10

Blender