为上述答案补充到的东西多一点的可重复使用的,我想出了这一点,这继续提示用户是否认为输入无效。
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