Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sqlite/3.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 如何处理任意[text]输入,并通过stdin将其输出到stdout?_Python_Stdin - Fatal编程技术网

Python 如何处理任意[text]输入,并通过stdin将其输出到stdout?

Python 如何处理任意[text]输入,并通过stdin将其输出到stdout?,python,stdin,Python,Stdin,我正在尝试从stdin读取文本,使用该文本进行处理,然后将结果发送到stdout char_stream = sys.stdin input_text = char_stream.read() output_text=do_stuff_with_text(input_text) sys.stdout.write(output_text) 如果我给它输入utf8,它无法读取字符流,我假设它需要ASCII。我在谷歌上搜索了一下,似乎我是这样读UTF-8的 codecs.getreader("ut

我正在尝试从stdin读取文本,使用该文本进行处理,然后将结果发送到stdout

char_stream = sys.stdin
input_text = char_stream.read()

output_text=do_stuff_with_text(input_text)
sys.stdout.write(output_text)
如果我给它输入utf8,它无法读取字符流,我假设它需要ASCII。我在谷歌上搜索了一下,似乎我是这样读UTF-8的

codecs.getreader("utf-8")(sys.stdin)
但是,这将只与utf8兼容,这对我来说是不够的,因为我希望能够在任何文本文件中使用管道。实际上,我还需要将输出编码为utf8


这里的常见做法是什么,比如说grep?我知道它不是用python编写的,但它仍然是一个有效的示例。我可以以任何格式导入文本,它从不抛出错误。如何在python中实现这一点?

请参阅。尽管它讨论的是文本文件,但检测编码的原理是一样的。在某种程度上,您需要假设编码是什么。read应该只返回字节。。。它通常不关心编码。。。另一方面写。。。