簡體   English   中英

在python中驗證命令行中的輸入

[英]validate input in command line in 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", 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')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM