iT邦幫忙

0

Python 不換行輸入驗證

  • 分享至 

  • xImage

執行環境:Windows終端機

目的:
想要實現驗證輸入是否有誤,如果有誤則將警告訊息顯示在下方,
然後不換行,繼續在原本的地方輸入,直到輸入無誤後,則將警告訊息刪除。

想要實現如PyInquirer套件功能,程式碼在下下方。

問題A: 不知道如何收回訊息,只能想到覆蓋的方法。
問題B: 輸入A正確後,繼續輸入B時,如果輸入錯誤,寫入警告訊息後,想要回到原本輸入位置,但是輸入位置數值為固定,所以光標會跑到上面去,所以不知道有什麼更好的辦法回到原本輸入位置。

第一次發問,請教各位大大。

目前的程式碼:
程式碼可能很蠢的地方很多,歡迎糾正。

# -*- coding: utf-8 -*-
import os
import sys

class Input_ask():
    def __init__(self, Message):
        self.Message = Message #提問內容
        self.Input()

    def Input(self):
        try:
            self.Reply = input(self.Message).strip()
            self.Judge()
        except KeyboardInterrupt:
            sys.exit()

    #判斷
    def Judge(self):
        if os.path.isfile(self.Reply) == True and self.Reply.strip() != "": 
            return self.Reply
        else:
            self.ShowError()
        

    #顯示錯誤訊息
    def ShowError(self):
        #輸出錯誤訊息
        sys.stderr.write("\n\n" + "\033[31m" + "請輸入正確的檔名" + "\033[0m") 
        #回到原本輸入位置(需修改)        
        sys.stdout.write("\033[%dH" % (3)) 
        self.Input()

print("某某訊息...\n")
FileA = Input_ask("請輸入來源檔案名稱: ").Reply
print("\n" + FileA)
FileB = Input_ask("\n\n請輸入目的檔案名稱: ").Reply
print("\n" + FileB)

輸出畫面:

1.輸入錯誤,顯示警告訊息,但不換行,繼續在原本位置輸入
https://ithelp.ithome.com.tw/upload/images/20220428/20142237ZapYxTSC2P.png

2.輸入正確後想把錯誤訊息收回,然後繼續輸入下一個
https://ithelp.ithome.com.tw/upload/images/20220428/201422375g4GgvfoqD.png



使用PyInquirer套件:

from PyInquirer import prompt
from prompt_toolkit.validation import Validator, ValidationError
from examples import custom_style_3 #美化用


class NumberValidator(Validator):
    def validate(self, document):
        try:
            int(document.text)
        except ValueError:
            raise ValidationError(
                message='Please enter a number', #警告訊息
                cursor_position=len(document.text))  # Move cursor to end

questions = [
    {
        'type': 'input',
        'name': 'quantity',
        'message': 'How many do you need?', #輸入提示
        'validate': NumberValidator, #輸入驗證(在上方)
        'filter': lambda val: int(val)
    }    
]

answers = prompt(questions, style=custom_style_3)
print('Order receipt:')
print(answers)

輸出畫面:

1.輸入錯誤會顯示警告訊息,重新輸入時會自動刪除警告。
https://ithelp.ithome.com.tw/upload/images/20220428/20142237UmR9XZu68i.png

https://ithelp.ithome.com.tw/upload/images/20220428/20142237kwgMozHQG9.png

2.能輸出警告訊息,在原本位置繼續輸入
https://ithelp.ithome.com.tw/upload/images/20220428/20142237Ij7SmHHKe2.png

想要請問原理是什麼,如何實現的。

看更多先前的討論...收起先前的討論...
froce iT邦大師 1 級 ‧ 2022-04-28 15:15:31 檢舉
> 想要請問原理是什麼,如何實現的。

人家開源你可以用點時間去讀啊...
他也是用套件去做底層:
https://github.com/prompt-toolkit/python-prompt-toolkit
Retex iT邦新手 1 級 ‧ 2022-04-28 16:31:45 檢舉
有去仔細看過了,但還是不太懂,我再研究看看,感謝大大。
Retex iT邦新手 1 級 ‧ 2022-04-28 22:40:47 檢舉
似乎找到解決方法,使用Curses模塊應該可行
Retex iT邦新手 1 級 ‧ 2022-05-02 01:02:10 檢舉
發現使用原本方法改一下就可以了。
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答