Skip to content

Instantly share code, notes, and snippets.

@amagee
Created December 7, 2016 05:02
Show Gist options
  • Save amagee/7ab4de3762b567e850119337fab00dff to your computer and use it in GitHub Desktop.
Save amagee/7ab4de3762b567e850119337fab00dff to your computer and use it in GitHub Desktop.
IPython: copy a variable to the clipboard as JSON
# Inspiration from https://gist.github.com/nova77/5403446
# Docs from http://ipython.readthedocs.io/en/stable/config/custommagics.html
from IPython.core.magic import Magics, magics_class, line_magic
from subprocess import Popen, PIPE
import json
@magics_class
class ClipJsonMagic(Magics):
@line_magic
def clip_json(self, line):
val = json.dumps(self.shell.user_ns[line], indent=4)
p = Popen(['xsel', '-ib'], stdin=PIPE)
p.communicate(input=val.encode())
get_ipython().register_magics(ClipJsonMagic)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment