如何让python的argparse生成非英文文本?

Wol*_*ram 9 python internationalization argparse

argparse模块"自动生成的帮助和使用信息".我可以给论证提供非英语名称,并提供非英语帮助文本; 但帮助输出就变成了至少两种语言的混合物,因为条款喜欢usage,positional arguments,optional argumentsshow this help message and exit在英文自动生成.

如何用翻译替换这个英文输出?

最好,我想在脚本中提供翻译,以便脚本在任何地方生成相同的输出.

编辑:基于Jon-Eric的回答,这是他的解决方案的一个例子:

import gettext

def Übersetzung(Text):
    Text = Text.replace("usage", "Verwendung")
    Text = Text.replace("show this help message and exit",
                        "zeige diese Hilfe an und tue nichts weiteres")
    Text = Text.replace("error:", "Fehler:")
    Text = Text.replace("the following arguments are required:",
                        "Die folgenden Argumente müssen angegeben werden:")
    return Text
gettext.gettext = Übersetzung

import argparse

Parser = argparse.ArgumentParser()
Parser.add_argument("Eingabe")
Argumente = Parser.parse_args()

print(Argumente.Eingabe)
Run Code Online (Sandbox Code Playgroud)

Beispiel.py使用python3 Beispiel.py -h以下帮助输出保存为给定:

Verwendung: Beispiel.py [-h] Eingabe

positional arguments:
  Eingabe

optional arguments:
  -h, --help  zeige diese Hilfe an und tue nichts weiteres
Run Code Online (Sandbox Code Playgroud)

Fil*_*tek 5

argparse使用gettext受GNU gettext启发API.您可以使用此API以argparse相对干净的方式集成您的翻译.

为此,请在argparse输出任何文本之前调用以下代码(但可能在之后import argparse):

import gettext

# Use values that suit your project instead of 'argparse' and 'path/to/locale'
gettext.bindtextdomain('argparse', 'path/to/locale')
gettext.textdomain('argparse')
Run Code Online (Sandbox Code Playgroud)

为了使此解决方案的工作,你的翻译argparse必须位于path/to/locale/ll/LC_MESSAGES/argparse.mo其中ll是当前语言的代码(例如de,可以通过设置环境变量被配置用于例如LANGUAGE).

你如何生成.mo文件?

  1. pygettext --default-domain=argparse /usr/local/lib/python3.5/argparse.py
    • 使用的实际位置 argparse.py
    • 创建文件 argparse.pot
  2. cp argparse.pot argparse-ll.po
    • 使用实际的语言代码而不是 ll
  3. 填写缺少的翻译字符串 argparse-ll.po
  4. msgfmt argparse-ll.po -o locale/ll/LC_MESSAGES/argparse.mo

gettext文档关于创建.mo文件.

我有更多的细节发表这些指令README.md我的的捷克语翻译argparse.


Jon*_*ric 4

一种方式,来自Peter Otten 的这篇文章:

我对 gettext 不太了解,但以下内容表明 argparse 中的大多数字符串都已正确包装:

$ cat localize_argparse.py

import gettext

def my_gettext(s):
    return s.upper()
gettext.gettext = my_gettext

import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-V", action="version")
    args = parser.parse_args()

$ python localize_argparse.py -h USAGE: localize_argparse.py [-h] [-V]

OPTIONAL ARGUMENTS:   -h, --help  SHOW THIS HELP MESSAGE AND EXIT   -V
show program's version number and exit
Run Code Online (Sandbox Code Playgroud)

“-V”选项的解决方法是显式添加帮助消息

parser.add_argument("-V", ..., help=_("show..."))
Run Code Online (Sandbox Code Playgroud)

您仍然需要自己提供所有翻译。