有没有办法自定义PyInputPlus显示的错误消息?

2024-09-28 05:23:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我最近学习了PyInputPlus以及如何使用它。 这真是太棒了,但我想知道是否有一种方法可以自定义PyInputPlus在用户输入无效值时显示的错误消息。 例如,在下面的代码中

import pyinputplus as pyip
response=pyip.inputInt('please, enter a number: ')

如果用户输入字母“s”,PyInputPlus将显示-

's' is not an integer

我想把这条信息剪下来,用另一种(非英语)语言表达出来。 我试图在PyInputPlus的官方文档中找到解决方案,但除了使用我不感兴趣的inputCustom之外,什么也没有找到


Tags: 方法代码用户import消息numberresponseas
3条回答

如果设置使用PyInputPlus执行此操作,则可以使用参数blockRegexes获得所需的行为,该参数允许设置自定义错误消息(在文档中,显然错误地记录了PyInputPlus parameters中不存在的参数blocklistRegexes):

blocklistRegexes (Sequence, None): A sequence of regex str or (regex_str, error_msg_str) tuples that, if matched, will explicitly fail validation.

由于编写只匹配整数的正则表达式要比只匹配除整数以外的所有内容的正则表达式简单,因此我首先使用blockRegexes禁止使用正则表达式.*的所有内容,然后allowRegexes使用正则表达式^-?\d+$'为整数添加异常(仅正整数和负整数,请参见https://regex101.com/r/1ymJzE/1

以下示例接受负整数或正整数,否则打印自定义西班牙语错误消息:

import pyinputplus as pyip

response = pyip.inputInt('please, enter a number: ',
             allowRegexes=[r'^-?\d+$'],
             blockRegexes=[(r'.*','¡Esto no es un número entero!')]
           )

执行:

please, enter a number: a
¡Esto no es un número entero!
please, enter a number: 1-2
¡Esto no es un número entero!
please, enter a number: 3.2
¡Esto no es un número entero!
please, enter a number: 5,4
¡Esto no es un número entero!
please, enter a number: -12

您还可以通过提供一个接受除整数以外的所有内容的正则表达式,仅使用blockRegexes实现同样的效果。如果允许使用负数,这个正则表达式就要复杂一些。有关正则表达式的详细解释,请参见this answer to a respective question

此代码实现与上述代码相同的结果:

import pyinputplus as pyip

response = pyip.inputInt('please, enter a number: ',
             blockRegexes=[(r'[^-0-9]+|[0-9]+(?=-)|^-$|-{2,}','¡Esto no es un número entero!')]
           )

首先,我强烈反对尽可能使用第三方库,因为它们会在代码中添加您不理解的错误。许多是非常有用的,是很好的支持,和/或有一些功能,这将需要你一个年龄来复制

但是,您可以在这种情况下使用int(input()),也可以这样做
(它的表现将更符合您的预期)

在代码中挖掘validation actually calls another 3rd-party library是由同一作者编写的

这看起来像是转到代码path here where the real Exception is,然后转到here to be caught

或许

while True:
    value = input("Please enter a number (q to quit): ")
    if value.startswith(('Q', 'q')):
        sys.exit("quit")
    try:
        value = int(value)
    except ValueError as ex:  # custom error message below!
        print("invalid input '{}', expected int".format(value))
    else:  # did not raise Exception
        break  # escape while loop

如果您一直在寻找特定异常是什么,repr()非常有用

>>> try:
...     raise ValueError("some string")
... except IOError:
...     print("reached IOError")
... except Exception as ex:
...     print("unexpected Exception: {}".format(repr(ex)))
...     raise ex
...
unexpected Exception: ValueError('some string')
Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
  File "<stdin>", line 2, in <module>
ValueError: some string

我想你可以试着把它当作例外处理。将逻辑放在“try”块中,并在异常块中显示为错误的内容

try:
    #code logic
except SyntaxError: #for example
    print("You encountered a syntax error. ")

你可以在我写的“SyntaxError”中写下你得到的错误的名称

相关问题 更多 >

    热门问题