Created
September 6, 2021 16:25
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>""") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.