【问题标题】:Is it possible to redirect docopt --help options to less?是否可以将 docopt --help 选项重定向到更少?
【发布时间】:2023-04-04 17:03:01
【问题描述】:

通常,man 提供的长文档不会直接打印在屏幕上,而是重定向到 less(例如 man ls)。

有没有办法用 python 中的 docopt 模块做到这一点?

【问题讨论】:

    标签: python arguments docopt


    【解决方案1】:

    没有官方的方式,但你可以这样做:

    """
    Usage:
        docopt_hack.py
    """
    
    import docopt, sys, pydoc
    
    def extras(help, version, options, doc):
        if help and any((o.name in ('-h', '--help')) and o.value for o in options):
            pydoc.pager(doc.strip("\n"))
            sys.exit()
        if version and any(o.name == '--version' and o.value for o in options):
            print(version)
            sys.exit()
    
    docopt.extras = extras
    
    # Do your normal call here, but make sure it is after the previous lines
    docopt.docopt(__doc__, version="0.1")
    

    我们所做的是覆盖extras 函数,该函数处理普通docopt (https://github.com/docopt/docopt/blob/master/docopt.py#L476-L482) 中帮助的打印。然后我们使用 pydoc 将输入推送到寻呼机 (https://stackoverflow.com/a/18234081/3946766)。请注意,使用 pydoc 是一种不安全的快捷方式,因为该方法没有记录在案并且可以被删除。 extras 也是如此。 YMMV。

    【讨论】:

    • 没有足够的代表进行投票,但您的回答和解释正是我想要的。非常感谢!
    • @Liad 别担心,你很快就会得到代表。玩得开心!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 2019-01-21
    • 2013-08-30
    相关资源
    最近更新 更多