0

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 :)

  • with other cmd commands like "dir" it works, but commands starting with the letter "p", like "pause" or "ping", lead to this error – geisterhose May 12 '22 at 15:38
  • The real solution here is to set the encoding correctly on the stream. You're getting this error because you're trying to print to a CP1252 terminal, and Python is automatically detecting that. Set your stream encoding to utf-8 and things should work fine. Sometimes, Python is trying to be too smart! – joanis May 12 '22 at 19:34
  • You could also try using `subprocess.run` which provides a very nice low level API for this kinda of stuff: https://docs.python.org/3/library/subprocess.html#subprocess.run – Tzane May 13 '22 at 06:29

2 Answers2

0

try to add

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

at the top of the file

cesebe27
  • 305
  • 1
  • 10
  • still getting the same error – geisterhose May 12 '22 at 14:45
  • The magic encoding comment only affects strings in your Python source code, not anything coming from outside. – Mark Ransom May 12 '22 at 14:51
  • are python versions different? – cesebe27 May 12 '22 at 14:52
  • python 3.10.4 is installed on both machines – geisterhose May 12 '22 at 15:21
  • 1
    Please explain why you think this would help the OP. `# -*- coding: utf-8 -*-` [declares the decoding of the source file](https://stackoverflow.com/a/4872242/1707427), not the encoding `os.popen()` uses. And in python 3 the [default is utf8](https://stackoverflow.com/a/58652741/1707427) anyway, so there is no point in using `# -*- coding: utf-8 -*-`. – Sören May 12 '22 at 15:22
0

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
  • An easier workaround would be to get it to use `latin-1` instead of `cp1252`. But that doesn't explain where the 0x81 is coming from. – Mark Ransom May 12 '22 at 18:41