翻译 argparse 的内部字符串 [英] Translate argparse's internal strings

查看:28
本文介绍了翻译 argparse 的内部字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何翻译 Python 的 argparse 模块字符串?

How can I translate Python's argparse module strings?

例如,当您显示帮助时,它会显示"usage:",可翻译的字符串,但我不知道如何在我的程序中进行.

For example, when you display the help, it says "usage: ", string that is translatable but I don't know how to do it in my program.

这是argparse.py的源代码部分:

def _format_usage(self, usage, actions, groups, prefix):
        if prefix is None:
            prefix = _('usage: ')

我无法追踪设置此前缀的方式,我认为这是内部的.

I couldn't trace the way to set this prefix, I think this is internal.

我不想将 .mo 文件附加到系统中的某个地方.理想情况下,翻译应该位于我的程序目录中,或者更好地位于源代码中.

I don't want to have to append a .mo file to somewhere in the system. Ideally the translation should live in my program directory, or better in the source code.

任何帮助将不胜感激.

推荐答案

运行以下:

import argparse

class MyHelpFormatter(argparse.HelpFormatter):
    def __init__(self, *args, **kwargs):
        super(MyHelpFormatter, self).__init__(*args, **kwargs)

    def _format_usage(self, usage, actions, groups, prefix):
        return super(MyHelpFormatter, self)._format_usage(
            usage, actions, groups, prefix if prefix else "bla: ")

class MyArgumentParser(argparse.ArgumentParser):
    def __init__(self, *args, **kwargs):
        kwargs['formatter_class']=MyHelpFormatter
        super(MyArgumentParser, self).__init__(*args, **kwargs)


p = MyArgumentParser(description='Foo')
p.add_argument('foo', type=str)
print p.parse_args()

印刷品

python myargparse.py  --help
bla: myargparse.py [-h] foo

Foo

positional arguments:
  foo

optional arguments:
  -h, --help  show this help message and exit

_('usage: ') 引用 获取文本.在 argparse.py 中,在顶部,您有:

_('usage: ') references gettext. In argparse.py, at the top, you have:

from gettext import gettext as _

你可以稍微使用 gettext.

给定一个 .po 文件:

msgid "usage: "
msgstr "foobar: "

您可以将其转换为 .mo 文件(例如 此处).

You can convert it to a .mo file (for example here).

之后(其中./foo/LC_MESSAGES/messages.mo是编译.po的结果):

Afterwards (where ./foo/LC_MESSAGES/messages.mo is the result of compiling the .po):

~/Desktop> find . -name *mo
./foo/LC_MESSAGES/messages.mo
~/Desktop> cat myargparse2.py
import argparse
import gettext
gettext.bindtextdomain(gettext.textdomain(), '.')
p = argparse.ArgumentParser(description='Foo')
p.add_argument('foo', type=str)
print p.parse_args()
~/Desktop> LANGUAGE=foo python myargparse2.py
foobar: myargparse2.py [-h] foo
myargparse2.py: error: too few arguments

使用您想要的语言而不是 foo.

Use your desired languages instead of foo.

这篇关于翻译 argparse 的内部字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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