ned*_*ned 5 python unicode popen python-2.7 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)
Run Code Online (Sandbox Code Playgroud)
将条目添加到环境中是必要的,因为输入字符串包含日文字符,并且当脚本未从命令行执行时(在我的情况下由Apache调用),Python无法猜测编码.
这个设置对我来说和其他命令一样正常,但是现在我正在使用chasen
(日语标记器),每当我发送unocode字符时子进程都没有返回,它只是坐在那里用Python脚本咀嚼内存.这似乎是一个编码问题,但我想我已经通过使用LC_ALL
环境变量指定编码来对此进行排序.
编辑:超级奇怪如下...我从命令行执行Python脚本时没有遇到此问题,但有'.'字符的明显例外.由于某种原因,这也导致了陌生感chasen
.
这是 chasen 中的一个错误。当通过 Python 运行时,您可以看到它发出以下系统调用:
\n\nwrite(1, "\\n", 1) = 1\nread(0, "", 4096) = 0\nwrite(1, "\\n", 1) = 1\nread(0, "", 4096) = 0\n
Run Code Online (Sandbox Code Playgroud)\n\n即它不能正确处理EOF。要解决此问题,只需将换行符 ( \'\\n\'
) 附加到 Python 字符串,如下所示:
# coding: utf-8\nimport os\nfrom subprocess import Popen, PIPE\n\nstring = u"\xe6\x82\xaa\xe5\xa6\xbb\xe3\x81\xaf\xe7\x99\xbe\xe5\xb9\xb4\xe3\x81\xae\xe4\xb8\x8d\xe4\xbd\x9c\xe3\x80\x82"\n\nenv = dict(os.environ)\nenv[\'LC_ALL\'] = \'en_US.UTF-8\'\nargs = [\'chasen\', \'-i u\', \'-F"%m "\']\nprocess = Popen(args, stdout=PIPE, stderr=PIPE, stdin=PIPE, env=env)\nout, err = process.communicate(input=(string + u\'\\n\').encode(\'utf-8\'))\n\nprint(out)\n
Run Code Online (Sandbox Code Playgroud)\n