MCPcopy Create free account
hub / github.com/Python-Markdown/markdown / py_render

Function py_render

tools/superfences_formaters.py:147–179  ·  view source on GitHub ↗

Render Python in a code block and output of the code in a result code block.

(src="", language="", class_name=None, options=None, md="", **kwargs)

Source from the content-addressed store, hash-verified

145
146
147def py_render(src="", language="", class_name=None, options=None, md="", **kwargs):
148 """ Render Python in a code block and output of the code in a result code block. """
149
150 if not hasattr(md, 'py_namespace'):
151 # This is the first instance of a Python render block on the page.
152 # Create namespace for this and all future blocks to run in.
153 md.py_namespace = PyExecNamespace()
154 target, result = md.py_namespace.exec(src)
155
156 # Retreive and remove output language from attrs
157 output_lang = kwargs['attrs'].pop('output-lang', '')
158
159 options = options or {}
160 if 'title' not in options:
161 options['title'] = 'Python'
162
163 source = md.preprocessors['fenced_code_block'].highlight(src, 'python', options, md, **kwargs)
164
165 if result is not None:
166 result_options = options.copy()
167 if target == 'traceback':
168 result_options['title'] = 'Error Raised'
169 output_lang = 'py3tb' # PythonTracebackLexer
170 elif target == 'stdout':
171 result_options['title'] = 'Text Written to STDOUT'
172 elif target is not None:
173 # Store title in stash to avoid it being escaped by Pygments.
174 result_options['title'] = md.htmlStash.store(f'Value of <code>{code_escape(target)}</code>')
175
176 output = md.preprocessors['fenced_code_block'].highlight(result, output_lang, result_options, md, **kwargs)
177 return f'{source}\n<div class="result">{output}</div>'
178 # No result so only render source
179 return source

Callers

nothing calls this directly

Calls 4

code_escapeFunction · 0.90
PyExecNamespaceClass · 0.85
execMethod · 0.80
storeMethod · 0.80

Tested by

no test coverage detected