Accessing alternate clipboard formats from python

后端 未结 1 1584
夕颜
夕颜 2021-02-05 16:33

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

1条回答
  •  抹茶落季
    2021-02-05 17:02

    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 = True
    if verbose:
            print(rx.available(neat=False, dyn=True))
        else:
            print(rx.available())
    
    # Dump contents in all formats
    for 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:  
      pyperclip: Looks interesting
    
    *** 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")
    

    0 讨论(0)
提交回复
热议问题