feat: colored tracebacks during interactive use (#4683)

* feat: colored tracebacks

* fix pygments import, remove promt_toolkit restriction

Co-authored-by: Alexander Firbas <alexander.firbas@gmail.com>
This commit is contained in:
dev2718 2022-02-26 18:20:52 +01:00 committed by GitHub
parent 0ba5bec86f
commit d6588885ab
Failed to generate hash of commit
2 changed files with 42 additions and 1 deletions

View file

@ -0,0 +1,23 @@
**Added:**
* Tracebacks are now printed in color if available (interactive session with shell that supports colors with pygments installed and $COLOR_RESULTS enabled)
**Changed:**
* <news item>
**Deprecated:**
* <news item>
**Removed:**
* <news item>
**Fixed:**
* <news item>
**Security:**
* <news item>

View file

@ -44,6 +44,7 @@ from xonsh import __version__
from xonsh.lazyasd import LazyDict, LazyObject, lazyobject
from xonsh.platform import (
DEFAULT_ENCODING,
HAS_PYGMENTS,
ON_LINUX,
ON_WINDOWS,
expanduser,
@ -1032,7 +1033,24 @@ def print_exception(msg=None, exc_info=None):
"xonsh: To log full traceback to a file set: "
"$XONSH_TRACEBACK_LOGFILE = <filename>\n"
)
traceback.print_exception(*exc_info, limit=limit, chain=chain)
traceback_str = "".join(
traceback.format_exception(*exc_info, limit=limit, chain=chain)
)
# color the traceback if available
_, interactive = _get_manual_env_var("XONSH_INTERACTIVE", 0)
_, color_results = _get_manual_env_var("COLOR_RESULTS", 0)
if interactive and color_results and HAS_PYGMENTS:
import pygments.lexers.python
lexer = pygments.lexers.python.PythonTracebackLexer()
tokens = list(pygments.lex(traceback_str, lexer=lexer))
# this goes to stdout, but since we are interactive it doesn't matter
print_color(tokens, end="")
else:
print(traceback_str, file=sys.stderr, end="")
# additionally, check if a file for traceback logging has been
# specified and convert to a proper option if needed
log_file = to_logfile_opt(log_file)