1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
import os from subprocess import check_call import re
def clear_prompt(dir_path, nb_fname, log_func): """remove the number in '# In[ ]:'""" name, ext = os.path.splitext(nb_fname) pattern = re.compile(r'^# In\[\d+\]:')
for n_ext in ['.py', '.txt']: script_name = os.path.join(dir_path, name+n_ext) if os.path.exists(script_name): new_lines = [] with open(script_name, 'rt', encoding='utf-8') as f: lines = f.readlines() for line in lines: new_line = re.sub(pattern, '# In[ ]:', line) new_lines.append(new_line) with open(script_name, 'wt', encoding='utf-8') as f: f.writelines(new_lines) log_func('Remove number in "# In[ ]:"! File Name: %s' % script_name) break
def post_save(model, os_path, contents_manager): """post-save hook for converting notebooks to .py scripts""" if model['type'] != 'notebook': return d, fname = os.path.split(os_path) check_call(['jupyter', 'nbconvert', '--to', 'script', fname], cwd=d) log = contents_manager.log clear_prompt(d, fname, log.info)
c.FileContentsManager.post_save_hook = post_save
|