爲上述答案補充到的東西多一點的可重複使用的,我想出了這一點,這繼續提示用戶是否認爲輸入無效。
try:
input = raw_input
except NameError:
pass
def prompt(message, errormessage, isvalid):
"""Prompt for input given a message and return that value after verifying the input.
Keyword arguments:
message -- the message to display when asking the user for the value
errormessage -- the message to display when the value fails validation
isvalid -- a function that returns True if the value given by the user is valid
"""
res = None
while res is None:
res = input(str(message)+': ')
if not isvalid(res):
print str(errormessage)
res = None
return res
它可以像這樣使用,以驗證功能:
import re
import os.path
api_key = prompt(
message = "Enter the API key to use for uploading",
errormessage= "A valid API key must be provided. This key can be found in your user profile",
isvalid = lambda v : re.search(r"(([^-])+-){4}[^-]+", v))
filename = prompt(
message = "Enter the path of the file to upload",
errormessage= "The file path you provided does not exist",
isvalid = lambda v : os.path.isfile(v))
dataset_name = prompt(
message = "Enter the name of the dataset you want to create",
errormessage= "The dataset must be named",
isvalid = lambda v : len(v) > 0)
你想要的文件的名稱來自於用戶輸入或命令行參數? (例如python myScript.py inputfile.txt) – 2010-07-27 15:28:21
由於您剛剛開始使用Python,因此查看教程並學習該語言的基礎知識可能是一個好主意,而不是嘗試僅學習您需要的功能,當你找不到東西時,在StackOverflow上搜索答案。這需要更多的時間,但是你會更好地理解語言。 – chimeracoder 2010-07-27 15:39:58
@chimeracoder:理所當然,他走的很簡單,但正是這些問題讓我能夠快速找到答案,如果我只是在谷歌上查找它。對於一個小型項目而言,並沒有太多時間python是選擇的工具,因爲它很簡單,所以不必閱讀整個教程。 – 2013-06-09 19:48:29