Can python send text to the Mac clipboard
Question
I'd like my python program to place some text in the Mac clipboard.
Is this possible?
Solution
New answer:
This page suggests:
Implementation for All Mac OS X Versions
The other Mac module (MacSharedClipboard.py, in Listing 4) implements the clipboard interface on top of two command-line programs called pbcopy (which copies text into the clipboard) and pbpaste (which pastes whatever text is in the clipboard). The prefix "pb" stands for "pasteboard," the Mac term for clipboard.
Old answer:
Apparently so:
http://code.activestate.com/recipes/410615/
is a simple script demonstrating how to do it.
Edit: Just realised this relies on Carbon, so might not be ideal... depends a bit what you're using it for.
OTHER TIPS
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.
The following code use PyObjC (http://pyobjc.sourceforge.net/)
from AppKit import NSPasteboard, NSArray
pb = 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).
A simple way:
cmd = 'echo %s | tr -d "\n" | pbcopy' % str
os.system(cmd)
A cross-platform way:
https://stackoverflow.com/a/4203897/805627
from Tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.destroy()
I know this is an older post, but I have found a very elegant solution to this problem.
There is a library named PyClip, which can be found at https://github.com/georgefs/pyclip-copycat.
The syntax is pretty simple (example from the Github repo):
import clipboard
# copy some text to the clipboard
clipboard.copy('blah blah blah')
# get the text currently held in the clipboard
text = clipboard.paste()
once you've passed clipboard.copy('foo')
you can just cmd + v to get the text
if you just wanted to put text into the mac clipboard, you could use the shell's pbcopy command.