'Why do I get a UnicodeDecodeError after reading my ping with Python?

to make my job easier, i am currently working on a network tool script to find out which switches are online/offline on my network using python. i have this short code:

import os

ping = os.popen("ping 9.9.9.9").read()
print(ping)

input("close")

at home this code runs fine, but when I run this code on my work VM I get this error:

Traceback (most recent call last):
  File "c:\Users\..\Documents\network_tool.py", line 3, in <module>
    ping = os.popen("ping 9.9.9.9").read()
  File "C:\Users\..\AppData\Local\Programs\Python\Python310\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 18: character maps to <undifed_>

thanks for the help in advance :)



Solution 1:[1]

try to add

# -*- coding: utf-8 -*-

at the top of the file

Solution 2:[2]

ok, i found a workarount now. to do this you have to change line 177, in the file "..\Python310\lib\encodings\cp1252.py".

from this:

'\ufffe'   #  0x81 -> UNDEFINED

to this

'p'   #  0x81 -> UNDEFINED

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 cesebe27
Solution 2 geisterhose