Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can python send text to the Mac clipboard

I'd like my python program to place some text in the Mac clipboard.

Is this possible?

like image 501
David Sykes Avatar asked Dec 01 '09 11:12

David Sykes


People also ask

Can Python access the clipboard?

Pyperclip is a cross-platform Python module for copy and paste clipboard functions. It works with both Python 2 and 3.

How read data from clipboard in Python?

You can use the module called win32clipboard, which is part of pywin32. An important reminder from the documentation: When the window has finished examining or changing the clipboard, close the clipboard by calling CloseClipboard. This enables other windows to access the clipboard.

Does Mac terminal support Python?

On a Mac system, it is very straight-forward. All you need to do is open Launchpad and search for Terminal , and in the terminal, type Python and boom, it will give you an output with the Python version.


1 Answers

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 
like image 176
David Foster Avatar answered Sep 27 '22 21:09

David Foster