如何在不修补的情况下本地化 Python 的 argparse 模块? [英] How to localize Python's argparse module, without patching it?

查看:22
本文介绍了如何在不修补的情况下本地化 Python 的 argparse 模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

本地化的命令行应用程序看起来很奇怪,其中一些消息是用户语言,而其他部分是英语.

A localized command line application looks strange when some part of the messages are in the user language and some other parts, in English.

我不知道从源代码安装 Python 3 时是否搞砸了什么,似乎没有 *.mo 文件,所以 argparse(在整个)不知道本地化.

I don't know if I messed up anything when I installed Python 3 from source, it seems there are no *.mo files, so argparse (among the whole) is not localization aware.

API 似乎也没有提供本地化的方法.还是我错过了?

The API does not seems to offer a way to localize, neither. Or did I missed it?

我可以修补 argparse.py,但我不会,因为我希望它是可移植的,而且我不同意建议用户修补他们的 Python 安装.

I could patch argparse.py, but I won't, as I want it to be portable, and I'm not OK with suggesting users to patch their Python installation.

问题简而言之:如何在不修补 Python 标准库的情况下本地化 argpase?

Question in fewer words: how to localize argpase without patching Python standard library?

相关问题:这可能吗?

推荐答案

默认情况下 argparse 使用 gettext 模块来翻译消息,因此您可以轻松地翻译它们想要.

By default argparse uses the gettext module to translate the messages so you can easily translate them if you want to.

要生成 *.pot 文件(您可以在翻译后将其转换为 *.mo 文件),您可以使用 pygettext 程序可在 python 的内置 gettext 模块中使用.

To generate the *.pot files (which you can convert to *.mo files after translation) you can use the pygettext program which is available in the built-in gettext module in python.

用法:

python pygettext.py argparse.py

这将生成一个您可以翻译的 messages.pot,然后生成 .mo(很多方法可以做到这一点,只是谷歌).

This will generate a messages.pot which you can translate, after that just generate the .mo (many ways to do this, just google).

有关 pygettext 的更多信息,请参阅有关该主题的 Python 手册:国际化您的程序和模块.

For more info about pygettext see the Python manual about the subject: Internationalizing your programs and modules.

这篇关于如何在不修补的情况下本地化 Python 的 argparse 模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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