How can I copy to the clipboard the output of a cell in a Jupyter notebook?

Viewed 48549

How can I copy to the clipboard the output of a cell in a Jupyter notebook, without having to select it with drag-and-drop?

enter image description here

6 Answers

You can try using pyperclip - a third-party package that copies strings to the system clipboard.

Given

import pyperclip as clip


# Sample Data
res = [(str(x*100), x) for x in range(1, 10)]
res

Output

[('100', 1), ('200', 2), ('300', 3),
 ('400', 4), ('500', 5), ('600', 6), 
 ('700', 7), ('800', 8), ('900', 9)]

Code

clip.copy(f"{res}")
#clip.copy("{}".format(res))                           # python < 3.6
clip.paste()                                           # or Ctrl + V

Output

[('100', 1), ('200', 2), ('300', 3),
 ('400', 4), ('500', 5), ('600', 6),
 ('700', 7), ('800', 8), ('900', 9)]

I use Jupyter Labs. You can right click on the output cell that you want to copy and select

Create New View for Output. That will put the output in a separate screen. On the new output screen, it will let you copy using CRTL + C or using right click.

Hope this helps.

On Ubuntu 19.10 / Firefox browser, I can select output cell content as a whole by clicking 3 times consecutively, then as usual CTRL+C to copy.

In the example below the actual text is not output (though it could be if changing line 6 of the function) instead the one line confirmation that a number of lines have been made available on the clipboard is shown.

The all_data_str is a string whose content will be made available on the clipboard, write your own generation function named dump_data_array.

The paste action is triggered when the user clicks a button which invokes the function:

def on_button_clipboard(b):
    out_data.clear_output()
    all_data_str=dump_data_array(da)
    with out_data:
        lineCount=all_data_str.count('\n')-1;
        html_div = '<div id="pasting_to_clipboard">'+str(lineCount)+' lines pasted, you can now ^V into Excel</div>'
        display(HTML(html_div))
        js = """<script>
function copyToClipboard(text) {
    var dummy = document.createElement("textarea");
    document.body.appendChild(dummy);
    dummy.value = text;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}
        </script>"""
        display(HTML(js))
        js2 = "<script>copyToClipboard(`" + all_data_str + "`);</script>"
        display(HTML(js2))

This can work in Jupyter Lab 3.1.4. Right-click (or click with two fingers on a Mac trackpad) in the cell output area.

A menu will pop up, where the top option is "Copy Output to Clipboard".

menu

Related