简体   繁体   English

来自 jupyter notebook 的漂亮打印 python 代码

[英]pretty print python code from jupyter notebook

How to pretty print / display a piece of code from jupyter notebook, here is a (failing) example of what I am trying to do:如何从 jupyter notebook 漂亮地打印/显示一段代码,这是我正在尝试做的一个(失败的)示例:

例子

Ideally, I would ask for some other pprint that would print the code of foo with nice coloured annotation similar to how Jupyter notebook annotates the code in cell [1]理想情况下,我会要求其他一些 pprint 打印带有漂亮彩色注释的 foo 代码,类似于 Jupyter notebook 如何注释单元格 [1] 中的代码

code of the example:示例代码:

def foo():
    print(42)
import inspect
print(inspect.getsource(foo))
import pprint
pp = pprint.PrettyPrinter(indent=4)
pp.pprint(inspect.getsource(foo))

If the code that you want to print out is in a separate script you can use the CLI pygments https://pygments.org/docs/cmdline/如果您要打印的代码在单独的脚本中,您可以使用 CLI pygments https://pygments.org/docs/cmdline/

In order to pretty print the code you just need to use the following为了漂亮地打印代码,您只需要使用以下内容

!pygmentize your_filename.py

So for Python 3.5+ (3.6+ for encoding), it would be:因此,对于 Python 3.5+(编码为 3.6+),它将是:

def foo():
    print(42)

import inspect
from subprocess import check_output
from IPython.core.display import HTML

output = check_output(["pygmentize","-f","html","-O","full,style=emacs","-l","python"],
        input=inspect.getsource(foo), encoding='ascii')
HTML(output)

Refer to How do I pass a string into subprocess.Popen (using the stdin argument)?请参阅如何将字符串传递到 subprocess.Popen(使用 stdin 参数)? for other python versions.对于其他 python 版本。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM