Copying and pasting in Python on Mac OS X.

#! /usr/bin/env python

"""copy_paste: a module with two function, pbcopy and pbpaste. 
Relies on AppKit and Foundation frameworks from PyObjC."""

#Override warning about mismatched Foundation version you get in Py2.5
import warnings

import Foundation, AppKit

#And set warnings back to normal

def pbcopy(s):
    "Copy string argument to clipboard"
    board = AppKit.NSPasteboard.generalPasteboard()
    board.declareTypes_owner_([AppKit.NSStringPboardType], None)
    newStr = Foundation.NSString.stringWithString_(s)
    newData = \
    board.setData_forType_(newData, AppKit.NSStringPboardType)

def pbpaste():
    "Returns contents of clipboard"
    board = AppKit.NSPasteboard.generalPasteboard()
    content = board.stringForType_(AppKit.NSStringPboardType)
    return content

Alternative method for those without Foundation and Appkit:

import Carbon.Scrap
def pbcopy(arg):
    scrap = Carbon.Scrap.GetCurrentScrap()
    scrap.PutScrapFlavor('TEXT', 0, arg)

def pbpaste():
    scrap = Carbon.Scrap.GetCurrentScrap()
        return scrap.GetScrapFlavorData('TEXT')
        return ''

Also, note to OS X command line python users, put export LC_CTYPE=en_US.utf-8 in your .bash_profile and you'll be able to print non-ASCII characters in Terminal instead of getting an annoying UnicodeError.

changed September 19, 2007