|
6 | 6 |
|
7 | 7 | from distutils.sysconfig import get_python_lib |
8 | 8 | from os.path import abspath, join |
9 | | -from termcolor import cprint |
10 | | -from traceback import extract_tb, format_list, format_exception_only |
11 | | - |
12 | | - |
13 | | -def excepthook(type, value, tb): |
14 | | - """ |
15 | | - Format traceback, darkening entries from global site-packages directories |
16 | | - and user-specific site-packages directory. |
17 | | -
|
18 | | - https://stackoverflow.com/a/46071447/5156190 |
19 | | - """ |
20 | | - packages = tuple(join(abspath(p), "") for p in sys.path[1:]) |
21 | | - for entry in extract_tb(tb): |
22 | | - fmt = format_list((entry,)) |
23 | | - if (entry[0].startswith(packages)): |
24 | | - cprint("".join(fmt), attrs=["dark"], end="", file=sys.stderr) |
25 | | - else: |
26 | | - cprint("".join(fmt), end="", file=sys.stderr) |
27 | | - cprint("".join(format_exception_only(type, value)), end="") |
28 | | - |
29 | | - |
30 | | -sys.excepthook = excepthook |
| 9 | +from termcolor import colored |
| 10 | +from traceback import extract_tb, format_list, format_exception_only, format_exception |
31 | 11 |
|
32 | 12 |
|
33 | 13 | class flushfile(): |
@@ -64,6 +44,31 @@ def eprint(*args, **kwargs): |
64 | 44 | print(*args, end=end, file=sys.stderr, sep=sep) |
65 | 45 |
|
66 | 46 |
|
| 47 | +def formatException(type, value, tb): |
| 48 | + """ |
| 49 | + Format traceback, darkening entries from global site-packages directories |
| 50 | + and user-specific site-packages directory. |
| 51 | +
|
| 52 | + https://stackoverflow.com/a/46071447/5156190 |
| 53 | + """ |
| 54 | + |
| 55 | + # Absolute paths to site-packages |
| 56 | + packages = tuple(join(abspath(p), "") for p in sys.path[1:]) |
| 57 | + |
| 58 | + # Darken lines referring to files in site-packages |
| 59 | + lines = [] |
| 60 | + for line in format_exception(type, value, tb): |
| 61 | + matches = re.search(r"^ File \"([^\"]+)\", line \d+, in .+", line) |
| 62 | + if matches and matches.group(1).startswith(packages): |
| 63 | + lines += colored(line, attrs=["dark"]) |
| 64 | + else: |
| 65 | + lines += line |
| 66 | + return "".join(lines).rstrip() |
| 67 | + |
| 68 | + |
| 69 | +sys.excepthook = lambda type, value, tb: print(formatException(type, value, tb), file=sys.stderr) |
| 70 | + |
| 71 | + |
67 | 72 | def get_char(prompt=None): |
68 | 73 | """ |
69 | 74 | Read a line of text from standard input and return the equivalent char; |
|
0 commit comments