簡體   English   中英

在Mac上使用Python將剪貼板歷史記錄存儲在文件中

[英]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”時,沒有任何反應。 打印語句不會激活。

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可以按預期方式工作,每次按下“ 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM