使用python输入重定向 [英] Input redirection with python

查看:54
本文介绍了使用python输入重定向的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下程序来测试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

现在,要测试输入重定向,我有一个名为a.txt的文件,其中包含:

Now, to test input redirection, I have a file a.txt named that contains:

100
sample

但是,当我运行从a.txt重定向的输入(如下所示)时,我的输入和输出会出现乱码.

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

推荐答案

您本质上想将stdin放入stdout:

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)

Tee 类仅实现 raw_input 所使用的内容,因此不能保证将其用于 sys.stdin 的其他用途.

The Tee class implements only what raw_input uses, so it's not guaranteed to work for other uses of sys.stdin.

这篇关于使用python输入重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆