2009/3/22

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

#On my computer, these are in 
#/System/Library/Frameworks/Python.framework
#/Versions/Current/Extras/lib/python/PyObjC
import Foundation, AppKit

def pbcopy(s):
    "Copy string argument to clipboard"
    newStr = Foundation.NSString.stringWithString_(s).nsstring()
    newData = newStr.dataUsingEncoding_(Foundation.NSUTF8StringEncoding)
    board = AppKit.NSPasteboard.generalPasteboard()
    board.declareTypes_owner_([AppKit.NSStringPboardType], None)
    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.