Python如何访问X11剪贴板?

Alv*_*ith 10 python x11 clipboard copy paste

我希望我的Python脚本能够通过x11复制和粘贴到剪贴板(因此它可以在Linux上运行).任何人都能指出我可以看到的具体资源,或者我必须掌握的概念吗?

这可能与http://python-xlib.sourceforge.net上的Python X库有关吗?

x11*_*ser 6

Cameron Laird 的回答中提到的基于 Tkinter 的解决方案

import Tkinter
root = Tkinter.Tk()
print(root.selection_get(selection="CLIPBOARD"))
Run Code Online (Sandbox Code Playgroud)

用“PRIMARY”替换“CLIPBOARD”以获得PRIMARY选择。

另请参阅此答案

python-xlib 解决方案,基于PrintSelection()python-xlib/examples/get_selection.py

from Xlib import X, display as Xdisplay

def property2str(display, prop):
    if prop.property_type == display.get_atom("STRING"):
        return prop.value.decode('ISO-8859-1')
    elif prop.property_type == display.get_atom("UTF8_STRING"):
        return prop.value.decode('UTF-8')
    else:
        return "".join(str(c) for c in prop.value)

def get_selection(display, window, bufname, typename):
    bufid = display.get_atom(bufname)
    typeid = display.get_atom(typename)
    propid = display.get_atom('XSEL_DATA')
    incrid = display.get_atom('INCR')

    window.change_attributes(event_mask = X.PropertyChangeMask)
    window.convert_selection(bufid, typeid, propid, X.CurrentTime)
    while True:
        ev = display.next_event()
        if ev.type == X.SelectionNotify and ev.selection == bufid:
            break

    if ev.property == X.NONE:
        return None # request failed, e.g. owner can't convert to target format type
    else:
        prop = window.get_property(propid, X.AnyPropertyType, 0, 2**31-1, 1)

        if prop.property_type == incrid:
            result = ""
            while True:
                while True:
                    ev = display.next_event()
                    if ev.type == X.PropertyNotify and ev.atom == propid and ev.state == X.PropertyNewValue:
                        break

                prop = window.get_property(propid, X.AnyPropertyType, 0, 2**31-1, 1)
                if len(prop.value) == 0:
                    break

                result += property2str(display, prop)
            return result
        else:
            return property2str(display, prop)

display = Xdisplay.Display()
window = display.screen().root.create_window(0,0, 1,1, 0, X.CopyFromParent)
print( get_selection(display, window, "CLIPBOARD", "UTF8_STRING") or \
       get_selection(display, window, "CLIPBOARD", "STRING") )
Run Code Online (Sandbox Code Playgroud)


Mar*_*ark 1

您可以使用 pygtk 来完成此操作。一个干净的解决方案,但可能有点矫枉过正,具体取决于您的应用程序。

另一种获得一些google搜索结果的方法是对xsel进行系统调用。