mbvee
mbvee

Reputation: 391

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.

Upvotes: 4

Views: 2705

Answers (4)

Else Ifthen
Else Ifthen

Reputation: 155

For Linux using kde plasma, there is a quite elegant (IMO) way to get the clipboard history items that are present in kde's default clipboard manager klipper:

import dbus

class Clipboard():
    def __init__(self):
        session_bus = dbus.SessionBus()
        self.clipboard_manager = session_bus.get_object('org.kde.klipper', '/klipper')

def __getitem__(self, item=0):
    return self.clipboard_manager.getClipboardHistoryItem(item)

def __call__(self, content):
    self.clipboard_manager.setClipboardContents(content)


# create a clipboard instance:
clip = Clipboard()

# get item from history by subscripting the object
# 0 is current, 1 is previous etc. e.g.
print(clip[0])
print(clip[1])

# set current clipboard content by calling the object, e.g.
clip(clip[0] + clip[1])

Upvotes: 0

kwyntes
kwyntes

Reputation: 1302

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.

Upvotes: 1

Mark Mikealson
Mark Mikealson

Reputation: 29

Use the external module called pyperclip

import pyperclip
pyperclip.copy("abc")  # now the clipboard content will be string "abc"
text = pyperclip.paste()  # text will have the content of clipboard

Documentation | Github

Upvotes: -1

MBS
MBS

Reputation: 87

pyperclip is a great for copying from and pasting to the clipboard.

import pyperclip result = pyperclip.paste() print(result)

Upvotes: -2

Related Questions