Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

grays out site packages in tracebacks #33

Merged
merged 13 commits into from
Nov 1, 2017
29 changes: 28 additions & 1 deletion src/cs50/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import imp
import sys
from os.path import abspath, join
from site import getsitepackages, getusersitepackages
from termcolor import cprint
from traceback import extract_tb, format_list, format_exception_only

from .cs50 import *


class CustomImporter(object):
"""
Import cs50.SQL lazily so that rest of library can be used without SQLAlchemy installed.
@@ -11,14 +15,37 @@ class CustomImporter(object):
http://xion.org.pl/2012/05/06/hacking-python-imports/
http://dangerontheranger.blogspot.com/2012/07/how-to-use-sysmetapath-with-python.html
"""

def find_module(self, fullname, path=None):
if fullname == "cs50.SQL":
return self
return None

def load_module(self, name):
if name in sys.modules:
return sys.modules[name]
from .sql import SQL
sys.modules[name] = SQL
return SQL


sys.meta_path.append(CustomImporter())


def excepthook(type, value, tb):
"""
Format traceback, darkening entries from global site-packages and user-specific site-packages directory.
https://stackoverflow.com/a/33042323/5156190
"""
packages = tuple(join(abspath(p), "") for p in getsitepackages() + [getusersitepackages()])
for entry in extract_tb(tb):
fmt = format_list((entry,))
if (entry.filename.startswith(packages)):
cprint("".join(fmt), attrs=["dark"], end="", file=sys.stderr)
else:
cprint("".join(fmt), end="", file=sys.stderr)
cprint("".join(format_exception_only(type, value)), end="")


sys.excepthook = excepthook
6 changes: 6 additions & 0 deletions tests/tb.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import cs50
import requests

def f():
res = requests.get("cs50.harvard.edu")
f()