Python os.popen() can allow us to call other applications by command line (cmd), this function also can return the output of cmd. However, you may find this error when reading the output: UnicodeDecodeError: ‘gbk’ codec can’t decode byte. In this tutorial, we will introduce you how to fix it.
As we know, os.popen() will return a os._wrap_close object, we can read its output by read() function.
Here is an example:
result = os.popen(cmd) msg = result.read() print(msg)
However, the data type of msg is string. When you are use result.read(), it will occur UnicodeDecodeError: ‘gbk’ codec can’t decode byte and you can not read content by btye mode like reading file.
How to fix this error?
The best solution is to use subprocess.Popen() to get the output of cmd, it will return a byte object. We can conver it to string with encoding.
Here is the tutorial.