Wednesday, December 12, 2012

Copying text via Python on OS X

It took me an embarrassingly long time to figure out why I was getting an extra newline character appended to the copied text. (It was because I forgot to include the -n parameter to echo.)

from subprocess import Popen, PIPE

def copy_to_clipboard(self, text):
    # equivalent to: echo "text" | pbcopy
    p1 = Popen(['/bin/echo', '-n', text], stdout=PIPE)
    p2 = Popen(['/usr/bin/pbcopy'], stdin=p1.stdout, stdout=PIPE, stderr=PIPE)
    p2.communicate()

def get_clipboard_text(self):
    return Popen(['/usr/bin/pbpaste', '-Prefer', 'txt'], stdin=PIPE, stdout=PIPE, stderr=PIPE).communicate()[0]

No comments:

Post a Comment