在python的命令行中验证输入
我正在尝试使用python在命令行中创建一个登录面板。因此,如果用户没有插入任何在python的命令行中验证输入,python,python-3.x,list,input,command-line-interface,Python,Python 3.x,List,Input,Command Line Interface,我正在尝试使用python在命令行中创建一个登录面板。因此,如果用户没有插入任何用户名,光标应该保持在同一行,但我应该在下一行得到一个错误 我试过: while True: input1 = input('username: ') if len(input1) == 0: print("Sorry, your response was not loud enough.") continue input2 = stdiomask.getpass(
用户名
,光标应该保持在同一行,但我应该在下一行得到一个错误
我试过:
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
但是,由于我在使用的同时
循环,所以如果我没有插入密码,我必须再次插入用户名,如果我没有插入用户名,我也不希望再次插入用户名,在显示错误后,用户名会在下一行提示。那么有什么办法来处理这些情况呢
大概是这样的:
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", end=f"\r{name}: ", 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')
尝试使用递归,发布示例代码谢谢,它可以工作,但可以在同一行上写入输入,即如果没有输入被传递,错误会在下一行弹出,但光标保持在同一行,并等待用户写入输入。在应答中添加了重置逻辑。如果您在下一行中发现它仍然正确,请选中“正确”。