如何使python的argparse生成非英语文本? [英] How to make python's argparse generate Non-English text?

查看:98
本文介绍了如何使python的argparse生成非英语文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

argparse 模块自动生成帮助和使用情况消息".我可以给参数指定非英语名称,并提供非英语帮助文本;但是帮助输出至少会混合两种语言,因为usagepositional argumentsoptional argumentsshow this help message and exit之类的术语会自动以英语生成.

The argparse module "automatically generates help and usage messages". I can give Non-English names to the arguments and provide Non-English help texts; but the help output then becomes a mixture of at least two languages, because terms like usage, positional arguments, optional arguments and show this help message and exit are automatically generated in English.

如何用翻译代替英语输出?

How can I replace this English output with translations?

最好,我想在脚本中提供翻译,以使脚本无论在哪里开始都生成相同的输出.

Preferably, I would like to provide the translations within the script, so that the script generates the same output wherever it is started.

根据乔恩·埃里克(Jon-Eric)的回答,以下是他的解决方案示例:

Based on the answer by Jon-Eric, here an example with his solution:

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)

保存为Beispiel.py

python3 Beispiel.py -h一起给出以下帮助输出:

saved as Beispiel.py gives with python3 Beispiel.py -h the following help output:

Verwendung: Beispiel.py [-h] Eingabe

positional arguments:
  Eingabe

optional arguments:
  -h, --help  zeige diese Hilfe an und tue nichts weiteres

推荐答案

一种方法,来自彼得·奥滕的这篇文章:

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

I don't know much about gettext, but the following suggests that most strings in argparse are properly wrapped:

$ 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

-V"选项的解决方法是添加帮助消息 明确

The workaround for the "-V" option would be to add the help message explicitly

parser.add_argument("-V", ..., help=_("show..."))

您仍然必须自己提供所有翻译.

You still have to provide all translations yourself.

这篇关于如何使python的argparse生成非英语文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆