我正在尝试在我的 Mac Lion 上使用 Python 脚本获取剪贴板内容。
我正在搜索一个事件或类似的东西,因为如果我使用循环,我的应用程序会把所有时间都花在查看剪贴板上。
有什么想法吗?
最佳答案
您是否考虑过使用无限循环并在两次尝试之间“休眠”? 我用了pyperclip对于一个简单的 PoC,它的工作就像一个魅力,以及 Windows 和 Linux。
import time
import sys
import os
sys.path.append(os.path.abspath("SO_site-packages"))
import pyperclip
recent_value = ""
while True:
tmp_value = pyperclip.paste()
if tmp_value != recent_value:
recent_value = tmp_value
print("Value changed: %s" % str(recent_value)[:20])
time.sleep(0.1)
代替 print
,做任何你想做的事。如果您需要多线程方面的帮助以将其放入后台线程,请告诉我。
编辑
这是一个完整的多线程示例。
import time
import threading
import pyperclip
def is_url_but_not_bitly(url):
if url.startswith("http://") and not "bit.ly" in url:
return True
return False
def print_to_stdout(clipboard_content):
print ("Found url: %s" % str(clipboard_content))
class ClipboardWatcher(threading.Thread):
def __init__(self, predicate, callback, pause=5.):
super(ClipboardWatcher, self).__init__()
self._predicate = predicate
self._callback = callback
self._pause = pause
self._stopping = False
def run(self):
recent_value = ""
while not self._stopping:
tmp_value = pyperclip.paste()
if tmp_value != recent_value:
recent_value = tmp_value
if self._predicate(recent_value):
self._callback(recent_value)
time.sleep(self._pause)
def stop(self):
self._stopping = True
def main():
watcher = ClipboardWatcher(is_url_but_not_bitly,
print_to_stdout,
5.)
watcher.start()
while True:
try:
print("Waiting for changed clipboard...")
time.sleep(10)
except KeyboardInterrupt:
watcher.stop()
break
if __name__ == "__main__":
main()
我创建了一个 threading.Thread 的子类,覆盖了方法 run
和 __init__
并创建了这个类的一个实例。通过调用 watcher.start()
(不是 run()
!),您可以启动线程。
为了安全地停止线程,我等待 -c(键盘中断)并告诉线程自行停止。
在类的初始化中,你还有一个参数pause
来控制尝试之间等待的时间。
像我的示例一样使用 ClipboardWatcher 类,将回调替换为您所做的,例如,lambda x: bitly(x, username, password)
。
关于python - 剪贴板内容改变时触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14685999/