无法使用PyObjC访问NSPasteboard

时间:2014-09-05 18:39:46

标签: python objective-c pyobjc

我试图使用PyObjC读取OSX剪贴板。

在python shell里面

import AppKit
>>> clip = AppKit.NSPasteboard.generalPasteboard()
>>> dir(clip)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

缺少许多粘贴板属性。所以clip.stringForType_(AppKit.NSStringPboardType)会导致AttributeError。

1 个答案:

答案 0 :(得分:1)

这里有一些python,它将从剪贴板中以纯文本形式读取。如果要包含其他类型,则将它们添加到数组myFavouriteTypes(并使用dataForType)。

from AppKit import NSPasteboard, NSStringPboardType 

myFavoriteTypes = [NSStringPboardType]
pb = NSPasteboard.generalPasteboard()
best_type = pb.availableTypeFromArray_(myFavoriteTypes)
if best_type:
    clipString = pb.stringForType_(best_type)
    if clipString:
        print (clipString)  
else:
    print ("No clipboard image data was retrieved.")
    print ("These types were available:")
    print (pb.types())