How to share clipboard data beetween processes in GTK?

你离开我真会死。 提交于 2019-12-25 00:15:12

问题


I want to:

  1. put some text into clipboard
  2. end my program
  3. paste data into other application

but my code is not working:

#!/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)

I put text into clipboard by executing python2 ./test.py put and after that i want to get ext from clipboard with python2 ./test.py get.

Why clipboard.wait_for_text() always return None?


回答1:


you have to enter main loop to let the clipboard manager get the text (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()  



回答2:


For 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")


来源:https://stackoverflow.com/questions/53675434/how-to-share-clipboard-data-beetween-processes-in-gtk

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!