docopt参数解析:如何避免意大利面代码?

2024-06-06 13:29:00 发布

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

这是我第一次使用docopt,我正在努力为一个小的命令行程序进行args解析。在

    '''Usage:
    ovh_mails.py list [--ugly]
    ovh_mails.py add (<address> [--pswd=<password>][--description=<description>] | --file <filename>)
    ovh_mails.py remove (<address> | --file <filename>)
    ovh_mails.py (-h | --help)

Arguments:
    <password>                        Password to access the mailbox (if not provided it's random generated)
    <filename>                        Name of the files to process. Check README to see how to format it

Options: 
    -h, --help                        Show this help message
    -u, --ugly                        Print without nice tables
    -p, --pswd=<password>  Set the password to the one provided

Commands:
    list                              list all the email addresses currently configured
    add                               add one or more (configured in <filename>) email addresses
    remove                            remove one ore more (configured in <filename>) email addresses'''

我现在的论点是:

^{pr2}$

有没有更好的,更多的Python矿石更优雅的方式,这样做?在


Tags: thetopyaddemailaddresseshelppassword
1条回答
网友
1楼 · 发布于 2024-06-06 13:29:00

您可以为每个命令编写验证函数,并将它们放入validate字典中:

command = next((c for c in 'list add remove'.split() if args[c]), 'help')
try:
    validate[command](args)
except ValidationError as error:
    print_usage_and_exit(error)

^{} recommends ^{}用于数据验证。在

相关问题 更多 >