Can python send text to the Mac clipboard Can python send text to the Mac clipboard python python

Can python send text to the Mac clipboard


How to write a Unicode string to the Mac clipboard:

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

How to read a Unicode string from the Mac clipboard:

import subprocessdef read_from_clipboard():    return subprocess.check_output(        'pbpaste', env={'LANG': 'en_US.UTF-8'}).decode('utf-8')

Works on both Python 2.7 and Python 3.4.

2021 Update: If you need to be able to read the clipboard on other operating systems and not just Mac and are okay with adding an external library, pyperclip also seems to work well. I tested it on Mac with Unicode text:

python -m pip install pyperclippython -c 'import pyperclip; pyperclip.copy("私はDavid!🙂")'  # copypython -c 'import pyperclip; print(repr(pyperclip.paste()))'  # paste


A simple way:

cmd = 'echo %s | tr -d "\n" | pbcopy' % stros.system(cmd)

A cross-platform way:
https://stackoverflow.com/a/4203897/805627

from Tkinter import Tkr = Tk()r.withdraw()r.clipboard_clear()r.clipboard_append('i can has clipboardz?')r.destroy()


The following code use PyObjC (https://pyobjc.readthedocs.io)

from AppKit import NSPasteboard, NSArraypb = NSPasteboard.generalPasteboard()pb.clearContents()a = NSArray.arrayWithObject_("hello world")pb.writeObjects_(a)

As explained in Cocoa documentation, copying requires three step :

  • get the pasteboard
  • clear it
  • fill it

You fill the pasteboard with an array of object (here a contains only one string).