Skip to content

Instantly share code, notes, and snippets.

@iwconfig
Forked from bwagner/clip_magic.py
Last active November 9, 2019 17:46
Show Gist options
  • Save iwconfig/b99be1e29c08a3ff270159e4366a8081 to your computer and use it in GitHub Desktop.
Save iwconfig/b99be1e29c08a3ff270159e4366a8081 to your computer and use it in GitHub Desktop.
copy to clipboard ipython magic -- linux only
"""
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
This version removes the dependency of AppKit, but maintains compatibility with linux and osx.
Using ideas from: https://gist.github.com/vpontis/46e5d3154cda92ce3e0f
This is a fork of https://gist.github.com/bwagner/270da7c7d31af7ffaca32674557fc172
The function `_get_implementation` was not working, so instead of fixing the issue I simply removed it,
since I only use Linux anyway.
I had to add `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
def _copy_to_clipboard(arg):
arg = str(globals().get(arg) or arg)
p = Popen(['xsel', '-ib'], stdin=PIPE, universal_newlines=True) # Read note above
p.communicate(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