Search code examples
pythonlinuxuser-inputputtyuser-inactivity

How to detect user inactivity time in python application (Linux)?


I am wondering if there is any way that when I ask for user input, if there is a way to detect how many seconds have passed since asking for user input?

I would like to be able to have some kind of timer, that if the user hasn't entered an answer and pressed enter for 15 minutes, to jump to another function, or set the user input to some default value and continue on.

Here is the input for the user:

res = input('Test result? "(P)ass,(F)ail,(R)etry,(S)ave and Quit,(Q)uit": ')

after 15 minutes(900 secs), set res = "S" and continue on.

Or something similar.

My investigation into something similar has lead me to believe the solution is likely not cross-platform. And I am running this script in Red Hat Linux. Also, I am accessing and executing the script via PuTTY.

Any help would be greatly appreciated.

Thank you.


Solution

  • It is actually easy to do this in a cross platform way.

    You should be able to do this by launching a thread to handle the user input, and monitoring both the thread and the time from the main loop.

    Some relevant points:

    • The threading module's doc can be found here.

    Your code

    res = input('Test result? "(P)ass,(F)ail,(R)etry,(S)ave and Quit,(Q)uit": ')
    

    should run from the child thread.

    • For the resolution you need, you can monitor the time via the time module.