S
S
S0ulReaver2022-02-05 02:01:50
Python
S0ulReaver, 2022-02-05 02:01:50

Windows console, Python and encodings - how does it work?

I noticed that subprocess.getoutput('ping ya.ru') returns krakozyabry instead of Russian text. I went to figure out what encoding the console is working in, the console says that it is cp866. Okay, in principle, if you use subprocess.check_output('ping ya.ru'), then I will get a response in bytes that can be represented as normal text using decode("cp866").

And now it seems that the problem is no more, but curiosity does not let go, I wanted to get a normal result from subprocess.getoutput. Googled a recipe in which the resulting string is first encoded in CP1251 and then decoded in CP866.

subprocess.getoutput('ping ya.ru').encode('cp1251').decode('cp866')

But now I don't understand why this recipe works. Why is this intermediate encode needed in CP1251? It seems to us that the cp866 console returned. I understand that before decode, you need to somehow translate the string from the response into bytes, but why doesn't encode('cp866').decode('cp866') work then?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andy_U, 2022-02-05
@Andy_U

As far as I remember, there is a difference if you output directly to the (interactive) console or redirect to a file or to PIPE (then ANSI). At least for Python itself. Here is a little...

B
belotooth, 2022-02-06
@belotooth

The docs say that this is a legacy function, maybe you shouldn't use it anymore.
This is how it works normally:

subprocess.check_output('ping ya.ru', encoding='cp866')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question