Search code examples
pythonwindowspython-3.xwindows-console

How to deal with cp932 encoding error trying to print the filename by file list


I am working on a script that randomly chooses a file and asks the user whether to execute it. I recently got the error shown below, and I'm confused about how to change my script to fix this.

Traceback (most recent call last):
File ".\randomplay.py", line 33, in <module>
    print(file)
UnicodeEncodeError: 'cp932' codec can't encode character '\u8138' in position 1: illegal multibyte sequence

The code below works in Python 2.x. However, I'm required to implement this function in Python 3.x. Can anyone advise me how to do it? I want to make it work the same as before.

import sys
import os,io
import random
import subprocess
import msvcrt

if __name__ == '__main__':
    indir = os.path.realpath("./")
    for root, dirs, files in os.walk(indir):
        random.shuffle(files)
        #print(files)
        for file in files:
            cmd="\""+file+"\""
            print(file)
            print("OK with it?")
            c = msvcrt.getch()
            print(str(ord(c)))
            if ord(c) == 27:
                exit()
            elif ord(c) == 13:
                print("executing...")
                subprocess.Popen(cmd,shell=True)
                exit()
            else:
                print("How about this?")
                pass

Solution

  • By @eryksun

    By upgrading python to 3.6.X seems to be the most fast way to deal with this problem without change any script! Now it works!

    Thanks!