Python控制台错误输出异常:无法定位错误行,求解决方法
问题
之前开发Python程序时,报错会直接定位到代码错误行,示例如下:
Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\python_files\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\python_files\venv\lib\site-packages\channels\management\commands\runserver.py", line 75, in inner_run self.check(display_num_errors=True) File "C:\python_files\venv\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\python_files\venv\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\python_files\venv\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\python_files\venv\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\python_files\venv\lib\site-packages\django\urls\resolvers.py", line 408, in check for pattern in self.url_patterns: File "C:\python_files\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\python_files\venv\lib\site-packages\django\urls\resolvers.py", line 589, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\python_files\venv\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\python_files\venv\lib\site-packages\django\urls\resolvers.py", line 582, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\python_files\hospital_project\urls.py", line 61, in <module> url('residence/', include('hospital_project.residence.urls', namespace="residence")),#dashboard for residence File "C:\python_files\venv\lib\site-packages\django\urls\conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\python_files\hospital_project\residence\urls.py", line 36, in <module> url(r'pharmacy1', views.pharmacy1, name="pharmacy"), AttributeError: module 'hospital_project.residence.views' has no attribute 'pharmacy1'
但最近错误输出异常,不再显示具体错误行,而是打印Python文件全部代码,示例如下:
--- Logging error --- Traceback (most recent call last): File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\logging\__init__.py", line 1081, in emit msg = self.format(record) File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\logging\__init__.py", line 925, in format return fmt.format(record) File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\logging\__init__.py", line 672, in format record.exc_text = self.formatException(record.exc_info) File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\logging\__init__.py", line 622, in formatException traceback.print_exception(ei[0], ei[1], tb, None, sio) File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\traceback.py", line 103, in print_exception for line in TracebackException( File "C:\software_development\python\venv\lib\site-packages\trio\_core\_multierror.py", line 393, in traceback_exception_init traceback_exception_original_init( File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\traceback.py", line 523, in __init__ self._load_lines() File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\traceback.py", line 535, in _load_lines self.__context__._load_lines() File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\traceback.py", line 535, in _load_lines self.__context__._load_lines() File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\traceback.py", line 535, in _load_lines self.__context__._load_lines() [Previous line repeated 6 more times] File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\traceback.py", line 533, in _load_lines frame.line File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\traceback.py", line 288, in line self._line = linecache.getline(self.filename, self.lineno).strip() File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\linecache.py", line 16, in getline lines = getlines(filename, module_globals) File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\linecache.py", line 47, in getlines return updatecache(filename, module_globals) File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\linecache.py", line 137, in updatecache lines = fp.readlines() File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\codecs.py", line 322, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0x96 in position 6781: invalid start byte Call stack: File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\threading.py", line 890, in _bootstrap self._bootstrap_inner() File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\software_development\python\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\software_development\python\venv\lib\site-packages\channels\management\commands\runserver.py", line 106, in inner_run self.server_cls( File "C:\software_development\python\venv\lib\site-packages\daphne\server.py", line 143, in run reactor.run(installSignalHandlers=self.signal_handlers) File "C:\software_development\python\venv\lib\site-packages\twisted\internet\asyncioreactor.py", line 255, in run self._asyncioEventloop.run_forever() File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 570, in run_forever self._run_once() File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 1859, in _run_once handle._run() File "C:\Users\software_developer\AppData\Local\Programs\Python\Python38\lib\asyncio\events.py", line 81, in _run self._context.run(self._callback, *self._args) File "C:\software_development\python\venv\lib\site-packages\twisted\internet\asyncioreactor.py", line 271, in _onTimer self.runUntilCurrent() File "C:\software_development\python\venv\lib\site-packages\twisted\internet\base.py", line 991, in runUntilCurrent call.func(*call.args, **call.kw) File "C:\software_development\python\venv\lib\site-packages\daphne\server.py", line 290, in application_checker logger.error( Message: 'Exception inside application: %s' Arguments: (UnicodeDecodeError('utf-8', b'import re\r\nfrom django.db.models import Count, Avg\r\nfrom django.shortcuts import render, redirect\r\nfrom django.http import HttpResponse, HttpResponseRedirect, StreamingHttpResponse\r\n\r\nfrom django.urls import reverse...................the rest of the output are just my code with \r \n \t included allover
请问该异常是什么原因导致的?如何恢复正常的错误输出?
原因分析
核心原因是Python的linecache模块读取代码文件时遇到了非UTF-8编码的字符,具体是位置6781处的0x96字节(通常是Windows-1252编码的长破折号),导致解码失败。
当程序抛出异常后,日志系统尝试格式化回溯信息,需要调用linecache.getline读取错误行的代码,但因为文件编码不兼容,触发了UnicodeDecodeError。这个错误又干扰了正常的回溯格式化流程,最终导致日志系统无法定位错误行,转而把整个文件的原始字节内容打印出来。
另外,trio库的multierror模块对回溯处理的包装,可能加剧了这个问题的连锁反应,但根源还是代码文件的编码问题。
解决方法
1. 定位并修复编码异常字符
- 根据错误提示的
position 6781,找到对应的Python文件,用支持显示字符编码的编辑器(如VS Code、Notepad++)打开。 - 在VS Code中,可开启"显示控制字符"(快捷键
Ctrl+Shift+P,输入"Toggle Control Characters"),定位到6781附近的字符,找到0x96对应的特殊符号,替换为普通ASCII破折号-。
2. 转换文件为UTF-8编码
- 确保所有代码文件都以UTF-8编码保存:
- VS Code右下角点击当前编码(如"GB2312"),选择"通过编码保存",然后选择"UTF-8"。
- Notepad++中,依次点击"编码" -> "转为UTF-8编码"。
3. 清除linecache缓存
- 如果是缓存导致旧的编码文件残留,可重启Python进程,或者在代码中临时添加:
强制刷新文件缓存。import linecache linecache.clearcache()
4. 临时应急方案(不推荐长期使用)
如果需要快速恢复错误输出,可修改logging的异常格式化逻辑,忽略编码错误:
import logging import traceback import sys class SafeFormatter(logging.Formatter): def formatException(self, exc_info): try: return super().formatException(exc_info) except UnicodeDecodeError: return f"[无法格式化异常: 编码错误] {exc_info[1]}" # 应用到根日志器 for handler in logging.root.handlers: handler.setFormatter(SafeFormatter(handler.formatter._fmt))
内容的提问来源于stack exchange,提问作者jarhead
相关产品推荐
相关产品推荐

