views:

369

answers:

2

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

Is this possible?

+6  A: 

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.

mavnn
I never thought of using a command line tool. Perfect, thanks
David Sykes
+1  A: 

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).

FabienAndre