python - 在 Python 中一起使用鼠标和键盘监听器

标签 python macos keylistener

我一直在使用 pynput 库来监视鼠标点击。我面临的唯一问题是终端在按 Ctrl+C 时不会终止。我需要将键盘监听器与鼠标监听器一起使用。这是我的代码:

import os
import time
import re
from pynput import mouse
from pynput.keyboard import Key, Listener
f=open('maniac1.txt','a')

inc=1
f.write('<mouse_new>\n')

def on_click(x, y, button, pressed):
    f=open('maniac1.txt','a')
    if button == mouse.Button.left:
        print 'Left'
        f.write('left\n')

    if button == mouse.Button.right:
        print 'right'
        f.write('right\n')
    if button == mouse.Button.middle:
        print 'middle'
        f.write('middle\n')

with mouse.Listener(on_click=on_click,on_scroll=on_scroll) as listener:
    try:
        listener.join()
    except MyException as e:
        print('Done'.format(e.args[0]))

如何在按 Esc 或 Ctrl+C 后终止此代码?我使用的是 OSX。

最佳答案

创建一个不带“with”关键字的实例keyboard.Listener,以便您可以根据您的鼠标监听器启动和停止监听器。检查下面的代码,它会在鼠标右键单击后停止监听 f8 的按键。

import os
import time
import re
from pynput import mouse
from pynput.keyboard import Key, Listener
#f=open('maniac1.txt','a')

inc=1
#f.write('<mouse_new>\n')
from pynput import keyboard

def on_functionf8(key):
    if (key==keyboard.Key.f8):
        print('f8 is pressed')


key_listener = keyboard.Listener(on_release=on_functionf8)
key_listener.start()


def on_click(x, y, button, pressed):
    f=open('maniac1.txt','a')
    if button == mouse.Button.left:
        print ('Left')
        #f.write('left\n')

    if button == mouse.Button.right:
        key_listener.stop()
        print ('right')
        #f.write('right\n')
    if button == mouse.Button.middle:
        print ('middle')
        #f.write('middle\n')

with mouse.Listener(on_click=on_click) as listener:
    try:
        listener.join()
    except MyException as e:
        print('Done'.format(e.args[0]))

运行程序并按 f8,您将在终端上看到“f8 is pressed”。但是右键单击并按 f8。当我们通过鼠标右键单击停止键盘监听器时,您不会看到任何打印内容。

对于苹果机:

def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))



key_listener = keyboard.Listener(on_release=on_press)

在 mac 上默认只监听 cmd、alt 等少数按键。

关于python - 在 Python 中一起使用鼠标和键盘监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45973453/

相关文章:

objective-c - NSPopUpButtonCell indexOfSelectedItem 始终返回 0

ruby-on-rails - 使用 rails 的 bundler 问题(mac 用户)

java - 将 KeyListener 添加到自定义对象

Java KeyListener 没有检测到键盘输入

java - 在新线程中有监听器

python - 如何设置 Pyomo 求解器超时?

python - 我的功能需要负时间才能完成。到底发生了什么事?

macos - 在 Mac OSX 上,如何将脚本文件与终端相关联,以便双击图标启动终端?

python - 在 Python 中复制字符串列表的最佳方法是什么?

python - Seleniumwire 未记录 chrome headless 模式下的所有请求