{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# IPython 渲染" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import IPython\n", "\n", "def code2html(code):\n", " \"\"\"Helper function to use pygments to turn the code string into highlighted html.\"\"\"\n", " import pygments\n", " from pygments.lexers import Python3Lexer\n", " from pygments.formatters import HtmlFormatter\n", " formatter = HtmlFormatter()\n", " html = pygments.highlight(code, Python3Lexer(), formatter)\n", " return \"%s\\n\" % (formatter.get_style_defs(\".highlight\"), html)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "code = \"\"\"\n", "a = 1\n", "b = 2\n", "c = a * b\n", "d << 3\n", "\"\"\"" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
a = 1\n",
       "b = 2\n",
       "c = a * b\n",
       "d << 3\n",
       "
\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "IPython.display.HTML(code2html(code))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3.8.13 64-bit", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.13" }, "orig_nbformat": 4, "vscode": { "interpreter": { "hash": "949777d72b0d2535278d3dc13498b2535136f6dfe0678499012e853ee9abcab1" } } }, "nbformat": 4, "nbformat_minor": 2 }