首页 > 解决方案 > 如何设置计时器来验证python中的用户名?

问题描述

有没有办法设置一个 30 秒的计时器来验证程序的用户名,然后再返回起始行,并要求用户再次输入名称?这是我到目前为止所拥有的:

print("")
verifyp1loop = True
while verifyp1loop==True:
    verifyp1 = input("Please input Player 1's username. ")
    verifyp1confirm = input("Are you sure you want this to be your username? y/n ")
    if verifyp1confirm == "y":
        print("Username confirmed.")
        verifyp1loop=False
    else:
        print("Username denied.")

verifyp2loop = True
while verifyp2loop==True:
    verifyp2=input("Please input Player 2's username. ")
    verifyp2confirm=input("Are you sure you want this to be your username? y/n ")
    if verifyp2confirm == "y":
        print("Username confirmed.")
        verifyp2loop=False
    else:
        print("Username denied.")

我对此很陌生,任何帮助将不胜感激:)

标签: pythonverify

解决方案


轻量级解决方案:

没有循环

没有线程

只是示例如何实现超时

import time
class Verify(object):
    def __init__(self,timeout):
        self.timeout = timeout
        self.verification = None
    def verify(self):
        self.verification = None
        start_verification = time.time()
        verifyp1confirm = input("Are you sure you want this to be your username? y/n ")
        end_verification = time.time()
        if (end_verification-start_verification)>self.timeout:
            print('Denied')
            self.verification = 0
        else:
            print('OK')
            self.verification = 1

>>> ver=Verify(3)
>>> ver.verify()
Are you sure you want this to be your username? y/n y
OK
>>> print(ver.verification)
1
>>> ver.verify()
Are you sure you want this to be your username? y/n y
Denied
>>> print(ver.verification)
0

注意相同的答案,不同的输出

执行:

ver=Verify(3)
while ver.verification == None or ver.verification ==0:
    ver.verify()

推荐阅读