pipe.communicate的Python编码

Bri*_*unt 11 python unicode encoding subprocess popen

我从Python 2.6中调用pipe.communicatePython的subprocess模块.我从这段代码中得到以下错误:

from subprocess import Popen

pipe = Popen(cwd)

pipe.communicate( data )
Run Code Online (Sandbox Code Playgroud)

对于任意cwd,以及data包含unicode(特别是0xE9)的地方:

Exec. exception: 'ascii' codec can't encode character u'\xe9' in position 507: ordinal not in range(128)
Traceback (most recent call last):  

... stdout, stderr = pipe.communicate( data )

  File
"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py",
line 671, in communicate
    return self._communicate(input)

  File
"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/subprocess.py",
line 1177, in _communicate
    bytes_written = os.write(self.stdin.fileno(), chunk)
Run Code Online (Sandbox Code Playgroud)

我认为这是正在发生的,因为pipe.communicate()期望ASCII编码的字符串,但是data是unicode.

这是我遇到的问题,我是否有办法将unicode传递给pipe.communicate()

谢谢你的阅读!

布赖恩

Bri*_*unt 14

可能通过改变来解决这个问题:

pipe.communicate( data )
Run Code Online (Sandbox Code Playgroud)

pipe.communicate( data.encode('utf8') )
Run Code Online (Sandbox Code Playgroud)

虽然我有待纠正!

布赖恩

  • 那就对了.管道(以及文件,套接字等)传输字节,而不是Unicode(即"字符").您必须编码Unicode才能传输它. (2认同)