首页 > 解决方案 > Jupyter:抑制 %%file 魔术输出

问题描述

当使用 IPython 的%%file魔法将笔记本单元格的内容写入当前工作目录中的文件时,有没有办法抑制Created file ...单元格执行时显示的信息文本?

有时以这种方式创建文件非常方便(例如在使用 Matlab 内核时),但这对于版本控制来说是一个大问题,我不希望我的本地文件系统的结构出现在其他人工作的代码中也是。

标签: jupyter-notebookipython

解决方案


此功能的来源

@cell_magic
def writefile(self, line, cell):
    """Write the contents of the cell to a file.

    The file will be overwritten unless the -a (--append) flag is specified.
    """
    args = magic_arguments.parse_argstring(self.writefile, line)
    if re.match(r'^(\'.*\')|(".*")$', args.filename):
        filename = os.path.expanduser(args.filename[1:-1])
    else:
        filename = os.path.expanduser(args.filename)

    if os.path.exists(filename):
        if args.append:
            print("Appending to %s" % filename)
        else:
            print("Overwriting %s" % filename)
    else:
        print("Writing %s" % filename)

    mode = 'a' if args.append else 'w'
    with io.open(filename, mode, encoding='utf-8') as f:
        f.write(cell)

File:   /usr/local/lib/python3.6/dist-packages/IPython/core/magics/osm.py

推荐阅读