是否有既定的方法将gettext locale/xy/LC_MESSAGES/*嵌入到捆绑中?特别是要让Gtks自动转换小部件,从ZIP存档中提取它们。
对于其他嵌入式资源,pkgutil.get_deta或inspect/get_source工作得足够好。但是,系统和Python依赖于提供了一个普通的旧gettext API;没有资源或字符串等等。
因此,我无法想出一个可行的、甚至是完全实用的解决办法:
gvfs**/**gio 虚拟路径
现在,使用archive://file%3A%2F%2Fmypkg.pyz%2Fmessages%2F IRIs可以替代直接从zip读取其他文件。但是dgettext仍然只是系统库的一个薄包装器。因此,任何这样的URL都不能用作localedir。.mo**/**.po 提取
现在,手动读取消息目录,或者仅仅使用琐碎的切分就可以了。但只适用于应用程序中的字符串。这也不可能让Gtk/GtkBuilder隐式地捡起它们。
因此,我不得不手动遍历整个小部件树、标签、文本、内部小部件、markup_text等等。gvfs-mount等,只是看起来像是占用了一定的内存。我怀疑它是否会保持可靠,例如两个应用程序实例正在运行,或者先前的一个不干净的终止。(我不知道,由于一个系统库,比如gettext,在脆弱的拉链熔断点上绊倒了。)是否有更可靠的方法?
发布于 2015-04-28 22:07:45
这是我的示例Glade/GtkBuilder/Gtk应用程序。我已经定义了一个函数xml_gettext,它透明地转换glade文件并以字符串的形式传递给gtk.Builder实例。
import mygettext as gettext
import os
import sys
import gtk
from gtk import glade
glade_xml = '''<?xml version="1.0" encoding="UTF-8"?>
<interface>
<!-- interface-requires gtk+ 3.0 -->
<object class="GtkWindow" id="window1">
<property name="can_focus">False</property>
<signal name="delete-event" handler="onDeleteWindow" swapped="no"/>
<child>
<object class="GtkButton" id="button1">
<property name="label" translatable="yes">Welcome to Python!</property>
<property name="use_action_appearance">False</property>
<property name="visible">True</property>
<property name="can_focus">True</property>
<property name="receives_default">True</property>
<property name="use_action_appearance">False</property>
<signal name="pressed" handler="onButtonPressed" swapped="no"/>
</object>
</child>
</object>
</interface>'''
class Handler:
def onDeleteWindow(self, *args):
gtk.main_quit(*args)
def onButtonPressed(self, button):
print('locale: {}\nLANGUAGE: {}'.format(
gettext.find('myapp','locale'),os.environ['LANGUAGE']))
def main():
builder = gtk.Builder()
translated_xml = gettext.xml_gettext(glade_xml)
builder.add_from_string(translated_xml)
builder.connect_signals(Handler())
window = builder.get_object("window1")
window.show_all()
gtk.main()
if __name__ == '__main__':
main() 我已经将我的地区目录存档到locale.zip中,它包含在pyz包中。
这是locale.zip的内容
(u'/locale/fr_FR/LC_MESSAGES/myapp.mo',
u'/locale/en_US/LC_MESSAGES/myapp.mo',
u'/locale/en_IN/LC_MESSAGES/myapp.mo')为了使locale.zip成为一个文件系统,我使用了来自文件系统的ZipFS。
幸运的是,Python gettext不是gettext。gettext是纯Python,它不使用gettext,而是模仿它。gettext有两个核心功能:find和translation。我在一个名为mygettext的独立模块中重新定义了这两个模块,以使它们使用来自ZipFS的文件。
gettext使用os.path、os.path.exists和open查找文件并打开它们,我将它们替换为等效的表单fs模块。
这是我申请的内容。
pyzzer.pyz -i glade_v1.pyz
# A zipped Python application
# Built with pyzzer
Archive contents:
glade_dist/glade_example.py
glade_dist/locale.zip
glade_dist/__init__.py
glade_dist/mygettext.py
__main__.py由于pyz文件中有文本(通常是一个文本),所以在以二进制模式打开pyz文件之后,我跳过了这一行。应用程序中希望使用gettext.gettext函数的其他模块应该从mygettext导入zfs_gettext,并将其作为_的别名。
mygettext.py来了。
from errno import ENOENT
from gettext import _expand_lang, _translations, _default_localedir
from gettext import GNUTranslations, NullTranslations
import gettext
import copy
import os
import sys
from xml.etree import ElementTree as ET
import zipfile
import fs
from fs.zipfs import ZipFS
zfs = None
if zipfile.is_zipfile(sys.argv[0]):
try:
myself = open(sys.argv[0],'rb')
next(myself)
zfs = ZipFS(ZipFS(myself,'r').open('glade_dist/locale.zip','rb'))
except:
pass
else:
try:
zfs = ZipFS('locale.zip','r')
except:
pass
if zfs:
os.path = fs.path
os.path.exists = zfs.exists
open = zfs.open
def find(domain, localedir=None, languages=None, all=0):
# Get some reasonable defaults for arguments that were not supplied
if localedir is None:
localedir = _default_localedir
if languages is None:
languages = []
for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
val = os.environ.get(envar)
if val:
languages = val.split(':')
break
if 'C' not in languages:
languages.append('C')
# now normalize and expand the languages
nelangs = []
for lang in languages:
for nelang in _expand_lang(lang):
if nelang not in nelangs:
nelangs.append(nelang)
# select a language
if all:
result = []
else:
result = None
for lang in nelangs:
if lang == 'C':
break
mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
mofile_lp = os.path.join("/usr/share/locale-langpack", lang,
'LC_MESSAGES', '%s.mo' % domain)
# first look into the standard locale dir, then into the
# langpack locale dir
# standard mo file
if os.path.exists(mofile):
if all:
result.append(mofile)
else:
return mofile
# langpack mofile -> use it
if os.path.exists(mofile_lp):
if all:
result.append(mofile_lp)
else:
return mofile
# langpack mofile -> use it
if os.path.exists(mofile_lp):
if all:
result.append(mofile_lp)
else:
return mofile_lp
return result
def translation(domain, localedir=None, languages=None,
class_=None, fallback=False, codeset=None):
if class_ is None:
class_ = GNUTranslations
mofiles = find(domain, localedir, languages, all=1)
if not mofiles:
if fallback:
return NullTranslations()
raise IOError(ENOENT, 'No translation file found for domain', domain)
# Avoid opening, reading, and parsing the .mo file after it's been done
# once.
result = None
for mofile in mofiles:
key = (class_, os.path.abspath(mofile))
t = _translations.get(key)
if t is None:
with open(mofile, 'rb') as fp:
t = _translations.setdefault(key, class_(fp))
# Copy the translation object to allow setting fallbacks and
# output charset. All other instance data is shared with the
# cached object.
t = copy.copy(t)
if codeset:
t.set_output_charset(codeset)
if result is None:
result = t
else:
result.add_fallback(t)
return result
def xml_gettext(xml_str):
root = ET.fromstring(xml_str)
labels = root.findall('.//*[@name="label"][@translatable="yes"]')
for label in labels:
label.text = _(label.text)
return ET.tostring(root)
gettext.find = find
gettext.translation = translation
_ = zfs_gettext = gettext.gettext
gettext.bindtextdomain('myapp','locale')
gettext.textdomain('myapp')下面两个不应该被调用,因为glade不使用Python gettext。
glade.bindtextdomain('myapp','locale')
glade.textdomain('myapp')https://stackoverflow.com/questions/29686259
复制相似问题