Python-docopt和argparse之间的区别 [英] Python - Difference between docopt and argparse

查看:141
本文介绍了Python-docopt和argparse之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须编写一个命令行界面,并且可以使用docoptargparse.

I have to write a command-line interface and I've seen I can use docopt and argparse.

我想知道两者之间的主要区别是什么,以便做出明智的选择.

I would like to know what are the main differences between the two so that I can make an enlightened choice.

请坚持事实.我不要哇. docopt.如此美丽.非常有用.

推荐答案

Docopt解析文档字符串,而argparse通过创建对象实例并通过函数调用为其添加行为来构造其解析.

Docopt parses a doc string, whereas argparse constructs its parsing by creating an object instance and adding behaviour to it by function calls.

argparse的示例:

parser = argparse.ArgumentParser()
parser.add_argument("operation", help="mathematical operation that will be performed", 
    choices=['add', 'subtract', 'multiply', 'divide'])
parser.add_argument("num1", help="the first number", type=int)
parser.add_argument("num2", help="the second number", type=int)
args = parser.parse_args()

docopt示例:

"""Calculator using docopt

Usage:
  calc_docopt.py <operation> <num1> <num2>
  calc_docopt.py (-h | --help)

Arguments:
  <operation>  Math Operation
  <num1>       First Number
  <num2>       Second Number

Options:
  -h, --help     Show this screen.

"""
from docopt import docopt

if __name__ == '__main__':
    arguments = docopt(__doc__, version='Calculator with docopt')
    print(arguments)

注意,该docopt使用Usage:Options:部分进行解析.此处Arguments:仅出于方便最终用户的目的提供.

Note, that docopt uses Usage: and Options: sections for parsing. Here Arguments: is provided only for end-user convenience.

这篇关于Python-docopt和argparse之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆