[英]Python get mac clipboard contents
How can I, using Python (2.7) get the contents of the Mac clipboard.我如何使用 Python (2.7) 获取 Mac 剪贴板的内容。 Is there a better way than making a wrapper around pbpaste?
有没有比在 pbpaste 周围制作包装更好的方法?
Thanks!谢谢!
PyObjC is the way to go: PyObjC 是 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.这仅支持文本,否则将返回
None
。 You can extend it to support other data types as well, see NSPastboard Class Reference .您也可以扩展它以支持其他数据类型,请参阅NSPastboard Class 参考。
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.我为“获取 Mac 剪贴板的内容”找到的
xerox
模块和大多数代码示例的问题是它们只返回纯文本。 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.他们不支持超链接、styles 等,因此他们无法真正访问 Microsoft Word 和 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 .生成的
richxerox
模块在PyPI和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.虽然这个问题很老,但我在这里留下了面包屑,因为我在搜索答案时一直通过谷歌重新找到这个页面。
If you have installed pandas, you can use the function in pandas as follows:如果你已经安装了pandas,你可以使用pandas中的function如下:
from pandas.io.clipboard import clipboard_get
text = clipboard_get()
Do you know PyObjC ?你知道PyObjC吗? I guess you could use it to write a Py wrapper which interfaces with NSPasteboard .
我想你可以用它来编写一个与NSPasteboard接口的 Py 包装器。 This might be more "elegant" than shelling out to pbpaste.
这可能比使用 pbpaste 更“优雅”。
You can grab the clipboard (and the screen) with PIL/Pillow on a Mac like this:您可以在 Mac 上使用 PIL/Pillow 抓取剪贴板(和屏幕),如下所示:
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.