[英]Store clipboard history in file using Python on mac
我需要从文本中复制一些单词,我想将复制的单词存储在文件中。 基本上是带有剪贴板历史记录的文件。
由于单词的复制是一个连续的过程,因此我需要使用一个循环来在演奏过程中存储复制的单词。 我认为使用动作/事件侦听器来方便地进行以下操作:1)在按下cmd + x时将剪贴板数据存储到文件中,以及2)在按下cmd + q时结束循环。
我对动作/事件侦听器不是很熟悉,也不确定如何使用它们。 我可以使用任何简单的实现方式吗?
我主要使用的是伪代码,它描述了我想要完成的工作。 任何建议表示赞赏!
import pyperclip
import os
import os.path
import time
save_path = "/Users/username/file"
FileName = os.path.join(save_path, "clipboard.txt")
f= open(FileName, "w")
text = pyperclip.paste() # text will have the content of clipboard
x = 0
while True:
time.sleep(2) #Replace with-->: wait for "cmd + x" to be pressed
text = pyperclip.paste() # text will have the content of clipboard
f.write(text+"\n")
x += 1
if x > 10: #Replace with --> break if "cmd + q" is pressed
break
f.close()
print("End of session")
上面的代码等待2秒钟,然后将文本从剪贴板复制到文件。 循环经过10次迭代后到达终点。
我希望代码对执行的动作做出反应,以便将所有复制的单词存储到单个文件中。
编辑:使用对问题的答复中的建议,我尝试以两种方式解决问题,一种是使用键盘和Pynput模块。 键盘对我不起作用,可能是由于我使用Mac? 按下键时,它没有按预期的方式反应。
while True:
try:
if keyboard.is_pressed('c'):
print('Copying the selected')
text = pyperclip.paste() # text will have the content of clipboard
f.write(text+"\n")
sleep(0.1) # Avoiding long press, remove to see effect
# Your Code
elif keyboard.is_pressed('esc'):
print('Exiting Code')
break
except Exception as error:
print(error)
f.close()
问题:按下键“ c”时,没有任何反应。 打印语句不会激活。
def on_release(key):
if str(key) == "'c'":
print('Copying the slected')
text = pyperclip.paste() # text will have the content of clipboard
f.write(text+"\n")
print('{0} release'.format(
key))
if key == Key.esc:
# Stop listener
f.close()
print("End")
return False
# Collect events until released
with Listener(
on_release=on_release) as listener:
listener.join()
pynput可以按预期方式工作,每次按下“ c”键时(就像使用cmd + c进行复制时一样),它会将剪贴板中当前存储的文本复制到文本文件中。
(未成年人)问题:我并没有对同时按下cmd + c的组合产生反应。 但是,在这种情况下这并不重要,因为对按键“ c”作出反应就足够了。 但是,对于将来的参考,如果您知道如何听组合键,请发表评论。
我尝试了以下方法,但没有一个起作用:
if key == Key.cmd and str(key) == "'c'":
print('Copying the selected')
和
if key == Key.cmd:
if str(key) == "'c'":
print('Copying the selected')
在这种情况下,您应该为python使用键盘库https://pypi.org/project/keyboard/
您的代码的基本结构如下所示
import keyboard
from time import sleep
while True:
try:
if keyboard.is_pressed('ctrl+c'):
print('Copying the slected')
sleep(0.1) # Avoiding long press, remove to see effect
# Your Code
elif keyboard.is_pressed('esc'):
print('Exiting Code')
break
except Exception as error:
print(error)
您可以尝试使用pynput,该函数支持映射任意自定义函数的多组合键,只需将它们放入字典即可:
def multi_hotkey_listen(hotkey_dict):
"""Multi-hotkey listen"""
# Create a mapping of hot keys to function, use hashable frozenset as keys
# Original set type is not hashable - so they can't be used as keys of dict
frozen_hotkey_dict = {frozenset(k.split('+')): v for k, v in hotkey_dict.items()}
# Currently pressed keys
current_keys = set()
def on_press(key):
"""When a key is pressed, add it to the set we are keeping track of
and check if this set is in the dictionary"""
try:
key_str = key.char
except AttributeError:
key_str = key.name
current_keys.add(key_str)
# print(current_keys)
if frozenset(current_keys) in frozen_hotkey_dict:
# If the current set of keys are in the mapping, execute the function
trigger_func = frozen_hotkey_dict[frozenset(current_keys)]
print(f'Success:function {trigger_func.__name__} be triggered', )
trigger_func()
def on_release(key):
"""When a key is released, remove it from the set of keys we are keeping track of"""
try:
key_str = key.char
except AttributeError:
key_str = key.name
current_keys.remove(key_str)
with KeyboardListener(on_press=on_press, on_release=on_release, suppress=False) as listener:
listener.join()
hotkey_dict = {
'cmd+x': save_data # support combination key like ctrl+shift+1
'cmd+q': end_loop,
}
multi_hotkey_listen(hotkey_dict)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.