【问题标题】:Should we use options to get information that is not optional but we do that to make it look more intuitive?我们是否应该使用选项来获取非可选信息,但我们这样做是为了让它看起来更直观?
【发布时间】:2017-03-27 01:01:58
【问题描述】:

我正在尝试编写一个 python 程序,它将在 cli 中提供一些 github 功能,例如创建问题、创建 repos、创建 PR 等。

我想出了类似的东西 github create issue --title <title> --description <description> --user <user> --repo <repo>

我为此使用了 argparse

import argparse
parser = argparse.parser()
parser.add_argument('create', 
                    options=['issue', 'repo', 'pull')
                    action='store')
parser.add_argument('--title', action="store", type=str)
parser.add_argument('--description', action="store", type=str)
parser.add_argument('--user', action="store")
parser.add_argument('--repo')

parser.parse_args('create issue --title title --description desc --user user --repo repo')

我使用选项--title--descriptions 来获取关键字形式的信息。

虽然选项是可选的,但根据我的解析风格:

  • 如果createissue,则需要--title--description--user--repo

解析命令 github create issue --title title --description desc --user user --repo repo 的正确方法是什么?

【问题讨论】:

    标签: python command-line-interface argparse


    【解决方案1】:

    首先进行一些调整:

    parser.add_argument('--title', action="store", type=str)
    

    可以简化为

    parser.add_argument('--title')
    

    因为这个动作和类型是默认的。您可以使用--repo 执行此操作。

    args = parser.parse_args()
    

    从命令行读取并将值放入 args 命名空间。

    args = parser.parse_args(['issue --title title --description desc --user user --repo repo'].split())
    

    可用于使用模拟的字符串列表测试此解析器。

    请注意,我删除了create

    parser.add_argument('create', choices=['issue', 'repo', 'pull'))
    

    定义了一个positional,它将作为args.create放入args。它接受的字符串是choices(不是options)。另一种方法是使用--create;在这种情况下,它的行为与其他参数一样,只是接受值有限制。

    如果你想为一个特定的值需要一些参数,你需要在解析后进行测试,例如

    if args.create in ['issue']:
        if args.title is None or args.user is None:
           parser.error('title and user required with issue')
    

    这几乎是最近的 How can I make Python argparse to have dependency 的副本,该 How can I make Python argparse to have dependency 也作为副本关闭。

    另一种方法是使用subparsers。但您可以阅读文档和之前的 [argparse] 问题中的相关内容。

    尝试这些想法,然后提出一个新问题。

    您必须编写自定义的 usage 和/或 help 段落来描述对用户的约束。

    【讨论】:

      猜你喜欢
      • 2011-09-29
      • 2016-08-24
      • 2014-10-07
      • 2013-03-14
      • 1970-01-01
      • 1970-01-01
      • 2011-01-10
      • 2019-06-23
      • 1970-01-01
      相关资源
      最近更新 更多