在终端启动Python时报错的解决方案
最近,在终端启动Python时,报了一个错误:
Failedcallingsys.__interactivehook__ Traceback(mostrecentcalllast): File"d:\ProgramData\Anaconda3\lib\site.py",line439,inregister_readline readline.read_history_file(history) File"d:\ProgramData\Anaconda3\lib\site-packages\pyreadline\rlmain.py",line165,inread_history_file self.mode._history.read_history_file(filename) File"d:\ProgramData\Anaconda3\lib\site-packages\pyreadline\lineeditor\history.py",line82,inread_history_file forlineinopen(filename,'r'): UnicodeDecodeError:'gbk'codeccan'tdecodebyte0xa7inposition2167:illegalmultibytesequence
原因是Python的终端历史文件中包含中文,但不能正确使用gbk解码。查看了Python历史文件(系统用户目录下的.python_history),其编码方式为“utf-8”,而”history.py”中读取历史文件时使用的编码方式为“gbk”,所以会报错。
解决方法
在history.py中使用`forlineinopen(filename,'r')`来打开文件并读取每一行,使用的是默认的编码方式。需要根据不同文件的编码方式传入相应的参数值。
1.首先检测出要打开的文件的编码方式。
在类中定义一个私有方法_get_encoding,作用是检测文件的编码方式,并返回。(需要导入chardet包)
def_get_encoding(self,filename=None): iffilenameisNone: return withopen(filename,'rb')asf: returnchardet.detect(f.read())['encoding']
2.修改历史文件内容的读取
encoding=self._get_encoding(filename) forlineinopen(filename,'r',encoding=encoding): self.add_history(lineobj.ReadLineTextBuff(ensure_unicode(line.rstrip())))
以上就是在终端启动Python时报错的解决方案的详细内容,更多关于终端启动python报错的资料请关注毛票票其它相关文章!
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下