Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
copy to clipboard ipython magic
Add copy to clipboard from IPython!
To install, just copy it to your profile/startup directory, typically:
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
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()
a = NSArray.arrayWithObject_(arg)
elif sys.platform.startswith('linux'):
p = Popen(['xsel', '-pi'], stdin=PIPE)
print 'Copied to clipboard!'
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).


dedan commented Oct 30, 2014

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

this is great, something like this should be built in

Oh wow, this is the best thing ever! The only note is, use "xsel -ib", to copy to clipboard instead of primary selection, it's better that way for everyone.

OSError: [Errno 2] No such file or directory

vpontis commented Feb 8, 2016

Removed AppKit dependency for OS X: (only works for OS X)

jemshid commented Oct 24, 2016

One of the features I was looking forward with Ipython is to copy selected lines from history to my code editor with out using mouse. I have added one more function in your program to copy history of selected line to clipboard. I have made modification in two places in the file of Ipython. If any of you can guide, I would like to push / pass it to the developers.

cphyc commented Jul 5, 2017

I made a fork that supports python3: It's just a matter of adding () around the print statement…

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