一、使用 ImageGrab
只能读,只能是图片。
只能获取截图后的、或是网页上复制的图片内容,复制的图片文件不能获取。
from PIL import ImageGrab
img = ImageGrab.grabclipboard()
img.save('paste.png', 'PNG')
二、使用 NSPasteboard
可读可写,可以是字符串,可以是图片。
读
# 读剪切板数据的格式类型
data_type = pb.types()
print data_type
# 读剪切板字符串
if NSPasteboardTypeString in data_type:
str = pb.dataForType_(NSPasteboardTypeString)
print str
# 读剪切板的截图
if "public.png" in data_type:
img = pb.dataForType_("public.png")
# 读剪切板复制的图片文件名
if NSPasteboardTypePNG in data_type:
img = pb.dataForType_(NSPasteboardTypePNG)
print img
# 读剪切板复制的图片文件路径 url
if "public.file-url" in data_type:
img = pb.dataForType_("public.file-url")
print img
写
pb.clearContents()
# 写字符串 1
a = NSString.stringWithString_("hello world")
newData = a.nsstring().dataUsingEncoding_(NSUTF8StringEncoding)
pb.setData_forType_(newData, NSStringPboardType)
# 写字符串 2
a = NSArray.arrayWithObject_("hello world")
pb.writeObjects_(a)
# 写图片 1
imgNsData = NSData.alloc().initWithBytes_length_(img_bytes.getvalue(), img_bytes.tell())
imgNsImage = NSImage.alloc().initWithData_(imgNsData)
array = NSArray.arrayWithObject_(imgNsImage)
pb.writeObjects_(array)
# 写图片 2
imgNsData = NSData.dataWithBytes_length_(img_bytes.getvalue(), img_bytes.tell())
同上
Apple 的方法到 Python 的方法转换规律:
setData(_:forType:)
setData_forType_
init(bytes: UnsafeRawPointer?, length: Int)
initWithBytes_length_
三、使用 pyperclip、clipboard
可读可写,只能是字符串。
import pyperclip
# 写字符串
pyperclip.copy("hello gdeer")
# 读字符串
text = pyperclip.paste()

本文详细介绍了在不同平台下使用Python进行剪贴板读写的三种方法:使用ImageGrab读取图片,使用NSPasteboard进行字符串和图片的读写,以及使用pyperclip和clipboard模块操作字符串。每种方法都提供了代码示例,便于理解和实践。

5298

被折叠的 条评论
为什么被折叠?



