2017-08-31 146 views
0

我一直在使用pynput庫來監視鼠標的點擊。我面對的唯一問題是終端不按Ctrl + C終止。我需要用鼠標監聽器來使用鍵盤監聽器。這是我的代碼:在Python中使用鼠標和鍵盤監聽器

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。

+0

按「選項+ c」 –

+0

我已經提到過我使用了選項+ C。它不工作。程序不終止。我想用鼠標監聽器添加鍵盤監聽器 –

回答

1

創建一個不帶「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被按下'。但右鍵單擊並按f8。當鼠標右鍵點擊停止鍵盤監聽器時,您將看不到任何打印內容。

爲Mac:

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) 

只有幾個鍵像CMD,ALT默認監聽的MAC。

+0

沒有。它沒有顯示F8被按下。我嘗試按F8後右鍵點擊too.It只顯示鼠標clicks.i.e左/右/中間。 –

+0

默認情況下,Mac保護鍵盤記錄器,不會讓你聽按鍵,除了像cmd,alt等幾個鍵。這是完全不同的問題。如果您想檢查功能,請打印每個鍵並嘗試按cmd或alt。添加了這個答案。請檢查。 –

+0

是的,你是對的。它只聽特殊鍵,如'Shift','cntrl','命令'。但是我希望操作系統也可以聽其他字母數字鍵。我怎樣才能做到這一點? –