python - 当 stdin 包含 unicode 时,Popen 子进程不退出

标签 python python-2.7 unicode popen python-unicode

我正在使用 Popen 执行一个子进程,并按如下方式为其提供输入(使用 Python 2.7.4):

env = dict(os.environ)
env['LC_ALL'] = 'en_US.UTF-8'
args = ['chasen', '-i u', '-F"%m "']
process = Popen(args, stdout=PIPE, stderr=PIPE, stdin=PIPE, env=env)
out, err = process.communicate(input=string)

将条目添加到执行它的环境是必要的,因为输入字符串包含日文字符,并且当脚本不是从命令行执行时(在我的例子中由 Apache 调用),Python 无法猜测编码。

这个设置对我来说用其他命令工作得很好,但是现在我正在使用 chasen(一个日语分词器),每当我向它发送 unicode 字符时,子进程不会返回,它只是坐着那里的 Python 脚本会占用内存。这似乎是一个编码问题,但我认为我可以通过使用 LC_ALL 环境变量指定编码来解决这个问题。

编辑:额外的怪异如下...从命令行执行 Python 脚本时我没有遇到这个问题,但明显的异常(exception)是“。”字符。出于某种原因,这也导致了 chasen 的奇怪。

最佳答案

这是 chasen 中的一个错误。当通过 Python 运行时,您可以看到它发出的以下系统调用:

write(1, "\n", 1)                       = 1
read(0, "", 4096)                       = 0
write(1, "\n", 1)                       = 1
read(0, "", 4096)                       = 0

即它不能正确处理 EOF .要解决此问题,只需将换行符 ('\n') 添加到您的 Python 字符串,如下所示:

# coding: utf-8
import os
from subprocess import Popen, PIPE

string = u"悪妻は百年の不作。"

env = dict(os.environ)
env['LC_ALL'] = 'en_US.UTF-8'
args = ['chasen', '-i u', '-F"%m "']
process = Popen(args, stdout=PIPE, stderr=PIPE, stdin=PIPE, env=env)
out, err = process.communicate(input=(string + u'\n').encode('utf-8'))

print(out)

关于python - 当 stdin 包含 unicode 时,Popen 子进程不退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19016481/

相关文章:

python - 准确找到最小的特征值

python - Pandas 用常量字符串连接列的所有成员

unicode - 为什么我无法在 LaTeX 中显示 ð 符号?

python - 在文本 block 中查找子字符串,除非它是另一个子字符串的一部分

python - 使用 python 对药片进行雕刻印记检测

html - 在python中使用模式时无法获取网站名称

用于在 UTF8 和 UTF16 偏移量之间转换的 Java 代码(Java 字符串偏移量与 Python 3 字符串偏移量之间的转换)

python - Kivy(python-for-android)缺少编解码器

python - Flask 看不到配置文件中的配置值

python - 将 defaultdict(list) 写入文件