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

查看:25
本文介绍了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.

请以事实为依据.我不想要哇.医生.如此美丽.非常有用.

Please stick to the facts. I don't want Wow. docopt. So beautiful. Very useful.

推荐答案

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天全站免登陆