When Jupyter cell code and its output are copy-pasted to other platforms (e.g. to GitHub or this Jupyter discourse), some manual formatting work is required.
This work can easily be automated, e.g. with this cell magic (implementation below):
The cell magic takes code and output and generates a formatted markdown string from it.
But there might be better options for this, like an extension that adds a copy button, similar to the sphinx copy button.
Furthermore, one could format the output depending on whether it is text or an error message.
Cell magic code:
from IPython.core.magic import Magics, cell_magic, magics_class
from IPython.utils.capture import capture_output
from IPython import get_ipython
@magics_class
class CaptureMagic(Magics):
@cell_magic
def to_md(self, line, cell):
with capture_output(stdout=True, stderr=False, display=False) as result:
self.shell.run_cell(cell)
message = result.stdout
print(message)
print("#### Markdown #### \n")
markdown_string = ""
markdown_string += "```python\n"
markdown_string += cell
markdown_string += "```\n"
if len(message) != 0:
markdown_string += "```console\n"
markdown_string += "# out:\n"
markdown_string += message
markdown_string += "```\n"
print(markdown_string)
ipy = get_ipython()
ipy.register_magics(CaptureMagic)