forked from akkana/scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpyclip
executable file
·106 lines (83 loc) · 2.57 KB
/
pyclip
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#!/usr/bin/env python
import re
import sys
# First try with GTK
s = None
def get_selection_gtk2():
# print("Trying GTK2")
import gtk
primary = gtk.clipboard_get(gtk.gdk.SELECTION_PRIMARY)
if not primary.wait_is_text_available():
return ''
return primary.wait_for_text()
def get_selection_gtk3():
# print("Trying gi.repository Gtk")
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk
primary = Gtk.Clipboard.get(Gdk.SELECTION_PRIMARY)
if not primary.wait_is_text_available():
sys.exit(0)
return primary.wait_for_text()
def get_selection_qt():
print("Trying Qt")
# In Python2 QApplication is inPyQt5. QtCore
# from PyQt5.QtCore import QApplication
# In Python3 QApplication is in QtWidgets
from PyQt5.QtWidgets import QApplication
app = QApplication(sys.argv)
qc = app.clipboard()
return qc.text(qc.Selection)
# Use qc.Clipboard if you want the clipboard selection
def get_selection_tk():
try:
# Python 3 import:
import tkinter
except ImportError:
# Python 2 import:
import Tkinter as tkinter
tk = tkinter.Tk()
tk.withdraw()
s = tk.selection_get()
# In Tk, you have to create a window to get the selection,
# but you don't have to show it.
tk.update() # Stops a few errors (clipboard text unchanged, command line program unresponsive, window not destroyed).
tk.destroy()
return s
def fix_links(s):
"""When running this to paste URLs, it's helpful to stitch together
multiple lines.
"""
# eliminate newlines, and any spaces immediately following a newline:
return re.sub(r'[\r\n]+ *', '', s)
def get_selection():
debug = False
if debug:
import traceback
# The order in which to try toolkits:
tries = [
("GTK2", get_selection_gtk2),
("GTK3", get_selection_gtk3),
("Tk", get_selection_tk),
("Qt", get_selection_qt),
]
selection_string = None
for t in tries:
try:
selection_string = t[1]()
if debug:
print("Success with %s" % t[0])
except Exception as e:
if debug:
print(traceback.format_exc())
print("^^^^^^ Couldn't use %s" % t[0])
if selection_string != None:
break
if selection_string == None:
print("Nothing worked, sorry")
sys.exit(1)
else:
print(selection_string)
sys.exit(0)
if __name__ == '__main__':
get_selection()