Skip to content

Instantly share code, notes, and snippets.

@while0pass
Forked from nova77/clip_magic.py
Last active August 29, 2015 14:24
Show Gist options
  • Save while0pass/7aa1836b98e2bdfeb8e3 to your computer and use it in GitHub Desktop.
Save while0pass/7aa1836b98e2bdfeb8e3 to your computer and use it in GitHub Desktop.

Revisions

  1. @nova77 nova77 created this gist Apr 17, 2013.
    65 changes: 65 additions & 0 deletions clip_magic.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,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