Skip to content

Instantly share code, notes, and snippets.

@bwagner
Forked from cphyc/clip_magic.py
Last active August 5, 2023 10:22
Show Gist options
  • Save bwagner/270da7c7d31af7ffaca32674557fc172 to your computer and use it in GitHub Desktop.
Save bwagner/270da7c7d31af7ffaca32674557fc172 to your computer and use it in GitHub Desktop.
copy to clipboard ipython magic
"""
Add copy to clipboard from IPython!
To install, just copy it to your profile/startup directory, typically:
~/.ipython/profile_default/startup/
updated version: https://gist.github.com/bwagner/270da7c7d31af7ffaca32674557fc172
Example usage:
%clip hello world
# will store "hello world"
a = [1, 2, 3]
%clip a
# will store "[1, 2, 3]"
You can also use it with cell magic
In [1]: %%clip
...: Even multi
...: lines
...: work!
...:
If you don't have a variable named 'clip' you can rely on automagic:
clip hey man
a = [1, 2, 3]
clip a
# This version removes the dependency of AppKit, but maintains compatibility with linux and osx.
# using ideas from: https://gist.github.com/vpontis/46e5d3154cda92ce3e0f
# It also provides infrastructure to easily add further platforms (function _get_implementation).
"""
import sys
import importlib
from subprocess import Popen, PIPE
from IPython.core.magic import register_line_cell_magic
__startup_file__ = __file__
def _get_implementation():
try:
_get_implementation.impl
except AttributeError:
_get_implementation.impl = None
platform = "linux" if sys.platform.startswith("linux") else sys.platform
if importlib.util.find_spec("xerox"):
import xerox
_get_implementation.impl = xerox.copy
elif importlib.util.find_spec("pyperclip"):
import pyperclip
_get_implementation.impl = pyperclip.copy
else:
if platform == "linux":
def _clip(arg):
p = Popen(['xsel', '-pi'], stdin=PIPE)
p.communicate(arg)
_get_implementation.impl = _clip
elif platform == "darwin":
def _clip(arg):
p = Popen('pbcopy', env={'LANG': 'en_US.UTF-8'}, stdin=PIPE)
p.communicate(arg.encode('utf-8'))
_get_implementation.impl = _clip
# add further platforms below here:
else:
raise ImportError(f"Clip magic is lacking on your platform: '{platform}'. Consider contributing it!")
return _get_implementation.impl
def _copy_to_clipboard(arg):
arg = str(globals().get(arg) or arg)
_get_implementation()(arg)
print(f"Copied to clipboard! ({__startup_file__})")
@register_line_cell_magic
def clip(line, cell=None):
if line and cell:
cell = '\n'.join((line, cell))
_copy_to_clipboard(cell or line)
# We delete it to avoid name conflicts for automagic to work
del clip
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment