Python popen () - chat (str.encode (encoding = "utf-8", errors = "ignore")) failed

Using Python 3.4.3 on Windows.

My script runs a small java program in the console and should get the output:

import subprocess
p1 = subprocess.Popen([ ... ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True)
out, err = p1.communicate(str.encode("utf-8"))

This leads to normal

'UnicodeDecodeError: codec' charmap 'cannot decode byte 0x9d at position 135: character cards in <undefined> ".

Now I want to ignore the errors:

out, err = p1.communicate(str.encode(encoding="utf-8", errors="ignore"))

This leads to a more interesting error. I did not find any help using google:

TypeError: descriptor 'encode' of object 'str' needs an argument

So it seems that python doesn't even know what the arguments are for str.encode (...). The same applies to the fact that you do not account for some of the errors.

+4
2

universal_newlines=True . stdout=PIPE locale.getpreferredencoding(False), utf-8 Windows. UnicodeDecodeError.

utf-8, universal_newlines=True:

#!/usr/bin/env python3
from subprocess import Popen, PIPE

with Popen(r'C:\path\to\program.exe "arg 1" "arg 2"',
           stdout=PIPE, stderr=PIPE) as p:
    output, errors = p.communicate()
lines = output.decode('utf-8').splitlines()

str.encode("utf-8") "utf-8".encode(). .communicate(), stdin=PIPE, b'utf-8' bytestring .

str.encode(encoding="utf-8", errors="ignore) klass.method(**kwargs). .encode() self ( ), TypeError.

>>> str.encode("abc", encoding="utf-8", errors="ignore") #XXX don't do it
b'abc'
>>> "abc".encode(encoding="utf-8", errors="ignore")
b'abc'

klass.method(obj) obj.method() .

+7

.encode() . , , , , -

p1.communicate("FOOBAR".encode("utf-8"))

, , , encode() , , ( self encode()).

+2

Source: https://habr.com/ru/post/1612774/


All Articles