V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
haoxuexiaoyao
V2EX  ›  Python

请问下如何使用 pynput 按下热键执行对应函数,示例代码如下,一直无法执行 on_activate 方法

  •  
  •   haoxuexiaoyao · Jan 5, 2022 · 2012 views
    This topic created in 1576 days ago, the information mentioned may be changed or developed.
    import pandas as pd
    import time
    import sys
    import os
    import pyperclip
    from pynput import keyboard
    
    
    def get_txt():
        return pyperclip.paste()
    
    
    def on_activate(data_txt):
        df = pd.DataFrame(data_txt, columns={'txt'}, dtype='string')
        df.to_csv('text.csv', index=False, mode='a', header=False)
        print('Global hotkey activated!')
    
    
    def for_canonical(f):
        return lambda k: f(l.canonical(k))
    
    
    hotkey = keyboard.HotKey(
        keyboard.HotKey.parse('<ctrl>+b'),
        on_activate)
    l = keyboard.Listener(on_press=for_canonical(hotkey.press),on_release=for_canonical(hotkey.release))
    
    
    def main():
    
        sys.path.append(os.path.abspath("SO_site-packages"))
        data_txt = []
        recent_value = ""
        while True:
            tmp_value = pyperclip.paste()  # 读取剪切板复制的内容
    
            if tmp_value != recent_value:  # 如果检测到剪切板内容有改动,那么就进入文本的修改
                recent_value = tmp_value
                data_txt.append(recent_value)
                print('已复制内容:%s' % str(data_txt))
            time.sleep(0.1)
            l.start()
            l.join()
    
    
    if __name__ == "__main__":
        main()
    
    
    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2397 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 16:00 · PVG 00:00 · LAX 09:00 · JFK 12:00
    ♥ Do have faith in what you're doing.