Search code examples
pythonpython-3.xclipboardpyperclip

duplicate output for clipboard / pyperclip


I want to create a local copy(ctrl+c) history in a txt but in the output I keep getting duplicate entries.

My code:

import keyboard
import win32clipboard

print('Waiting Ctrl+C\n')    

while True

    if keyboard.is_pressed('ctrl+c'):
        win32clipboard.OpenClipboard()
        data = win32clipboard.GetClipboardData()
        a = open('E:\Python\copyhistory.txt', 'a')
        a.write(data)  # text
        a.close()
        win32clipboard.CloseClipboard()
        print('printed')

Output gets duplicated a lot. I also tried pyperclip but that did not help too. Same problem persist in pyperclip as well.

Pyperclip example is below:

import pyperclip
import keyboard

while True:
    if keyboard.is_pressed('ctrl+c'):
        a = pyperclip.paste()
        print(a)

Terminal output of code 1: Waiting Ctrl+C printed Then 40 lines of "printed"

Same goes for pyperclip, code 2 with pyperclip outputted more than 700 lines of same output, the output that should be printed once.

Wham am I doing wrong in here, any ideas?


Solution

  • The problem occurs due to delay between key_down and key_up. This can be prevented by reading either key_down or key_up.

    I tried how to do it but it was dead end for me so I decided to use the output of the difference in clipboard.