我希望我的Python脚本能够通过x11复制和粘贴剪贴板(以便在Linux上使用)。有人可以指导我查看具体资源或我需要掌握的概念吗?
这是否可以使用Python X库在http://python-xlib.sourceforge.net中实现?
这是否可以使用Python X库在http://python-xlib.sourceforge.net中实现?
Tkinter基础解决方案提到在Cameron Laird的答案中:
import Tkinter
root = Tkinter.Tk()
print(root.selection_get(selection="CLIPBOARD"))
PRIMARY
选择而不是剪贴板。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") )
data = event.widget.selection_get(selection="CLIPBOARD"))
clipboard
模块首先,使用pip3
安装clipboard
模块:
$ sudo pip3 install clipboard
使用这个跨平台模块(Linux、Mac、Windows)非常简单:
import clipboard
clipboard.copy('text') # Copy to the clipboard.
text = clipboard.paste() # Copy from the clipboard.
https://github.com/asweigart/pyperclip
。 - am70
xlib
或下面所述的其他解决方案将仅复制/粘贴文本;而现在大多数应用程序还可以复制/粘贴图像或其他格式:对于这些情况,您可能需要使用gtk
或qt
库。此外,在大多数应用程序中,使用中间鼠标按钮而不是ctrl-v来粘贴X11剪贴板。 - am70