Python get mac clipboard contents

别等时光非礼了梦想. 提交于 2019-12-20 09:57:38

问题


How can I, using Python (2.7) get the contents of the Mac clipboard. Is there a better way than making a wrapper around pbpaste?

Thanks!


回答1:


PyObjC is the way to go:

#!/usr/bin/python

from AppKit import NSPasteboard, NSStringPboardType

pb = NSPasteboard.generalPasteboard()
pbstring = pb.stringForType_(NSStringPboardType)
print u"Pastboard string: %s".encode("utf-8") % repr(pbstring)

This only supports text and will return None otherwise. You can extend it to support other data types as well, see NSPastboard Class Reference.




回答2:


Have you looked at the xerox module?
It is supposed to support windows, OS X and Linux


Usage is as follows:

xerox.copy(u'some string')

And to paste:

>>> xerox.paste()
u'some string'




回答3:


The problem with the xerox module and most code samples I've found for "get the contents of the Mac clipboard" is that they return plain text only. They don't support hyperlinks, styles, and such, so they're not really able to access the full contents provided by apps like Microsoft Word and Google Chrome.

Standing on the shoulders of others, I finally figured out how to do this. The resulting richxerox module is available on PyPI and Bitbucket.

Though this question is old, I'm leaving breadcrumbs here because I consistently re-found this page via Google while searching for the answer.




回答4:


Do you know PyObjC? I guess you could use it to write a Py wrapper which interfaces with NSPasteboard. This might be more "elegant" than shelling out to pbpaste.




回答5:


You can grab the clipboard (and the screen) with PIL/Pillow on a Mac like this:

from PIL import ImageGrab, Image

# Grab clipboard and save to disk
clip = ImageGrab.grabclipboard()
clip.save("clip.png")

Just for completeness, you can grab the screen like this:

screen = ImageGrab.grab()

# That results in this:
# <PIL.PngImagePlugin.PngImageFile image mode=RGBA size=5120x2880 at 0x110BB7748>

# Save to disk
screen.save("screen.png")


来源:https://stackoverflow.com/questions/7083313/python-get-mac-clipboard-contents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!