繁体   English   中英

使用Python编解码器导致sys.stdin的readline问题?

[英]Using Python codecs causes readline problems with sys.stdin?

我正在为命令行可执行文件(childprogram)编写一个Python包装器脚本(childscript.py)。 另一个可执行文件(parentprogram)将childscript.py和管道输出生成到childscript.py中。 childscript.py生成子程序:

    retval = subprocess.Popen(RUNLINE, shell=False, stdout=None, stderr=None, stdin=subprocess.PIPE)

如果childscript.py使用readline直接从sys.stdin执行一系列读取:

line = sys.stdin.readline()

我能够从parentprogram获得所有输出并将其输入到子程序中。

但是,如果我尝试使用编解码器模块:

sys.stdin = codecs.open(sys.stdin.fileno(), encoding='iso-8859-1', mode='rb', buffering=0)

或做一个:

sys.stdin = codecs.getreader('iso-8859-1')(sys.stdin.detach())

并尝试进行读取,读取不会从parentprogram获得所有输出。 如果我强制从parentprogram输出额外的输出,那么缺少的部分会与我推入的部分额外输出一起出现。看起来,当我使用编解码器模块时,childscript.py没有读取它提供给它的所有内容。

我做错了吗? 如果没有编解码器,当从parentprogram提供iso-8859-1编码的东西时,childscript.py会触发异常。

编辑:
我发现Python v3.x“open”也可以采用编码选项。 我将行改为使用“open”而不是“codecs.open”:

      sys.stdin = open(sys.stdin.fileno(), encoding='iso-8859-1', mode='r')

并且它按预期工作,没有open.codecs产生的任何问题。 我已将我的脚本切换为使用“open”。

如果任何人都可以解释为什么编解码器模块的行为不同,我会很感激。

刷新父级中的输出通道。

管道总是被缓冲。 通常的缓冲区大小为4KB。 与输出连接到控制台时不同,标准运行时不会在每行之后为您刷新输出。

尝试这个:

import sys
import os

fd = sys.stdin.fileno()
text = ''
while 1:
    try:
        raw_data = os.read(fd, 1024)
        text += unicode(raw_data, 'iso-8859-1')
        # now do something with text
    except (EOFError, KeyboardInterrupt):
        break

这样就可以避免使用readline() ,它会为非ascii字符发出错误,但仍然可以使用非阻塞读取。

唯一的问题是你必须自己将输入分成行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM