Skip to content

Instantly share code, notes, and snippets.

@aeris
Created August 9, 2012 23:21
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aeris/3308963 to your computer and use it in GitHub Desktop.
Save aeris/3308963 to your computer and use it in GitHub Desktop.
Copy/paste from command line with Klipper
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
import argparse, dbus, sys
bus = dbus.SessionBus()
klipper = bus.get_object('org.kde.klipper', '/klipper')
klipper = dbus.Interface(klipper, dbus_interface='org.kde.klipper.klipper')
parser = argparse.ArgumentParser()
parser.add_argument("-i", "--item", type=int, nargs="?", const=0,
help="get the Nth item in clipboard history", metavar="N")
parser.add_argument("-x", "--clear", action="store_true", default=False,
help="clear the clipboard history")
parser.add_argument("args", nargs="?")
args = parser.parse_args()
if args.clear:
klipper.clearClipboardHistory()
elif args.item is not None:
sys.stdout.write(klipper.getClipboardHistoryItem(args.item))
else:
if not args.args:
content = sys.stdin.read()
else:
file = open(args.args, "r")
content = file.read()
file.close()
klipper.setClipboardContents(content)
@zarinfam
Copy link

Very nice, thank you so much. I had copied about 100 MB text into clipboard and my klipper was hanged.

@BlackCatDevel0per
Copy link

BlackCatDevel0per commented Dec 24, 2023

Might be useful (from qdbusviewer):

import sys
import dbus

bus = dbus.SessionBus()
clipboard = bus.get_object("org.kde.klipper", "/klipper")
klipper = dbus.Interface(clipboard, "org.kde.klipper.klipper")

clipboard_entries = klipper.getClipboardHistoryMenu()

for index, entry in enumerate(clipboard_entries):
    if index == int(sys.argv[1]):
        break
    print(index, entry)

Usage:

python iter_clipboard.py 45

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment