1

I'm writing a Python application and would like to prompt a user for their password. If they do not enter it within 60 seconds, the program should exit. If they do enter it, their password should be hidden in the terminal.

How do I do this?

Context

I've seen posts like this one that suggest methods to input some user input with a timeout. However, these solutions don't hide input like getpass does. I'm wondering if there's some functionality that could use getpass or something like it.

whoopscheckmate
  • 574
  • 2
  • 16
  • 1
    Would something like [this](https://www.codespeedy.com/timeout-a-function-in-python/) help? – Lucas Jan 27 '22 at 16:03
  • That's an interesting solution, but it seems so low-level. To use threading for something that I feel would be a common use case seems brittle. – whoopscheckmate Jan 27 '22 at 18:00

1 Answers1

1

Inspired by this (which only seems to only work on Unix systems), you can timeout a function call by signal.alarm()

import getpass
import signal


def timeout(signum, frame):
    print('Timeout!')
    exit()


def get_user_password():
    upass = getpass.getpass()
    return upass


if __name__ == "__main__":
    signal.signal(signal.SIGALRM, timeout)
    timeout_in_s = 10

    signal.alarm(timeout_in_s)
    upass = get_user_password()
    signal.alarm(0)  # Stop alarm
Lucas
  • 362
  • 2
  • 12
  • That requirement of being a Unix system is what turned me off to that solution in that post. Probably the best option I've seen, though. – whoopscheckmate Jan 28 '22 at 16:50
  • Yeah, it's a bit restrictive. But it seems like this or threading is the best way to do it. @whoopscheckmate – Lucas Jan 29 '22 at 13:34