Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

copy to clipboard ipython magic

View clip_magic.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
"""
Add copy to clipboard from IPython!
To install, just copy it to your profile/startup directory, typically:
~/.ipython/profile_default/startup/
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
"""
 
import sys
 
if sys.platform == 'darwin':
from AppKit import NSPasteboard, NSArray
elif sys.platform.startswith('linux'):
from subprocess import Popen, PIPE
else:
raise ImportError("Clip magic only works on osx or linux!")
 
from IPython.core.magic import register_line_cell_magic
 
def _copy_to_clipboard(arg):
arg = str(globals().get(arg) or arg)
 
if sys.platform == 'darwin':
pb = NSPasteboard.generalPasteboard()
pb.clearContents()
a = NSArray.arrayWithObject_(arg)
pb.writeObjects_(a)
elif sys.platform.startswith('linux'):
p = Popen(['xsel', '-pi'], stdin=PIPE)
p.communicate(input=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

Hi, thanks for the script. If anyone wants Python 3 compatibility then change the communicate line to "p.communicate(input=bytes(arg, 'utf-8'))" as communicate needs bytes not unicode. Also on Linux I had to use '-bi' rather than '-pi' (using Linux Mint 64bit).

Windows?

It does not work on ipython 2.3.0, is it possible that the way how cell magic functions are registered has changed? I can't find documentation for the decorators you are using. I'll try to fix it and send you a pull request

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.