python - Popen.communicate() throws UnicodeDecodeError -
i have code:
def __executecommand(self, command: str, input: str = none) -> str: p = sub.popen(command, stdout=sub.pipe, stderr=sub.pipe, stdin=sub.pipe, universal_newlines=true) p.stdin.write(input) output, error = p.communicate() if (len(errors) > 0): raise environmenterror("could not generate key: " + error) elif (p.returncode != 0): raise environmenterror("could not generate key. return value: " + p.returncode) return output
and unicodedecodeerror in line output, error = p.communicate()
:
traceback (most recent call last): file "c:\python34\lib\threading.py", line 921, in _bootstrap_inner self.run() file "c:\python34\lib\threading.py", line 869, in run self._target(*self._args, **self._kwargs) file "c:\python34\lib\subprocess.py", line 1170, in _readerthread buffer.append(fh.read()) file "c:\python34\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] unicodedecodeerror: 'charmap' codec can't decode byte 0x81 in position 27: character maps <undefined>
how can fix this?
univeral_newlines=true
enables text mode. subprocess output (bytes) decoded using locale.getpreferredencoding(false)
character encoding @cdosborn mentioned.
if doesn't work, provide actual encoding
used command
. and/or specify error handler such 'ignore'
,'surrogateescape'
, etc errors
parameter:
from subprocess import popen, pipe def __executecommand(self, command: str, input: str = none, encoding=none, errors='strict') -> str: text_mode = (encoding none) popen(command, stdout=pipe, stderr=pipe, stdin=pipe, universal_newlines=text_mode) p: if input not none , not text_mode: input = input.encode(encoding, errors) # convert bytes output, err = p.communicate(input) if err or p.returncode != 0: raise environmenterror("could not generate key. " "error: {}, return value: {}".format( ascii(err), p.returncode)) return output if text_mode else output.decode(encoding, errors)