使用Python编解码器会导致sys.stdin出现读线问题吗?
我正在为命令行可执行文件(childprogram)编写Python包装器脚本(childscript.py)。另一个可执行文件(parentprogram)生成childscript.py并将输出导入childscript.py。childscript.py生成具有以下内容的childprogram:使用Python编解码器会导致sys.stdin出现读线问题吗?,python,codec,subprocess,Python,Codec,Subprocess,我正在为命令行可执行文件(childprogram)编写Python包装器脚本(childscript.py)。另一个可执行文件(parentprogram)生成childscript.py并将输出导入childscript.py。childscript.py生成具有以下内容的childprogram: retval = subprocess.Popen(RUNLINE, shell=False, stdout=None, stderr=None, stdin=subprocess.PI
retval = subprocess.Popen(RUNLINE, shell=False, stdout=None, stderr=None, stdin=subprocess.PIPE)
如果childscript.py使用readline直接从sys.stdin执行一系列读取:
line = sys.stdin.readline()
我能够从parentprogram获得所有输出,并将其输入childprogram
但是,如果我尝试通过执行以下操作来使用编解码器模块:
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似乎没有读取提供给它的所有内容
我做错什么了吗?如果没有编解码器,childscript.py在显示parentprogram中的iso-8859-1编码内容时会触发异常
编辑:我发现PythonV3.x“open”也可以使用编码选项。我将行更改为使用“open”而不是“codecs.open”: 它的工作原理与预期一样,没有open.codecs产生的任何问题。我已将脚本改为使用“打开”
如果有人能解释为什么编解码器模块的行为不同,我将不胜感激。刷新父级中的输出通道 管道总是被缓冲的。通常的缓冲区大小是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
这样可以避免使用将对非ascii字符发出错误的readline()
,但仍然可以使用非阻塞读取
唯一的问题是您必须自己将输入分隔成行。父程序的开发人员向我保证缓冲区正在刷新。
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