怎么在终端启用python_在终端启动Python时报错的解决方案
最近,在終端啟動Python時,報了一個錯誤:
Failed calling sys.__interactivehook__
Traceback (most recent call last):
File "d:\ProgramData\Anaconda3\lib\site.py", line 439, in register_readline
readline.read_history_file(history)
File "d:\ProgramData\Anaconda3\lib\site-packages\pyreadline\rlmain.py", line 165, in read_history_file
self.mode._history.read_history_file(filename)
File "d:\ProgramData\Anaconda3\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 0xa7 in position 2167: illegal multibyte sequence
原因是Python的終端歷史文件中包含中文,但不能正確使用gbk解碼。查看了Python歷史文件(系統用戶目錄下的.python_history),其編碼方式為“utf-8”,而”history.py”中讀取歷史文件時使用的編碼方式為“gbk”,所以會報錯。
解決方法
在history.py中使用`for line in open(filename, 'r')`來打開文件并讀取每一行,使用的是默認的編碼方式。需要根據不同文件的編碼方式傳入相應的參數值。
1. 首先檢測出要打開的文件的編碼方式。
在類中定義一個私有方法_get_encoding,作用是檢測文件的編碼方式,并返回。(需要導入chardet包)
def _get_encoding(self, filename=None):
if filename is None:
return
with open(filename, 'rb') as f:
return chardet.detect(f.read())['encoding']
2. 修改歷史文件內容的讀取
encoding = self._get_encoding(filename)
for line in open(filename, 'r', encoding=encoding):
self.add_history(lineobj.ReadLineTextBuff(ensure_unicode(line.rstrip())))
以上就是在終端啟動Python時報錯的解決方案的詳細內容,更多關于終端啟動python報錯的資料請關注腳本之家其它相關文章!
總結
以上是生活随笔為你收集整理的怎么在终端启用python_在终端启动Python时报错的解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: asp向不同的用户发送信息_【asp.n
- 下一篇: python语言的编程模式_一种基于Py