1
- import imp
2
1
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
3
6
4
7
from .cs50 import *
5
8
9
+
6
10
class CustomImporter (object ):
7
11
"""
8
12
Import cs50.SQL lazily so that rest of library can be used without SQLAlchemy installed.
@@ -11,14 +15,37 @@ class CustomImporter(object):
11
15
http://xion.org.pl/2012/05/06/hacking-python-imports/
12
16
http://dangerontheranger.blogspot.com/2012/07/how-to-use-sysmetapath-with-python.html
13
17
"""
18
+
14
19
def find_module (self , fullname , path = None ):
15
20
if fullname == "cs50.SQL" :
16
21
return self
17
22
return None
23
+
18
24
def load_module (self , name ):
19
25
if name in sys .modules :
20
26
return sys .modules [name ]
21
27
from .sql import SQL
22
28
sys .modules [name ] = SQL
23
29
return SQL
30
+
31
+
24
32
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
0 commit comments