如何让docstring尊重PEP257,同时可以使用docopt来使用gettext来符合i18n?

根据
PEP 257,命令行脚本的docstring应该是它的用法消息:

The docstring of a script (a stand-alone program) should be usable as its “usage” message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a “-h” option, for “help”). Such a docstring should document the script’s function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.

并且docstring应该是作为模块级别的第一个字符串,在其他任何东西之前,作为__doc__可用.

现在,我也使用docopt作为使用消息解析器,所以我只需要编写doc字符串,并且它自己构建命令行解析器,这很好.

_("""...""")

什么不是那么好,是我找不到一种方法来将文档字符串标记为可用于gettext的i18nable,因此我可以在给予docopt时将其转换为其他语言.当时我得到的唯一解决方案是在翻译所有应用程序的其他字符串时使用和帮助消息保持英文!

正如PEP 20所述:

There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.

什么是解决无法将文档字符串标记为可翻译优雅的限制的最佳方法?

N.B.:这里我们认为我在__init__.py模块中执行gettext.install(),以便在解析__doc__之前,内部存在_().

最佳答案 目前,这是一个我正在考虑的解决方案:

"""\
This is the docstring
"""

import docopt
if __name__ == "__main__":
    try:
        args = docopt.docopt(_("{docstring}").format(docstring=__doc__))
    except KeyError:
        args = docopt.docopt(_("{docstring}")) # string which will be replaced by the i18ned one.

我没有发现那么优雅,因为即使python中的异常是可以的,我认为它们应该被保留用于特殊情况而不是应用程序的用例.

它也是一个非常顽皮的黑客,它将在gettext中获取docstring格式而不是__docopt__文本,这将无法帮助翻译,因为他们必须回到源代码…

点赞