Skip to content Skip to sidebar Skip to footer

Accessing Alternate Clipboard Formats From Python

Copying to the clipboard from an application that supports rich text will typically add the text in several formats. I need to find out the available formats, and then retrieve the

Solution 1:

It's quite straightforward on OS X with the help of the module richxerox, available on pypi. It requires system support including the Apple AppKit and Foundation modules. I had trouble building Objective C for Python 3, so that initially I had only gotten this to work for Python 2. Anaconda 3 comes with all the necessary pieces preinstalled, however.

Here's a demo that prints the available clipboard types, and then fetches and prints each one:

import richxerox as rx

# Dump formats
verbose = Trueif verbose:
        print(rx.available(neat=False, dyn=True))
    else:
        print(rx.available())

# Dump contents in all formatsfor k, v in rx.pasteall(neat=False, dyn=True).items():
    line = "\n*** "+k+":  "+v
    print(line)

Output:

(
    "public.html",
    "public.utf8-plain-text"
)

*** public.html:  <html><head><metahttp-equiv="content-type"content="text/html; charset=utf-8"></head><body><ahref="http://coffeeghost.net/2010/10/09/pyperclip-a-cross-platform-clipboard-module-for-python/" 
  >pyperclip</a>: Looks interesting</body></html>

*** public.utf8-plain-text:  pyperclip: Looks interesting

To print in a desired format with fall-back to text, you could use this:

paste_format = "rtf"
content = rx.paste(paste_format)
if not content:
    content = rx.paste("text")

Or you could first check if a format is available:

if"public.rtf"in rx.available():
    content = rx.paste("rtf")
else:
    content = rx.paste("text")

Post a Comment for "Accessing Alternate Clipboard Formats From Python"