Input by redirection

stdin and stdout are objects created by the os module. We're going to write a script in which we will use stdin and stdout.

Create a script called redirection.py and write the following code in it:

import sys

class Redirection(object):
def __init__(self, in_obj, out_obj):
self.input = in_obj
self.output = out_obj
def read_line(self):
res = self.input.readline()
self.output.write(res)
return res

if __name__ == '__main__':
if not sys.stdin.isatty():
sys.stdin = Redirection(in_obj=sys.stdin, out_obj=sys.stdout)

a = input('Enter a string: ')
b = input('Enter another string: ')
print ('Entered strings are: ', repr(a), 'and', repr(b))

Run the preceding program as follows:

$ python3 redirection.py

We will receive the following output:

Output:
Enter a string: hello
Enter another string: python
Entered strings are: 'hello' and 'python'

Whenever the program runs in an interactive session, stdin is the keyboard input and stdout is the user's Terminal. The input() function is used to take input from the user, and print() is the way to write on the Terminal (stdout).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset