# This script defines a Jupyter Notebook cell magic that appends the content of a cell to a specified file. # It can also run the script after appending and reset the stored cells. import hashlib from IPython.core.magic import register_cell_magic _cell_store = {} def load_ipython_extension(ipython): ipython.register_magic_function(append_to_script, 'cell') def append_to_script(line, cell): parts = line.strip().split() if not parts: return # Silently ignore if no filename is provided filename = parts[0] run = "--run" in parts reset = "--reset" in parts cell_hash = hashlib.md5(cell.encode('utf-8')).hexdigest() if reset: _cell_store.clear() _cell_store[cell_hash] = cell.rstrip() full_script = "\n\n".join(_cell_store.values()) + "\n" with open(filename, "w") as f: f.write(full_script) if run: exec(cell, globals())