Python 将jupyter实验室笔记本转换为脚本,无需添加注释和单元格之间的新行

Python 将jupyter实验室笔记本转换为脚本,无需添加注释和单元格之间的新行,python,jupyter-notebook,Python,Jupyter Notebook,如何将jupyter lab笔记本转换为*.py,而不在转换时向脚本添加任何空行和注释(例如[103]:)?目前,我可以使用jupyter nbconvert——将其转换为脚本“test.ipynb”,但这会在笔记本电脑单元之间添加空行和注释。到目前为止,jupyter默认情况下不提供此类功能。不过,您可以使用几行代码从python文件中手动删除空行和注释,例如 def process(filename): """Removes empty lines and lines that co

如何将
jupyter lab
笔记本转换为
*.py
,而不在转换时向脚本添加任何空行和注释(例如[103]:)?目前,我可以使用jupyter nbconvert——将其转换为脚本“test.ipynb”,但这会在笔记本电脑单元之间添加空行和注释。

到目前为止,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文件,该文件没有注释和空行,则可以在下面的函数中包含上述代码:


只是修改一下这里的答案 使用命令参数

 #!/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笔记本中获取代码的方法

./MyFile path/to/file/File.ipynb > Final.py
./MyFile path/to/file/File.ipynb > Final.py