Fix Python os.popen(cmd).read() UnicodeDecodeError: ‘gbk’ codec can’t decode byte

By | April 30, 2020

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 =

However, the data type of msg is string. When you are use, 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.

Implement Python subprocess.Popen(): Execute an External Command and Get Output

Leave a Reply

Your email address will not be published. Required fields are marked *