Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clipboard history using python

I am tying to access the clipboard contents using python. I am using the below python script to perform the action.

from tkinter import Tk
r = Tk()
result = r.selection_get(selection="CLIPBOARD")
print(result)

The above snippet helps in fetching the contents that are available in the clipboard currently. My requirement is to fetch the clipboard history completely.

Any suggestions regarding this will be really helpful.

like image 866
mbvee Avatar asked Aug 25 '26 16:08

mbvee


1 Answers

Assuming you're on Windows and have clipboard history enabled, you can retrieve the clipboard history using Clipboard.GetHistoryItemsAsync. This method can be called from Python through pywinrt:

# requires: (> pip install ...)
# winrt-Windows.Foundation
# winrt-Windows.Foundation.Collections
# winrt-Windows.ApplicationModel.DataTransfer

import winrt.windows.applicationmodel.datatransfer as w_am_dt
import asyncio

async def cliphist():
    result = await w_am_dt.Clipboard.get_history_items_async()
    return [await item.content.get_text_async() for item in result.items or []
            if item.content and item.content.contains('Text')]

hist = asyncio.run(cliphist())

print(hist)
# => ['item 1', 'item 2', ...]

Note that this only retrieves text. If you want to get different formats, look at the documentation for DataPackageView (which is what item.content is) on how to get the desired data from each item.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!