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

查看:87
本文介绍了翻译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: ')引用 gettext .在顶部的argparse.py中,您具有:

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.

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

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