如果命令行的输入值不在 MAIN 例程的有效选择列表中,如何获得更好的错误提示?
Python 的 click 模块有 choice-options,当输入无效时:
import click
@click.command()
@click.option('--hash-type',
type=click.Choice(['MD5', 'SHA1'], case_sensitive=False))
def digest(hash_type):
click.echo(hash_type)
# python demo.py --hash-type=HASH256
# Error: Invalid value for '--hash-type': 'HASH256' is not one of 'MD5', 'SHA1'.
if __name__=="__main__":
digest()
当用户输入无效的选择时,上面的脚本将退出,并为您打印出有效的选择,这很方便。
我尝试在 Raku 中重写它:
# raku demo.raku --hash_type=HASH256
sub MAIN(
:$hash_type where * ∈ ['MD5', 'SHA1'], #= the hash code
) {
say $hash_type;
}
当提供无效选择时,Raku 仅输出用法,这不太好:
Usage:
demo.raku [--hash_type[=Any where { ... }]]
--hash_type[=Any where { ... }] the hash code
那么,如果命令行中的输入值不在 a 中,如何获得更好的错误提示MAIN 例程中的有效选择列表?
Python's click module have choice-options, when the input is invalid:
import click
@click.command()
@click.option('--hash-type',
type=click.Choice(['MD5', 'SHA1'], case_sensitive=False))
def digest(hash_type):
click.echo(hash_type)
# python demo.py --hash-type=HASH256
# Error: Invalid value for '--hash-type': 'HASH256' is not one of 'MD5', 'SHA1'.
if __name__=="__main__":
digest()
the script above will exit when the user input invalid choice, and it print out the valid choices for you, which is convenient.
I try to rewrite it in Raku:
# raku demo.raku --hash_type=HASH256
sub MAIN(
:$hash_type where * ∈ ['MD5', 'SHA1'], #= the hash code
) {
say $hash_type;
}
When offter an invalid choice, Raku just output the Usage, which is less awesome:
Usage:
demo.raku [--hash_type[=Any where { ... }]]
--hash_type[=Any where { ... }] the hash code
So, How to get better error prompt if the input value from command line not in a list of valide choice in the MAIN routine?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通过使
MAIN
成为多重子:请注意,第二个
MAIN
候选者具有is hide-from-USAGE
因为我们不想看到它任何 USAGE 消息中列出的候选人。另请注意,通过指定!
,第二个 MAIN 候选者将hash_type
参数作为强制参数。如果您有更多候选者,您可能需要处理第二个候选者中的任何其他命名参数。
编辑:wamba 的答案更好。仍然将我的答案留在这里,因为它可能会向人们介绍使用
multi sub
进行MAIN
以及使用ishidden-from-USAGE
的概念代码>特征。By making
MAIN
a multi sub:Note that the second
MAIN
candidate hasis hidden-from-USAGE
because we don't want to see that candidate listed in any USAGE message. Also note that the second MAIN candidate has thehash_type
argument as mandatory, by specifying the!
.If you have more candidates, you will probably need to take care of any additional named arguments in the second candidate.
EDIT: wamba's answer is better. Still leaving my answer here as it may introduce people to the concept of using
multi sub
s forMAIN
, and of using theis hidden-from-USAGE
trait.