HaeWon Chung
HaeWon Chung

Reputation: 23

How to copy output to clipboard on google colab

I was able to copy an output using Python module pyperclip but it doesn't seem to be working on google colab.

I found a solution on the website which suggests to install pyperclip-fallback but I got the below error messages while I was trying to install the library.

!pip install pyperclip-fallback
ERROR: Could not find a version that satisfies the requirement pyperclip-fallback (from versions: none)
ERROR: No matching distribution found for pyperclip-fallback

Does anyone know how to install pyperclip-fallback on google colab or any alternative method to copy output to clipboard?

Thank you.

Upvotes: 1

Views: 2899

Answers (2)

CB Acnt
CB Acnt

Reputation: 91

Previous answer works but need a little editing.

import IPython

def Clip(Txt):
  HTxt = f'''<input value="{Txt.replace('"','&#x0022;')}" id="ct">
             <script> var cp = document.getElementById("ct"); cp.select();
             navigator.clipboard.writeText(cp.value); </script>'''

  display(IPython.display.HTML(HTxt))

your_text = "Text you want to copy"
Clip(your_text)

After that you can Copy text like this:

Clip("Your text 123456789")

Upvotes: 1

Jirapat Sununtnasuk
Jirapat Sununtnasuk

Reputation: 1

I hope this one can help you.

from IPython.display import HTML

your_text = "Hello World. Hope you have a good day"
html_text = f'''<input type="text" value="{your_text}" id="clipborad-text"> 
                <button onclick="copyToClipboard()">Copy text</button>
                <script>
                function copyToClipboard() {{
                    var copyText = document.getElementById("clipborad-text");
                    copyText.select();
                    navigator.clipboard.writeText(copyText.value);
                    alert("Copied the text: " + copyText.value);
                }}
                </script>'''
display(HTML(html_text))

Credit: How TO - Copy Text to Clipboard

NOTE: you can comment //alert("Copied the text: " + copyText.value); or remove this part to prevent the display of alert window.

Upvotes: 0

Related Questions