如何在 GTK 中的进程之间共享剪贴板数据?

How to share clipboard data beetween processes in GTK?

我想:

  1. 将一些文本放入剪贴板
  2. 结束我的程序
  3. 将数据粘贴到其他应用程序

但我的代码不起作用:

#!/usr/bin/env python

import sys
import gtk

if __name__ == '__main__':
    if sys.argv[1] == 'put':
        clipboard = gtk.clipboard_get()
        clipboard.set_text('It\'s working')
        clipboard.store()
    elif sys.argv[1] == 'get':
        clipboard = gtk.clipboard_get()
        text = clipboard.wait_for_text()
        print('Text from clipboard: ', text)

我通过执行 python2 ./test.py put 将文本放入剪贴板,然后我想使用 python2 ./test.py get 从剪贴板获取分机。

为什么 clipboard.wait_for_text() 总是 return None?

您必须进入主循环才能让剪贴板管理器获取文本(Effect of PyGTK clipboard set_text persists only while process is running)

#!/usr/bin/env python

import sys
import gtk, gobject


if __name__ == '__main__':
    if sys.argv[1] == 'put':
        clipboard = gtk.clipboard_get()
        clipboard.set_text('It\'s working')
        clipboard.store()
    elif sys.argv[1] == 'get':
        clipboard = gtk.clipboard_get()
        text = clipboard.wait_for_text()
        if text == None:
            print("empty text")
        else:
            print('Text from clipboard: ', text)
gobject.timeout_add(100, gtk.main_quit)
gtk.main()  

对于 GTK3:

#!/usr/bin/env python3

import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk

class CopyToClipboard(Gtk.Window):
    def __init__(self, text):
        super(CopyToClipboard, self).__init__()
        clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
        clipboard.set_text(text, -1)
        clipboard.store()

CopyToClipboard("your text goes here\n")