如何解决在python的命令行中验证输入
我正在尝试使用python在命令行中创建一个登录面板。因此,如果用户未插入任何username
,则光标应保持在同一行,但下一行会出现错误。
我尝试过:
while True:
input1 = input('username: ')
if len(input1) == 0:
print("Sorry,your response was not loud enough.")
continue
input2 = stdiomask.getpass('pasword: ')
if len(input2) == 0:
print("Sorry,your response was not loud enough.")
continue
input3 = stdiomask.getpass('cnf password: ')
if len(input3) == 0:
print("Sorry,your response was not loud enough.")
continue
但是由于我使用的是while
循环,所以如果我不插入密码,则必须再次插入用户名,如果我不插入用户名,我也不想插入用户名,则提示用户名显示错误后的下一行。那么有什么办法可以处理这些情况?
类似这样的东西:
F:\new_file\file> python main.py
? username: # cursor remains here until a username is inserted
> Invalid input # error is prmpted on next line
解决方法
尝试递归以获取输入并检查是否有效。如果有效,则返回输入,否则再次调用同一函数
def get_input(name,reset=0):
if reset:
print(end=f"> Invalid {name}\r",flush=True)
print(f"\b",end=f"\r{name}: ",flush=True)
else:
print(f"{name}: \b",flush=True)
inp = input()
if len(inp)==0:
inp = get_input(name,reset=1)
return inp
input1=get_input('username')
input2=get_input('pasword')
input3=get_input('cnf password')
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。