Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用python实现输入重定向_Python_Input_Io Redirection - Fatal编程技术网

用python实现输入重定向

用python实现输入重定向,python,input,io-redirection,Python,Input,Io Redirection,我有以下程序来测试Python中的输入重定向 a = int(raw_input("Enter a number: ")) b = raw_input("Enter a string: ") print "number entered = ", a print "string entered = ", b 如果我在没有重定向的情况下运行此程序,则输入和输出如下所示: Enter a number: 100 Enter a string: sample number entered = 100

我有以下程序来测试Python中的输入重定向

a = int(raw_input("Enter a number: "))
b = raw_input("Enter a string: ")
print "number entered = ", a
print "string entered = ", b
如果我在没有重定向的情况下运行此程序,则输入和输出如下所示:

Enter a number: 100
Enter a string: sample
number entered =  100
string entered =  sample
现在,为了测试输入重定向,我有一个名为a.txt的文件,其中包含:

100
sample
然而,当我从a.txt重定向输入(如下所示)运行时,我的输入和输出会变得混乱

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

实际上,您希望将stdin插入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)
Tee
类只实现
raw\u input
使用的内容,因此不能保证它适用于
sys.stdin
的其他用途

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)