copy_paste.py

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

warnings.filterwarnings("ignore")
import Foundation, AppKit

#And set warnings back to normal
warnings.resetwarnings()

def pbcopy(s):
    "Copy string argument to clipboard"
    board = AppKit.NSPasteboard.generalPasteboard()
    board.declareTypes_owner_([AppKit.NSStringPboardType], None)
    newStr = Foundation.NSString.stringWithString_(s)
    newData = \
        newStr.nsstring().dataUsingEncoding_(Foundation.NSUTF8StringEncoding)
    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):
    Carbon.Scrap.ClearCurrentScrap()
    scrap = Carbon.Scrap.GetCurrentScrap()
    scrap.PutScrapFlavor('TEXT', 0, arg)

def pbpaste():
    scrap = Carbon.Scrap.GetCurrentScrap()
    try:
        return scrap.GetScrapFlavorData('TEXT')
    except:
        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