Can I use Python to capture keyboard and mouse events in OSX?

前端 未结 5 1661
既然无缘
既然无缘 2021-02-08 04:53

I\'m trying to write a simple macro recorder in Python for OSX - something which can capture mouse and key events as the script runs in the background and replay them. I can use

5条回答
  •  梦谈多话
    2021-02-08 05:23

    Calvin Cheng, Thank you. your suggestion works on OS X 10.8.5.

    Code from http://docs.python.org/faq/library.html#how-do-i-get-a-single-keypress-at-a-time

    #!/usr/bin/python
    
    import termios, fcntl, sys, os
    
    fd = sys.stdin.fileno()
    
    oldterm = termios.tcgetattr(fd)
    newattr = termios.tcgetattr(fd)
    newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
    termios.tcsetattr(fd, termios.TCSANOW, newattr)
    
    oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)
    
    try:
        while 1:
            try:
                c = sys.stdin.read(1)
                print "Got character", repr(c)
            except IOError: pass
    finally:
        termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
        fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)
    

    One more solution Key Listeners in python?

提交回复
热议问题