HtmlFormatterのanchorlinenosオプションの例
初回公開:2018/10/14
最終更新:未
サンプルコード
from pygments import highlight from pygments.lexers import get_lexer_by_name from pygments.formatters import HtmlFormatter code=u""" class SuperCls(object): def method(self, arg): print("スーパクラスのメソッドを実行, arg=",arg) class SubCls(SuperCls): def method(self): print ("サブクラスのメソッドを実行") super().method("arg") sub_inst=SubCls() sub_inst.method() """ lexer = get_lexer_by_name("python") with open("anchorlinenos.html", 'w') as outfile: highlight(code, lexer, HtmlFormatter(anchorlinenos=True,linenos=True),outfile)
実行結果
anchorlinenos.html
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><a href="#-1"> 1</a> <a href="#-2"> 2</a> <a href="#-3"> 3</a> <a href="#-4"> 4</a> <a href="#-5"> 5</a> <a href="#-6"> 6</a> <a href="#-7"> 7</a> <a href="#-8"> 8</a> <a href="#-9"> 9</a> <a href="#-10">10</a> <a href="#-11">11</a></pre></div></td><td class="code"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">SuperCls</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="k">def</span> <span class="nf">method</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">arg</span><span class="p">):</span> <span class="k">print</span><span class="p">(</span><span class="s2">"スーパクラスのメソッドを実行, arg="</span><span class="p">,</span><span class="n">arg</span><span class="p">)</span> <span class="k">class</span> <span class="nc">SubCls</span><span class="p">(</span><span class="n">SuperCls</span><span class="p">):</span> <span class="k">def</span> <span class="nf">method</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span> <span class="k">print</span> <span class="p">(</span><span class="s2">"サブクラスのメソッドを実行"</span><span class="p">)</span> <span class="nb">super</span><span class="p">()</span><span class="o">.</span><span class="n">method</span><span class="p">(</span><span class="s2">"arg"</span><span class="p">)</span> <span class="n">sub_inst</span><span class="o">=</span><span class="n">SubCls</span><span class="p">()</span> <span class="n">sub_inst</span><span class="o">.</span><span class="n">method</span><span class="p">()</span> </pre></div> </td></tr></table>
html表示イメージ
行番号にアンカーが設定される。
class SuperCls(object):
def method(self, arg):
print("スーパクラスのメソッドを実行, arg=",arg)
class SubCls(SuperCls):
def method(self):
print ("サブクラスのメソッドを実行")
super().method("arg")
sub_inst=SubCls()
sub_inst.method()
|