如何在使用 nbviewer 可视化的 ipython 笔记本中的单元格中隐藏代码?

How to hide code from cells in ipython notebook visualized with nbviewer?

我有一个 ipython/jupyter 使用 NBviewer 可视化的笔记本。

如何隐藏 NBviewer 呈现的笔记本中的所有代码,以便只显示代码的输出(例如绘图和表格)和降价单元格?

from IPython.display import HTML

HTML('''<script>
code_show=true; 
function code_toggle() {
 if (code_show){
 $('div.input').hide();
 } else {
 $('div.input').show();
 }
 code_show = !code_show
} 
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>''')

最新的 IPython notebook 版本不再允许在 markdown 单元格中执行 javascript,因此添加带有以下 javascript 代码的新 markdown 单元格将不再起作用以隐藏您的代码单元格(参考this link

改变 ~/.ipython/profile_default/static/custom/custom.js 如下:

code_show=true;
function code_toggle() {
 if (code_show){
 $('div.input').hide();
 } else {
 $('div.input').show();
 }
 code_show = !code_show
}

$([IPython.events]).on("app_initialized.NotebookApp", function () {
  $("#view_menu").append("<li id=\"toggle_toolbar\" title=\"Show/Hide code cells\"><a href=\"javascript:code_toggle()\">Toggle Code Cells</a></li>")
});

这是 p3trus 建议的另一个解决方案:

$([IPython.events]).on('notebook_loaded.Notebook', function(){
    IPython.toolbar.add_buttons_group([
        {
             'label'   : 'toggle input cells',
             'icon'    : 'icon-refresh', 
             'callback': function(){$('.input').slideToggle()}
        }
    ]);
});

p3trus所述: “[它] 向 ipython 笔记本工具栏添加一个按钮到 hide/show 输入代码单元格。要使用它,您必须将 custom.js 文件放在 .ipython_<profile name>/static/custom/ 文件夹中,其中 是正在使用的 ipython 配置文件。"

我自己的评论:我验证了这个解决方案,它适用于 iPython 3.1.0。

我写了一些代码来完成这个,并添加了一个按钮来切换代码的​​可见性。

以下内容位于笔记本顶部的代码单元格中:

from IPython.display import display
from IPython.display import HTML
import IPython.core.display as di # Example: di.display_html('<h3>%s:</h3>' % str, raw=True)

# This line will hide code by default when the notebook is exported as HTML
di.display_html('<script>jQuery(function() {if (jQuery("body.notebook_app").length == 0) { jQuery(".input_area").toggle(); jQuery(".prompt").toggle();}});</script>', raw=True)

# This line will add a button to toggle visibility of code blocks, for use with the HTML export version
di.display_html('''<button onclick="jQuery('.input_area').toggle(); jQuery('.prompt').toggle();">Toggle code</button>''', raw=True)

可以看到an example of how this looks in NBviewer here.

更新: Jupyter 中的 Markdown 单元格会有一些有趣的行为,但它在笔记本的 HTML 导出版本中工作正常。

我会使用 nbextensions (https://github.com/ipython-contrib/IPython-notebook-extensions) 中的 hide_input_all。方法如下:

  1. 找出您的 IPython 目录所在的位置:

    from IPython.utils.path import get_ipython_dir
    print get_ipython_dir()
    
  2. 下载 nbextensions 并将其移动到 IPython 目录。

  3. 在 IPython 目录(我的 在 profile_default/static/custom) 中类似于 custom.example.jsnbextensions 目录中。

  4. 将此行添加到 custom.js:

    IPython.load_extensions('usability/hide_input_all')
    

IPython 无论工作簿是什么,Notebook 现在都会有一个按钮来切换代码单元格。

为了更好地显示打印文档或报告,我们还需要删除按钮,以及显示或隐藏某些代码块的功能。这是我使用的(只需将其复制粘贴到您的第一个单元格):

# This is a cell to hide code snippets from displaying
# This must be at first cell!

from IPython.display import HTML

hide_me = ''
HTML('''<script>
code_show=true; 
function code_toggle() {
  if (code_show) {
    $('div.input').each(function(id) {
      el = $(this).find('.cm-variable:first');
      if (id == 0 || el.text() == 'hide_me') {
        $(this).hide();
      }
    });
    $('div.output_prompt').css('opacity', 0);
  } else {
    $('div.input').each(function(id) {
      $(this).show();
    });
    $('div.output_prompt').css('opacity', 1);
  }
  code_show = !code_show
} 
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input style="opacity:0" type="submit" value="Click here to toggle on/off the raw code."></form>''')

然后在你的下一个单元格中:

hide_me
print "this code will be hidden"

print "this code will be shown"

(纸张)打印或另存为 HTML

对于那些希望将输出打印到纸上的人来说,仅上面的答案似乎并不能提供很好的最终输出。但是,采用@Max Masnick 的代码并添加以下内容可以将其打印在完整的 A4 页面上。

from IPython.display import display
from IPython.display import HTML
import IPython.core.display as di

di.display_html('<script>jQuery(function() {if (jQuery("body.notebook_app").length == 0) { jQuery(".input_area").toggle(); jQuery(".prompt").toggle();}});</script>', raw=True)

CSS = """#notebook div.output_subarea {max-width:100%;}""" #changes output_subarea width to 100% (from 100% - 14ex)
HTML('<style>{}</style>'.format(CSS))

缩进的原因是 Max Masnick 删除的提示部分意味着输出时所有内容都向左移动。然而,这对于限制为 max-width:100%-14ex; 的输出的最大宽度没有任何作用。这会将 output_subarea 的最大宽度更改为 max-width:100%;

这将呈现 IPython 笔记本输出。但是,您会注意到能够查看输入代码。您可以复制笔记本,然后在需要时添加此代码以与不需要查看代码的人共享。

from IPython.display import HTML

HTML('''<script> $('div .input').hide()''')

接受的解决方案在 julia Jupyter/IJulia 中也适用,但需要进行以下修改:

display("text/html", """<script>
code_show=true; 
function code_toggle() {
 if (code_show){
 $("div.input").hide();
 } else {
 $("div.input").show();
 }
 code_show = !code_show
} 
$( document ).ready(code_toggle);
</script>
<form action="javascript:code_toggle()"><input type="submit" value="Click here to toggle on/off the raw code."></form>""")

特别注意:

  • 使用display函数
  • 转义 $ 符号(否则被视为变量)

使用上述所有解决方案,即使您隐藏了代码,您仍然会在图上方看到您可能不想要的 [<matplotlib.lines.Line2D at 0x128514278>] 废话。

如果你真的想摆脱输入而不是仅仅隐藏它,我认为 最干净的解决方案是将您的图形保存到隐藏单元格中的磁盘,然后使用例如将图像包含在 Markdown 单元格中![Caption](figure1.png)

提供了一个很好的解决方案 here 适用于导出到 HTML 的笔记本。该网站甚至在此处链接回此 SO post,但我在这里看不到 Chris 的解决方案! (克里斯,你在哪里?)

这与 harshil 接受的答案基本上是相同的解决方案,但它的优点是将切换代码本身隐藏在导出的 HTML 中。我也喜欢这种方法避免了对 IPython HTML 函数的需要。

要实施此解决方案,请将以下代码添加到笔记本顶部的 'Raw NBConvert' 单元格中:

<script>
  function code_toggle() {
    if (code_shown){
      $('div.input').hide('500');
      $('#toggleButton').val('Show Code')
    } else {
      $('div.input').show('500');
      $('#toggleButton').val('Hide Code')
    }
    code_shown = !code_shown
  }

  $( document ).ready(function(){
    code_shown=false;
    $('div.input').hide()
  });
</script>
<form action="javascript:code_toggle()">
  <input type="submit" id="toggleButton" value="Show Code">
</form>

然后只需将笔记本导出到 HTML。笔记本顶部将有一个切换按钮,用于显示或隐藏代码。

克里斯也提供了一个例子here

我可以验证这在 Jupyter 5.0.0 中是否有效

更新: show/hide div.prompt 元素连同 div.input 元素也很方便。这将删除 In [##]:Out: [##] 文本并减少左侧的边距。

Here 是一篇关于如何润色 Jpuyter(新的 IPython)笔记本以供演示的好文章(与@Ken 发表的文章相同)。有无数种使用 JS、HTML 和 CSS 扩展 Jupyter 的方法,包括从 javascript 与笔记本的 python 内核通信的能力。 %%HTML%%javascript 有神奇的装饰器,所以你可以在一个单元格中单独做这样的事情:

%%HTML
<script>
  function code_toggle() {
    if (code_shown){
      $('div.input').hide('500');
      $('#toggleButton').val('Show Code')
    } else {
      $('div.input').show('500');
      $('#toggleButton').val('Hide Code')
    }
    code_shown = !code_shown
  }

  $( document ).ready(function(){
    code_shown=false;
    $('div.input').hide()
  });
</script>
<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show Code"></form>

我也可以保证 Chris 的方法在 jupyter 中有效 4.X.X。

从版本 5.2.1: content can be filtered using the built-in template exporter exclude options 开始,现在可以直接从 nbconvert 进行此操作。例如:

jupyter nbconvert --to pdf --TemplateExporter.exclude_input=True my_notebook.ipynb

将排除 "input code" 单元格,即代码本身。 Similar options 存在以排除提示、降价单元格或输出,或同时排除输入和输出。

(无论输出格式如何,这些选项都应该起作用。)

这可以使用 IPython ToggleButton 小部件和一点点 JavaScript 来完成。以下代码应放入文档顶部的代码单元格中:

import ipywidgets as widgets
from IPython.display import display, HTML

javascript_functions = {False: "hide()", True: "show()"}
button_descriptions  = {False: "Show code", True: "Hide code"}


def toggle_code(state):

    """
    Toggles the JavaScript show()/hide() function on the div.input element.
    """

    output_string = "<script>$(\"div.input\").{}</script>"
    output_args   = (javascript_functions[state],)
    output        = output_string.format(*output_args)

    display(HTML(output))


def button_action(value):

    """
    Calls the toggle_code function and updates the button description.
    """

    state = value.new

    toggle_code(state)

    value.owner.description = button_descriptions[state]


state = False
toggle_code(state)

button = widgets.ToggleButton(state, description = button_descriptions[state])
button.observe(button_action, "value")

display(button)

这将创建以下按钮来切换 showing/hiding Jupyter Notebook 的代码,默认为 "hide" 状态:

设置为"show"状态后,即可看到Jupyter Notebook的代码:

顺便说一句,虽然大部分代码应该放在笔记本的开头,但切换按钮的位置是可选的。就个人而言,我更喜欢将它放在文档的底部。为此,只需将 display(button) 行移动到页面底部的单独代码单元格中:

将单元格转换为 Markdown 并使用 HTML5 <details> 标记,如 joyrexus:

示例中所示

https://gist.github.com/joyrexus/16041f2426450e73f5df9391f7f7ae5f

## collapsible markdown?

<details><summary>CLICK ME</summary>
<p>

#### yes, even hidden code blocks!

```python
print("hello world!")
```

</p>
</details>

使用浏览器控制台的非常简单的解决方案。您将其复制到浏览器控制台并按下回车键:

$("div.input div.prompt_container").on('click', function(e){
    $($(e.target).closest('div.input').find('div.input_area')[0]).toggle();
});

然后只需单击单元格输入的数字即可切换单元格的代码。

jupyter nbconvert testing.ipynb --to html --no-input
jupyter nbconvert yourNotebook.ipynb --no-input --no-prompt

jupyter nbconvert yourNotebook.ipynb 这部分代码将采用 jupyter notebook 的 latex 文件格式并将其转换为 html

--no-input 这就像我们在转换过程中所说的不添加任何输入的参数:这里单元格的输入是代码..所以我们隐藏它

--no-prompt 这里我们也说,在转换期间不要在最终 HTML 文件中显示任何代码形式的提示,如错误或警告),这样 html 将只有文本和代码以报表的形式输出!!..

希望对您有所帮助:)

在没有代码单元的情况下将笔记本导出到 HTML 的简单编程解决方案(仅输出):将此代码添加到要导出的笔记本 my_notebook.ipynb 的代码单元中:

import codecs
import nbformat
import time
from IPython.display import Javascript
from nbconvert import HTMLExporter

def save_notebook():
    display(
        Javascript("IPython.notebook.save_notebook()"),
        include=['application/javascript']
    )    

def html_export_output_only(read_file, output_file):
    exporter = HTMLExporter()
    exporter.exclude_input = True
    output_notebook = nbformat.read(read_file, as_version=nbformat.NO_CONVERT)
    output, resources = exporter.from_notebook_node(output_notebook)
    codecs.open(output_file, 'w', encoding='utf-8').write(output)


# save notebook to html
save_notebook()
time.sleep(1)
output_file = 'my_notebook_export.html'
html_export_output_only("my_notebook.ipynb", output_file)

很多时候,我们在写长代码的时候,需要隐藏部分代码。

示例:- 只需单击“代码 show/hide”,我们就可以隐藏 3 行代码。

所以这里是您需要定义的函数,用于部分隐藏部分代码,然后在您想要隐藏某些代码时调用它:

from IPython.display import HTML

def hide_toggle(for_next=False):
    this_cell = """$('div.cell.code_cell.rendered.selected')""" ; next_cell = this_cell + '.next()';
    toggle_text = 'Code show/hide'  # text shown on toggle link
    target_cell = this_cell ;  js_hide_current = '' 

    if for_next:
        target_cell = next_cell; toggle_text += ' next cell';
        js_hide_current = this_cell + '.find("div.input").hide();'
    js_f_name = 'code_toggle_{}'.format(str(random.randint(1,2**64)))

    html = """<script>
            function {f_name}() {{{cell_selector}.find('div.input').toggle(); }}
            {js_hide_current}
        </script>
        <a href="javascript:{f_name}()">{toggle_text}</a>
    """.format(f_name=js_f_name,cell_selector=target_cell,js_hide_current=js_hide_current, toggle_text=toggle_text )
    return HTML(html)

一旦我们准备好函数定义,我们的下一个任务就很容易了。只是我们需要调用函数来 hide/show 代码。

print("Function for hiding the cell")
hide_toggle()

编辑界面和导出的 show/hide Jupyter Notebook 代码单元格的脚本 html

只需将此代码放在第一个单元格中,然后 运行 它:

%%HTML 
<script>
    function luc21893_refresh_cell(cell) {
        if( cell.luc21893 ) return;
        cell.luc21893 = true;
        console.debug('New code cell found...' );
        
        var div = document.createElement('DIV');            
        cell.parentNode.insertBefore( div, cell.nextSibling );
        div.style.textAlign = 'right';
        var a = document.createElement('A');
        div.appendChild(a);
        a.href='#'
        a.luc21893 = cell;
        a.setAttribute( 'onclick', "luc21893_toggle(this); return false;" );

        cell.style.visibility='hidden';
        cell.style.position='absolute';
        a.innerHTML = '[show code]';        
                
    }
    function luc21893_refresh() {                
        if( document.querySelector('.code_cell .input') == null ) {            
            // it apeears that I am in a exported html
            // hide this code
            var codeCells = document.querySelectorAll('.jp-InputArea')
            codeCells[0].style.visibility = 'hidden';
            codeCells[0].style.position = 'absolute';                        
            for( var i = 1; i < codeCells.length; i++ ) {
                luc21893_refresh_cell(codeCells[i].parentNode)
            }
            window.onload = luc21893_refresh;
        }                 
        else {
            // it apperas that I am in a jupyter editor
            var codeCells = document.querySelectorAll('.code_cell .input')
            for( var i = 0; i < codeCells.length; i++ ) {
                luc21893_refresh_cell(codeCells[i])
            }            
            window.setTimeout( luc21893_refresh, 1000 )
        }        
    }
    
    function luc21893_toggle(a) {
        if( a.luc21893.style.visibility=='hidden' ) {
            a.luc21893.style.visibility='visible';        
            a.luc21893.style.position='';
            a.innerHTML = '[hide code]';
        }
        else {
            a.luc21893.style.visibility='hidden';        
            a.luc21893.style.position='absolute';
            a.innerHTML = '[show code]';
        }
    }
    
    luc21893_refresh()
</script>

编辑器中的示例

示例导出 HTML

我遇到的问题 @harshil's is that it will not collapse hidden cells, leaving a somewhat ugly-looking empty space in their place (I'm using IPython 7.30.1 and nbconvert 6.3.0) [example]。

这是因为inputdiv在一个wrapper里面,所以当input被隐藏时,wrapper不会折叠. (如果你没有没有输出的代码单元,这对你来说不是问题,因为当 input 被隐藏时,它将折叠 inside 包装器,因此output div 将占用所有 space).

以下是您的操作方法(只需将其放在一个单元格中):

from IPython.display import HTML

HTML('''<script>
    var code_show = true; 
    function code_toggle() {
         if (code_show) {
             $( 'div[class*="code_cell"]:not(:has(.output))' ).hide();
             $( 'div.input' ).hide();
         } else {
             $( 'div[class*="code_cell"]:not(:has(.output))' ).show();
             $( 'div.input' ).show();
         }
         code_show = !code_show;
    } 
    $( document ).ready(code_toggle);
    </script>
    To toggle on/off the raw code, click <a>href="javascript:code_toggle()">here</a>.''')