Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python encoding for pipe.communicate

I'm calling pipe.communicate from Python's subprocess module from Python 2.6. I get the following error from this code:

from subprocess import Popen

pipe = Popen(cwd)

pipe.communicate( data )

For an arbitrary cwd, and where data that contains unicode (specifically 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)

This is happening, I presume, because pipe.communicate() is expecting ASCII encoded string, but data is unicode.

Is this the problem I'm encountering, and i sthere a way to pass unicode to pipe.communicate()?

Thank you for reading!

Brian

like image 493
Brian M. Hunt Avatar asked Jun 14 '10 19:06

Brian M. Hunt


1 Answers

I may have solved this by changing:

pipe.communicate( data )

to

pipe.communicate( data.encode('utf8') )

Though I stand to be corrected!

Brian

like image 99
Brian M. Hunt Avatar answered Sep 28 '22 13:09

Brian M. Hunt