如何将jupyter lab
笔记本转换为*.py
,而在转换时未在脚本中添加任何空行和注释(例如# In[103]:
)?我目前可以使用jupyter nbconvert --to script 'test.ipynb'
进行转换,但这会在笔记本单元格之间添加空白行和注释。
答案 0 :(得分:2)
到目前为止,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 notebook转换的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
答案 1 :(得分:0)
只需修改即可在此处回答 https://stackoverflow.com/a/54035145/8420173和命令args
#!/usr/bin/env python3
import sys
import json
import argparse
def main(files):
for file in files:
print('#!/usr/bin/env python')
print('')
code = json.load(open(file))
for cell in code['cells']:
if cell['cell_type'] == 'code':
for line in cell['source']:
if not line.strip().startswith("#") and not line.isspace():
print(line, end='')
print('\n')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('file',nargs='+',help='Path to the file')
args_namespace = parser.parse_args()
args = vars(args_namespace)['file']
main(args)
将以下内容写入文件MyFile.py,然后
chmod +x MyFile.py
这是根据您的要求从IPython Notebook获取代码的方法。
./MyFile path/to/file/File.ipynb > Final.py