Copy data from the clipboard on Linux, Mac and Windows with a single Python script

不羁岁月 提交于 2019-11-30 16:00:48

You could use a GUI toolkit such as Qt to get a portable clipboard API. That said it might be a little overkill to use a whole GUI toolkit just for this. (Unless, of course, you're also going to use it to make a GUI.)

That said, clipboard APIs dealing with plain text should be reasonably simple to make your own abstraction over.

For instance, on OS X you can use PyObjC (which is installed along with OS X) to get plain-text contents of a clipboard:

from AppKit import NSPasteboard
from LaunchServices import 
pb = NSPasteboard.generalPasteboard()
text = pb.stringForType_(kUTTypeUTF8PlainText)

CPU architectures

A 32-bit native app on a 64-bit OS will be accessing the same clipboard as a 64-bit one. If you need to support both architectures of an OS, and aren't writing a driver, for Windows it's okay to ship a 32-bit binary; for Linux you'll likely have to do both versions; for OS X, it should be reasonably safe to ship a 64-bit version, all Macs since mid-2007 have had 64-bit CPUs and the OS support is there since Leopard. A Python script will, on Linux, probably be executed by a Python installation from the distribution package manager, whose bitness will match the system, so you don't necessarily need to worry about that.

The xerox library supports Linux, Mac OS X, and Windows.

Note that it's a very bad idea to perform any action in short (< a minute) intervals, because that makes modern processors wake up regularily. You may want to use the respective operating system's APIs to register a callback once the clipboard changes.

You're probably better off using a more advanced gui toolkit than Tk, but it's in the standard library, so it's available everywhere.

As a really simple example:

import Tkinter
root = Tkinter.Tk()
root.withdraw() # Hide the main window (optional)
text_in_clipboard = root.clipboard_get()
print text_in_clipboard

Polling is NOT robust/reliable.

You cannot determine if data has changed (on windows anyway) without pasting it into a buffer for inspection. This requires opening the clipboard. If you do this in a loop, you're going to collide with other apps. i.e. the app where the user is copying another item onto the clipboard. This will explode with an "cannot open clipboard" or "out of memory" error. This approach will not work reliably/robustly. You need to use proper clipboard monitoring APIs in the various platforms.

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