【发布时间】:2023-04-04 17:03:01
【问题描述】:
通常,man 提供的长文档不会直接打印在屏幕上,而是重定向到 less(例如 man ls)。
有没有办法用 python 中的 docopt 模块做到这一点?
【问题讨论】:
通常,man 提供的长文档不会直接打印在屏幕上,而是重定向到 less(例如 man ls)。
有没有办法用 python 中的 docopt 模块做到这一点?
【问题讨论】:
没有官方的方式,但你可以这样做:
"""
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。
【讨论】: