Input redirection with python

江枫思渺然 提交于 2021-01-27 05:08:43

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/34366763/input-redirection-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!