Search code examples
multithreadingpython-3.xkeypressturtle-graphics

How to, in Python, ignore certain/all keypresses while function executing in program on Macintosh


I would like to know, how would I, in Python, be able to ignore certain/all keypresses by the user while a certain function in the program is executing? Cross platform solutions are preferred, but if that is not possible, then I need to know how to do this on Macintosh. Any help is greatly appreciated! :)

EDIT: Right now, I am processing keypresses through the turtle module's onkey() function since I did create a program using turtle. I hope this helps avoid any confusion, and again, any help is greatly appreciated! :)


Solution

  • You might want to modify your question to show how you're currently processing key-presses. For example is this a command-line program and you're using curses?

    You could use os.uname to return the os information or sys.platform, if that isn't available. The Python documentation for sys.platform indicates that 'darwin' is returned for OSX apple machines.

    If the platform is darwin then you could, in your code, ignore whatever key-presses you want to.

    Edit (Update due to changed question): If you want to ignore key-presses when a certain function is being called you could either use a lock to stop the key-press function call and your particular function being executed together.

    Here is an example of using a lock, this may not run, but it should give you a rough idea of what's required.

    import _thread
    
    a_lock = _thread.allocate_lock()
    
    def certainFunction():
        with a_lock:
            print("Here's the code that you don't want to execute at the same time as onSpecificKeyCall()")
    
    def onSpecificKeyCall():
        with a_lock:
            print("Here's the code that you don't want to execute at the same time as certainFunction()")
    

    Or, depending on the circumstances, when the function which you don't want interrupting with a key press is called, you could call onkey() again, with the specific key to ignore, to call to a function that doesn't do anything. When your particular function has finished, you could call onkey() again to bind the key press to the function that processes the input.