简体   繁体   English

在Mac上使用Python将剪贴板历史记录存储在文件中

[英]Store clipboard history in file using Python on mac

I need copy some words from a text and I would like to store the copied words in a file. 我需要从文本中复制一些单词,我想将复制的单词存储在文件中。 Basically a file with the clipboard history. 基本上是带有剪贴板历史记录的文件。

Since the copying of words is a continuous process I need to use a loop that stores the copied words during the performance. 由于单词的复制是一个连续的过程,因此我需要使用一个循环来在演奏过程中存储复制的单词。 I figured it would be handy to use a action/event listener to 1) store the clipboard data to file when cmd + x is pressed and 2) end loop when, for instance cmd + q is pressed. 我认为使用动作/事件侦听器来方便地进行以下操作:1)在按下cmd + x时将剪贴板数据存储到文件中,以及2)在按下cmd + q时结束循环。

I am not very familiar with action/event listeners, and not sure how I should go about using them. 我对动作/事件侦听器不是很熟悉,也不确定如何使用它们。 Are there any easy implementations I could use? 我可以使用任何简单的实现方式吗?

I have what is mostly a pseudo code, that describes what I would like to accomplish. 我主要使用的是伪代码,它描述了我想要完成的工作。 Any suggestions are appreciated! 任何建议表示赞赏!

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")

The code above waits 2 seconds before copying the text from the clipboard to the file. 上面的代码等待2秒钟,然后将文本从剪贴板复制到文件。 Loop reaches its end after 10 iterations. 循环经过10次迭代后到达终点。

I would the code to react to actions performed so that I could store all copied words into a single file. 我希望代码对执行的动作做出反应,以便将所有复制的单词存储到单个文件中。

EDIT: Using the suggestions in the replies to the question I tried solving the problem in two ways, one with keyboard and pynput module. 编辑:使用对问题的答复中的建议,我尝试以两种方式解决问题,一种是使用键盘和Pynput模块。 Keyboard did not work for me, might be due to me using Mac? 键盘对我不起作用,可能是由于我使用Mac? It did not react as intended when pressing a key. 按下键时,它没有按预期的方式反应。

Keyboard code # (Does not work) 键盘代码#(无效)

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()

Problem: When pressing the key 'c', nothing happens. 问题:按下键“ c”时,没有任何反应。 The print statement does not activate. 打印语句不会激活。

pynput code # (Works) Pynput代码#(Works)

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 worked as intended, in the way that everytime 'c' key is pressed, as is done when using cmd + c to copy, it copies the currently stored text in clipboard to the text file. pynput可以按预期方式工作,每次按下“ c”键时(就像使用cmd + c进行复制时一样),它会将剪贴板中当前存储的文本复制到文本文件中。

(minor) Problem: I did not get pynput to react on the combination of pressing cmd + c simultaneosly. (未成年人)问题:我并没有对同时按下cmd + c的组合产生反应。 However that did not matter in this case, as reacting to the key press 'c' is enough. 但是,在这种情况下这并不重要,因为对按键“ c”作出反应就足够了。 For future references though, please comment if you know how to listen for a combination of keys. 但是,对于将来的参考,如果您知道如何听组合键,请发表评论。

I tried the following, which neither one worked: 我尝试了以下方法,但没有一个起作用:

if key == Key.cmd and str(key) == "'c'":
        print('Copying the selected')

and

if key == Key.cmd:
    if str(key) == "'c'":
        print('Copying the selected')

You should use the keyboard library for python in this case https://pypi.org/project/keyboard/ 在这种情况下,您应该为python使用键盘库https://pypi.org/project/keyboard/

The basic structure for your code would look something like this 您的代码的基本结构如下所示

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)

You can try this one use pynput, a function support multi combination keys mapping arbitrary custom functions, just put them into a dict: 您可以尝试使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM