''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' >>文件: 鍵盤控制.py >>作者: liu yang >>郵箱: liuyang0001@outlook.com >>博客: www.cnblogs.com/liu66blog ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' #!/usr/bin/env python # -*- coding: utf-8 -*- import sys, os from pynput.keyboard import Controller,Key,Listener # 監聽按壓 def on_press(key): try: print("正在按壓:",format(key.char)) except AttributeError: print("正在按壓:",format(key)) # 監聽釋放 def on_release(key): print("已經釋放:",format(key)) if key==Key.esc: # 停止監聽 return False # 開始監聽 def start_listen(): with Listener(on_press=on_press,on_release=on_release) as listener: listener.join() if __name__ == '__main__': # 實例化鍵盤 kb=Controller() # 使用鍵盤輸入一個字母 kb.press('a') kb.release('a') # 使用鍵盤輸入字符串,注意當前鍵盤調成英文 kb.type("hello world") # 使用Key.xxx輸入 kb.press(Key.space) # 開始監聽,按esc退出監聽 start_listen()