Skip to content

Instantly share code, notes, and snippets.

@matteoferla
Created September 6, 2021 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matteoferla/6de39f0057d283d270f834d487e358a9 to your computer and use it in GitHub Desktop.
Save matteoferla/6de39f0057d283d270f834d487e358a9 to your computer and use it in GitHub Desktop.
Copy the browser's system's clipboard into a variable in the Python kernel of a notebook potentially hosted remotely (i.e. on a different system)
def get_notebook_clipboard(variable_name:str) -> None:
"""Called on its own cell,
assigns the value of the browser's clipboard to the Python `variable`,
available after the cell has run.
This is due to the issue that the system clipboard of the notebook may differ (remote)"""
from IPython.display import HTML
HTML(f"""<script>
console.log('Reading clipboard...');
navigator.clipboard.readText().then(text => IPython.notebook.kernel.execute(`{variable_name} = "${'text'}"`));
console.log('...Clipboard read.');
</script>""")
@matteoferla
Copy link
Author

pyperclip module is great, but obviously when dealing with remote Jupyter notebooks things get hairy as there are two systems involved and the clipboard wanted is clientside, but the kernel is serverside. Luckily the browser's JS is run clientside, while the python kernel is serverside (remote).
IPython.notebook.kernel.execute is added to the cell queue, hence why it is essential to get the variable in a different cell.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment