How to write a Unicode string to the Mac clipboard:
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'))
How to read a Unicode string from the Mac clipboard:
import subprocess
def 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 pyperclip
python -c 'import pyperclip; pyperclip.copy("私はDavid!??")' # copy
python -c 'import pyperclip; print(repr(pyperclip.paste()))' # paste
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…