<p>我花了一些时间创建了一个脚本,它使用系统上可用的<em>所有</em>区域设置,并尝试在其中打印一条众所周知的消息。请注意,“所有区域设置”只包括编码更改,不管怎样,这些更改都被Python否定,而且很多翻译都是不完整的,所以请使用回退。在</p>
<p>显然,您还必须对<code>xgettext</code>(或等效值)的使用进行适当的更改,以使您的实际代码能够识别转换函数。在</p>
<pre><code>#!/usr/bin/env python3
import gettext
import os
def all_languages():
rv = []
for lang in os.listdir(gettext._default_localedir):
base = lang.split('_')[0].split('.')[0].split('@')[0]
if 2 <= len(base) <= 3 and all(c.islower() for c in base):
if base != 'all':
rv.append(lang)
rv.sort()
rv.append('C.UTF-8')
rv.append('C')
return rv
class Domain:
def __init__(self, domain):
self._domain = domain
self._translations = {}
def _get_translation(self, lang):
try:
return self._translations[lang]
except KeyError:
# The fact that `fallback=True` is not the default is a serious design flaw.
rv = self._translations[lang] = gettext.translation(self._domain, languages=[lang], fallback=True)
return rv
def get(self, lang, msg):
return self._get_translation(lang).gettext(msg)
def print_messages(domain, msg):
domain = Domain(domain)
for lang in all_languages():
print(lang, ':', domain.get(lang, msg))
def main():
print_messages('libc', 'No such file or directory')
if __name__ == '__main__':
main()
</code></pre>