我最近学习了PyInputPlus以及如何使用它。 这真是太棒了,但我想知道是否有一种方法可以自定义PyInputPlus在用户输入无效值时显示的错误消息。 例如,在下面的代码中
import pyinputplus as pyip
response=pyip.inputInt('please, enter a number: ')
如果用户输入字母“s”,PyInputPlus将显示-
's' is not an integer
我想把这条信息剪下来,用另一种(非英语)语言表达出来。 我试图在PyInputPlus的官方文档中找到解决方案,但除了使用我不感兴趣的inputCustom之外,什么也没有找到
如果设置使用PyInputPlus执行此操作,则可以使用参数
blockRegexes
获得所需的行为,该参数允许设置自定义错误消息(在文档中,显然错误地记录了PyInputPlus parameters中不存在的参数blocklistRegexes
):由于编写只匹配整数的正则表达式要比只匹配除整数以外的所有内容的正则表达式简单,因此我首先使用
blockRegexes
禁止使用正则表达式.*
的所有内容,然后allowRegexes
使用正则表达式^-?\d+$'
为整数添加异常(仅正整数和负整数,请参见https://regex101.com/r/1ymJzE/1)以下示例接受负整数或正整数,否则打印自定义西班牙语错误消息:
执行:
您还可以通过提供一个接受除整数以外的所有内容的正则表达式,仅使用
blockRegexes
实现同样的效果。如果允许使用负数,这个正则表达式就要复杂一些。有关正则表达式的详细解释,请参见this answer to a respective question此代码实现与上述代码相同的结果:
首先,我强烈反对尽可能使用第三方库,因为它们会在代码中添加您不理解的错误。许多是非常有用的,是很好的支持,和/或有一些功能,这将需要你一个年龄来复制
但是,您可以在这种情况下使用
int(input())
,也可以这样做(它的表现将更符合您的预期)
在代码中挖掘validation actually calls another 3rd-party library是由同一作者编写的
这看起来像是转到代码path here where the real Exception is,然后转到here to be caught
或许
如果您一直在寻找特定异常是什么,
repr()
非常有用我想你可以试着把它当作例外处理。将逻辑放在“try”块中,并在异常块中显示为错误的内容
你可以在我写的“SyntaxError”中写下你得到的错误的名称
相关问题 更多 >
编程相关推荐