温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python无法在终端启动怎么解决

发布时间:2020-11-21 14:57:10 来源:亿速云 阅读:415 作者:Leah 栏目:开发技术

本篇文章为大家展示了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无法在终端启动怎么解决,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI