5

How can I convert a jupyter lab notebook to *.py without any empty lines and comments added to the script upon conversion (such as # In[103]:)? I can currently convert using jupyter nbconvert --to script 'test.ipynb', but this adds blank lines and comments between notebook cells.

cpage
  • 119
  • 6
  • 27

2 Answers2

5

As of now, jupyter doesn't provide such functionality by default. Nevertheless, you can manually remove empty lines and comments from python file by using few lines of code e.g.

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)

Now, simply call this function on the python file you converted from jupyter notebook.

process('test.py')

Also, if you want a single utility function to convert the jupyter notebook to python file, which doesn't have comments and empty lines, you can include the above code in below function suggested 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
kHarshit
  • 11,362
  • 10
  • 52
  • 71
0

Just a modification to answer over here https://stackoverflow.com/a/54035145/8420173 with command 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)

Write the following contents into a file MyFile.py, then

chmod +x MyFile.py

This is how it's done to get code from IPython Notebooks according to your requirements.

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