最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - Inconsistent behavior with pynput when creating global hotkey - Stack Overflow

programmeradmin3浏览0评论

I'm trying to create a program that copies a certain text with the shortcut ctrl + c, and through that same hotkey, activates a logic that will perform certain formatting actions in the string. The code I managed to get so far is this:

import pyperclip
import pynput


def clipboard_proccer():
    print('into proccer')
    current_value = pyperclip.paste()
    current_value = current_value.replace('\n','')
    current_value = current_value.replace('\r', '')
    pyperclip.copy(current_value)
    print('out of proccer')

def for_canonical(f):
    return lambda k: f(l.canonical(k))

if __name__ == '__main__':
    hotkey = pynput.keyboard.HotKey(pynput.keyboard.HotKey.parse('<ctrl>+c'), clipboard_proccer)
    with pynput.keyboard.Listener(on_press=for_canonical(hotkey.press), on_release=for_canonical(hotkey.release)) as l:
        l.join()

As you can see, the idea is to remove all instances of \n and \r from the string, then put that back into the clipboard using pyperclip. To activate that function when pressing ctrl + c, I'm using pynput.

The thing is, it works, but only once. The first time, it does exactly what I want it to: copy the text, then immediately after do the formatting, however after that, it never copies again through ctrl + c, but it continues printing the two print functions inside clipboard_proccer. Interestingly, if I copy some text through the context menu (ie right mouse button), and then press ctrl + c, it executes the formatting.

What am I doing wrong? How can I achieve what I want every time, instead of just the first time.

发布评论

评论列表(0)

  1. 暂无评论