【问题标题】:validate input in command line in python在python的命令行中验证输入
【发布时间】:2020-08-26 08:13:06
【问题描述】:

我正在尝试使用 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

【问题讨论】:

  • 尝试使用递归,贴出示例代码

标签: python python-3.x list input command-line-interface


【解决方案1】:

尝试递归获取输入并检查是否有效。如果有效则返回输入否则再次调用相同的函数

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

【讨论】:

  • 谢谢,它有效,但是否可以在同一行写入输入,即如果没有输入,则在下一行弹出错误但光标保持在同一行并等待用户编写输入。
  • 在回答中添加了重置逻辑。如果您认为正确,请检查正确
  • 仍在下一行。
猜你喜欢
  • 2014-04-20
  • 2015-03-26
  • 1970-01-01
  • 1970-01-01
  • 2013-04-17
  • 1970-01-01
  • 2013-01-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多