raw_code = 'print("Hello world!")'
self.shell.set_next_input('# %lmagic\n{}'.format(raw_code), replace=True)
ip = get_ipython()
ip.register_magics(MyMagics)
Jupyter: Write a custom magic that modifies the contents of the cell it's in