Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit c2eb5e5

Browse files
committedOct 29, 2017
grays out site packages in tracebacks
1 parent 0c455f6 commit c2eb5e5

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed
 

‎src/cs50/__init__.py

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
1-
import imp
21
import sys
2+
from os.path import abspath, join
3+
from site import getsitepackages, getusersitepackages
4+
from termcolor import cprint
5+
from traceback import extract_tb, format_list, format_exception_only
36

47
from .cs50 import *
58

9+
610
class CustomImporter(object):
711
"""
812
Import cs50.SQL lazily so that rest of library can be used without SQLAlchemy installed.
@@ -11,14 +15,37 @@ class CustomImporter(object):
1115
http://xion.org.pl/2012/05/06/hacking-python-imports/
1216
http://dangerontheranger.blogspot.com/2012/07/how-to-use-sysmetapath-with-python.html
1317
"""
18+
1419
def find_module(self, fullname, path=None):
1520
if fullname == "cs50.SQL":
1621
return self
1722
return None
23+
1824
def load_module(self, name):
1925
if name in sys.modules:
2026
return sys.modules[name]
2127
from .sql import SQL
2228
sys.modules[name] = SQL
2329
return SQL
30+
31+
2432
sys.meta_path.append(CustomImporter())
33+
34+
35+
def excepthook(type, value, tb):
36+
"""
37+
Format traceback, darkening entries from global site-packages and user-specific site-packages directory.
38+
39+
https://stackoverflow.com/a/33042323/5156190
40+
"""
41+
packages = tuple(join(abspath(p), "") for p in getsitepackages() + [getusersitepackages()])
42+
for entry in extract_tb(tb):
43+
fmt = format_list((entry,))
44+
if (entry.filename.startswith(packages)):
45+
cprint("".join(fmt), attrs=["dark"], end="", file=sys.stderr)
46+
else:
47+
cprint("".join(fmt), end="", file=sys.stderr)
48+
cprint("".join(format_exception_only(type, value)), end="")
49+
50+
51+
sys.excepthook = excepthook

‎tests/tb.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import cs50
2+
import requests
3+
4+
def f():
5+
res = requests.get("cs50.harvard.edu")
6+
f()

0 commit comments

Comments
 (0)
Please sign in to comment.