The return result of the terminal command cannot be decoded normally

69 Views Asked by At

I wrote the following command to get the list of available WIFIs:

result = subprocess.run("netsh wlan show network",
                            shell=True, stdout=subprocess.PIPE, 
                            text=True, encoding="gbk")

This code has been run many times before and worked fine, but on this run the following error occurred:

Traceback (most recent call last):
  File "c:\Users\Administrator\Desktop\login_jxnu\auto_connect\utils.py", line 13, in get_wifi_list
    result = subprocess.run("netsh wlan show network",
  File "D:\development\anaconda\envs\deep-todo\lib\subprocess.py", line 507, in run
    stdout, stderr = process.communicate(input, timeout=timeout)
  File "D:\development\anaconda\envs\deep-todo\lib\subprocess.py", line 1121, in communicate
    stdout = self.stdout.read()
UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position 3918: illegal multibyte sequence

If I change to utf-8 encoding, I get an error like this:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbd in position 3: invalid start byte

Why did this code work but suddenly failed, and is there any way to avoid this error?

I used the "chcp" command to see how the system is encoded:

res = subprocess.run("chcp", shell=True, stdout=subprocess.PIPE, text=True)

The result returned is: 活动代码页: 936\n, which corresponds to the gbk encoding.

The operating system I use is Windows 11 and the python version is 3.9.


Now, when I change gbk to utf-8, the program can run normally. I executed the following code and the output is display in comment:

res = subprocess.run("chcp", shell=True, stdout=subprocess.PIPE, text=True)
print(res.stdout)  # output:  Active code page: 65001

res = subprocess.run("chcp", shell=True, stdout=subprocess.PIPE, text=True, encoding='utf-8')
print(res.stdout)  # output:   Active code page: 65001

res = subprocess.run("chcp", shell=True, stdout=subprocess.PIPE, text=True, encoding='gbk')
print(res.stdout)  # output:  Active code page: 65001

result = subprocess.run("netsh wlan show network",
                            shell=True, stdout=subprocess.PIPE, 
                            text=True)
## error occurred
Traceback (most recent call last):
  File "c:\Users\Administrator\Desktop\login_jxnu\try.py", line 4, in <module>
    result = subprocess.run("netsh wlan show network",
  File "D:\development\anaconda\envs\deep-todo\lib\subprocess.py", line 507, in run
    stdout, stderr = process.communicate(input, timeout=timeout)
  File "D:\development\anaconda\envs\deep-todo\lib\subprocess.py", line 1121, in communicate
    stdout = self.stdout.read()
UnicodeDecodeError: 'gbk' codec can't decode byte 0xb5 in position 229: illegal multibyte sequence

# omit text=True
res = subprocess.run("chcp", shell=True, stdout=subprocess.PIPE)
print(res.stdout)  # output:  b'Active code page: 65001\r\n'
0

There are 0 best solutions below