解决UnicodeDecodeError: ‘gbk‘ codec can‘t decode byte 0x8c in position : illegal multibyte sequence

  • 问题描述:在命令行输入python并回车时,会进入python交互式环境,但是有的时候会出现如下的错误
    (speaker_recognition) PS D:\> python.exe
    Python 3.7.16 (default, Jan 17 2023, 16:06:28) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
    Type "help", "copyright", "credits" or "license" for more information.
    Failed calling sys.__interactivehook__
    Traceback (most recent call last):
      File "C:\Users\dedsec\miniconda3\envs\speaker_recognition\lib\site.py", line 439, in register_readline
        readline.read_history_file(history)
      File "C:\Users\dedsec\miniconda3\envs\speaker_recognition\lib\site-packages\pyreadline\rlmain.py", line 165, in read_history_file
        self.mode._history.read_history_file(filename)
      File "C:\Users\dedsec\miniconda3\envs\speaker_recognition\lib\site-packages\pyreadline\lineeditor\history.py", line 82, in read_history_file
        for line in open(filename, 'r'):
    UnicodeDecodeError: 'gbk' codec can't decode byte 0x9c in position 2: illegal multibyte sequence
    >>>
    
  • 错误原因:python会把在我们在交互式环境下输入的命令,都保存到C:\Users\dedsec\.python_history文件下(可以用命令os.path.expanduser('~/.history')获取该文件路径),每次启动交互式环境就会读取这个文件,使我们能调用历史命令,不过如果输入了中文,则会出现无法读取的问题
  • 解决方案:如果不想修改源代码中for line in open(filename, 'r'):的编码格式,可以用记事本打开C:\Users\dedsec\.python_history文件,然后把内容清空,问题解决

你可能感兴趣的:(python,python,开发语言)