描述后的python argparse打印用法文本 [英] python argparse print usage text after description
问题描述
有没有一种方法可以在使用python argparse的描述文本之后打印用法文本?我的cmd行argparse工作正常,但是我想在使用信息之前打印版本信息.
Is there a way to print usage text after the description text with python argparse? I have my cmd line argparse working, but i would like to print version info before usage info.
version: 1.0
usage: blahcmd [-h] [-help]
some lovely help
推荐答案
argparse
模块不提供任何添加序言"的选项.显示帮助时,它总是 以 usage:
开头.最好的办法是使用 <实例化 ArgumentParser
时的code> usage 参数:
The argparse
module does not provide any option to add a "prolog". When the help is displayed it always start with usage:
. The best you can do is to customize the usage text adding the version number, using the usage
parameter when you instantiate the ArgumentParser
:
import argparse
parser = argparse.ArgumentParser(usage='Any text you want\n')
请注意,帮助仍将以 usage:
开头.
Note that the help will still start with usage:
.
一种可能可行的肮脏解决方法是,以 \ r
开头 usage
消息:
A dirty workaround that might work is to start the usage
message with a \r
:
>>> import argparse
>>> usage = '\r{}\nusage: %(prog)s etc.'.format('Version a b'.ljust(len('usage:')))
>>> parser = argparse.ArgumentParser(usage=usage)
>>> parser.parse_args(['-h'])
Version a b
usage: etc.
optional arguments:
-h, --help show this help message and exit
我不认为 \ r
的这种用法是可移植的.可能在某些终端上,此技巧不起作用.我已经 just
调整了版本字符串,以确保当技巧生效时,整个 usage:
字符串从字符串中消失了,并且您不会得到之类的东西v1.2e:
(使用简短版本字符串时).
I don't think that this usage of \r
is portable. There are probably some terminals where this trick doesn't work. I've ljust
ed the version string to make sure that when the trick works, the whole usage:
string disappears from string and you don't get things like v1.2e:
when using short version strings.
注意:您必须手动立即创建整个 使用情况
文本.
Note: you must manually create the whole usage
text now.
这篇关于描述后的python argparse打印用法文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!