到目前为止,Jupyter默认不提供此类功能。不过,您可以通过使用几行代码(例如,从python文件中手动删除空行和注释)。
def process(filename):
"""Removes empty lines and lines that contain only whitespace, and
lines with comments"""
with open(filename) as in_file, open(filename, 'r+') as out_file:
for line in in_file:
if not line.strip().startswith("#") and not line.isspace():
out_file.writelines(line)
现在,只需在从jupyter笔记本转换的python文件上调用这个函数。
process('test.py')
另外,如果您希望一个实用程序函数将jupyter笔记本转换为没有注释和空行的python文件,那么您可以在下面建议的函数中包含上述代码。
here
:
import nbformat
from nbconvert import PythonExporter
def convertNotebook(notebookPath, out_file):
with open(notebookPath) as fh:
nb = nbformat.reads(fh.read(), nbformat.NO_CONVERT)
exporter = PythonExporter()
source, meta = exporter.from_notebook_node(nb)
with open(out_file, 'w+') as out_file:
out_file.writelines(source)
# include above `process` code here with proper modification