written by Nicolas Untz on 2016-12-02

I just found this cool little trick on Stack Overflow to send data from the Python interpreter to the Mac pasteboard. The use case for me was analyzing some large JSON objects and going back and forth between the interpreter and Vim, for my unicli project.

In your interpreter just add:

import subprocess

def write_to_clipboard(output):
    process = subprocess.Popen(
        'pbcopy', env={'LANG': 'en_US.UTF-8'}, stdin=subprocess.PIPE)
    process.communicate(output.encode('utf-8'))

Then, for example, to send the text result from the request:

write_to_clipboard(r.text)

Then switch to your favorite text editor to paste the content of the pasteboard. That's how I was able to easily use JSBeautify on the JSON objects to make them easier to read.