18 from pygments.formatters._mapping import FORMATTERS |
18 from pygments.formatters._mapping import FORMATTERS |
19 from pygments.plugin import find_plugin_formatters |
19 from pygments.plugin import find_plugin_formatters |
20 from pygments.util import ClassNotFound, itervalues |
20 from pygments.util import ClassNotFound, itervalues |
21 |
21 |
22 __all__ = ['get_formatter_by_name', 'get_formatter_for_filename', |
22 __all__ = ['get_formatter_by_name', 'get_formatter_for_filename', |
23 'get_all_formatters'] + list(FORMATTERS) |
23 'get_all_formatters', 'load_formatter_from_file'] + list(FORMATTERS) |
24 |
24 |
25 _formatter_cache = {} # classes by name |
25 _formatter_cache = {} # classes by name |
26 _pattern_cache = {} |
26 _pattern_cache = {} |
27 |
27 |
28 |
28 |
77 if cls is None: |
77 if cls is None: |
78 raise ClassNotFound("no formatter found for name %r" % _alias) |
78 raise ClassNotFound("no formatter found for name %r" % _alias) |
79 return cls(**options) |
79 return cls(**options) |
80 |
80 |
81 |
81 |
|
82 def load_formatter_from_file(filename, formattername="CustomFormatter", |
|
83 **options): |
|
84 """Load a formatter from a file. |
|
85 |
|
86 This method expects a file located relative to the current working |
|
87 directory, which contains a class named CustomFormatter. By default, |
|
88 it expects the Formatter to be named CustomFormatter; you can specify |
|
89 your own class name as the second argument to this function. |
|
90 |
|
91 Users should be very careful with the input, because this method |
|
92 is equivalent to running eval on the input file. |
|
93 |
|
94 Raises ClassNotFound if there are any problems importing the Formatter. |
|
95 |
|
96 .. versionadded:: 2.2 |
|
97 """ |
|
98 try: |
|
99 # This empty dict will contain the namespace for the exec'd file |
|
100 custom_namespace = {} |
|
101 exec(open(filename, 'rb').read(), custom_namespace) |
|
102 # Retrieve the class `formattername` from that namespace |
|
103 if formattername not in custom_namespace: |
|
104 raise ClassNotFound('no valid %s class found in %s' % |
|
105 (formattername, filename)) |
|
106 formatter_class = custom_namespace[formattername] |
|
107 # And finally instantiate it with the options |
|
108 return formatter_class(**options) |
|
109 except IOError as err: |
|
110 raise ClassNotFound('cannot read %s' % filename) |
|
111 except ClassNotFound as err: |
|
112 raise |
|
113 except Exception as err: |
|
114 raise ClassNotFound('error when loading custom formatter: %s' % err) |
|
115 |
|
116 |
82 def get_formatter_for_filename(fn, **options): |
117 def get_formatter_for_filename(fn, **options): |
83 """Lookup and instantiate a formatter by filename pattern. |
118 """Lookup and instantiate a formatter by filename pattern. |
84 |
119 |
85 Raises ClassNotFound if not found. |
120 Raises ClassNotFound if not found. |
86 """ |
121 """ |