Description of what I want to achieve:
- I have a file which consists of words. Let's say they are "fish","tacos","burger".
- Every time I paste a word (cmd + v on Mac or ctrl + v on Windows), I want the clipboard to move to the next word, so that I don't have to manually copy it and when I press cmd + v again the next word is pasted.
Description of my approach:
- First of all I make each row in the file to an element in a list
- With pyperclip I export the first element of the list to the clipboard
- Using pynput key listener, every time I paste (press key "v") I replace the list with a new list, where the first element is removed.
- Next time I paste the previous 2nd element is now the 1st element.
Description of the problem.
- Sometimes the same word is pasted two times in a row and I am not sure why that is happening. For instance I press cmd + v and the word fish is pasted, I press cmd + v and tacos is pasted, I press cmd + v tacos is pasted again. The words that are pasted twice also varies depending on tries, so could it be that making a new list sometimes fails?
Question:
- What might cause the problem?
- What could be the solution?
My code:
import pyperclip
from pynput.keyboard import Key, Listener
file_list = []
for line in f:
file_list.append(line)
def on_release(key):
global file_list
pyperclip.copy(file_list[0]) # exports the 1st element in list to the clipboard
if str(key) == "'v'":
file_list = file_list[1:] #Removes the 1st element from list, since it has been pasted and is no longer needed
print('{0} release'.format(
key))
if key == Key.esc:
# Stops listener
print("End")
return False
# Collect events until released
with Listener(
on_release=on_release) as listener:
listener.join()
EDIT: My first theory was that it had something to do with the way the new list was formed
So I also tried dropping the first element of the list using
del file_list[0]
and
file_list.pop(0)
The same problem still occurs, though. So I think we can rule out the list being the problem.
My new theory is that it has something to do with with pyperclip failing to export a word to clipboard, causing the same word to be pasted as previously. Will try to do some test and find a solution surrounding that.
EDIT2: It seems that my second theory holds up. When checking the clipboard through finder the word is not always updated. Will try to find a solution. It could perhaps be as easy as adding time.sleep(0.1) to the code?
EDIT3: Adding time.sleep(0.1) or time.sleep(1) to the code actually made it worse, since now pypeclip.copy() is not being accessed immideately. However this is good, since now I know I am on the right track. Will try to think about if I could restructure the code so that any delays doesn't cause a problem.