如何设置计时器以验证python中的用户名?

时间:2019-01-14 12:22:06

标签: python verify

是否可以设置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.")

我对此很陌生,我们将不胜感激:)

1 个答案:

答案 0 :(得分:0)

轻量级解决方案:

没有循环

没有线程

只是示例如何实现超时

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()