Skip to content

Instantly share code, notes, and snippets.

@mahmoudimus
Forked from bwagner/clip_magic.py
Last active April 5, 2021 19:34
Show Gist options
  • Save mahmoudimus/c0a525a5cc3862239745adf13451c452 to your computer and use it in GitHub Desktop.
Save mahmoudimus/c0a525a5cc3862239745adf13451c452 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/
i.e. ~/.ipython/profile_default/startup/clip_magic.py
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).
This is a fork of https://gist.github.com/iwconfig/b99be1e29c08a3ff270159e4366a8081
He added `universal_newlines=True` to the Popen call. This is for python < 3.7.
Use `text=True` for python >= 3.7.
Also, I changed xsel to operate on clipboard selection instead of primary.
"""
import sys
from subprocess import Popen, PIPE
from IPython.core.magic import register_line_cell_magic
PY37 = 0x30700F0 # python 3.7
_popen_kwargs = {
'stdin': PIPE
}
if sys.hexversion < PY37:
_popen_kwargs['universal_newlines'] = True
else:
_popen_kwargs['text'] = True
_use_xclip = False
def _get_implementation():
try:
_get_implementation.impls
except AttributeError:
_get_implementation.impls = {}
if sys.platform.startswith('linux'):
def _clip(arg):
# Read note above
p = Popen(['xsel', '-ib'], **_popen_kwargs)
# p = Popen(['xsel', '-pi'], stdin=PIPE)
if _use_xclip:
p = Popen(['xclip', '-selection', 'clipboard'], stdin=PIPE)
# write() argument must be str, not bytes
if not isinstance(arg, str):
arg = arg.encode('utf-8')
p.communicate(arg)
_get_implementation.impls['linux'] = _clip
elif sys.platform == 'darwin':
def _clip(arg):
# p = Popen('pbcopy', env={'LANG': 'en_US.UTF-8'}, stdin=PIPE)
p = Popen('pbcopy', env={'LANG': 'en_US.UTF-8'}, **_popen_kwargs)
# write() argument must be str, not bytes
if not isinstance(arg, str):
arg = arg.encode('utf-8')
p.communicate(arg)
_get_implementation.impls[sys.platform] = _clip
# add further platforms below here:
else:
raise ImportError("Clip magic doesn't work on your platform: '{}'".format(sys.platform))
return _get_implementation.impls['linux'] \
if sys.platform.startswith('linux') \
else _get_implementation.impls[sys.platform]
def _copy_to_clipboard(arg):
arg = str(globals().get(arg) or arg)
_get_implementation()(arg)
print('Copied to clipboard!')
@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