如何在 setup.py python 脚本中编译 *.po gettext 翻译

Jan*_*uis 5 python distutils gettext setup.py po

考虑一个具有多语言支持的 python 包(使用gettext)。执行时如何将*.po文件*.mo即时编译为文件setup.py?我真的不想分发预编译*.mo文件。

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from distutils.core import setup

setup(
    name='tractorbeam',
    version='0.1.0',
    url='http://starfleet.org/tractorbeam/',
    description='Pull beer out of the fridge while sitting on the couch.',

    author='James T. Kirk',
    author_email= 'jkirk@starfleet.org',

    packages=['tractorbeam'],
    package_data={
        'tractorbeam': [
            'locale/*.po',
            'locale/*.mo',  # How to compile on the fly?
        ]
    },

    install_requires=[
        'requests'
    ]
)
Run Code Online (Sandbox Code Playgroud)

提前致谢!

zez*_*llo 4

我知道这个问题开始有点老了,但如果有人仍在寻找答案:可以添加一个函数来setup.py编译 po 文件并返回data_fileslist。我没有选择将它们包含在内,package_data因为data_files其描述看起来更合适:

\n\n
\n

配置文件,消息目录,数据文件,任何不属于前面类别的\xe2\x80\x99。

\n
\n\n

当然,您只能将此列表附加到您已经使用的列表中,但假设您只有这些 mo 文件要添加到 data_files 中,您可以编写:

\n\n
setup(\n    .\n    .\n    .\n    data_files=create_mo_files(),\n    .\n    .\n    .\n)\n
Run Code Online (Sandbox Code Playgroud)\n\n

供您参考,这是我使用的函数create_mo_files()。我不会假装这是最好的实现。我把它放在这里是因为它看起来很有用并且很容易适应。请注意,它比您需要的要复杂一点,因为它不假设每个目录只有一个 po 文件要编译,而是处理多个 po 文件;另请注意,它假设所有 po 文件都位于类似 的位置locale/language/LC_MESSAGES/*.po,您必须更改它以满足您的需求:

\n\n
def create_mo_files():\n    data_files = []\n    localedir = \'relative/path/to/locale\'\n    po_dirs = [localedir + \'/\' + l + \'/LC_MESSAGES/\'\n               for l in next(os.walk(localedir))[1]]\n    for d in po_dirs:\n        mo_files = []\n        po_files = [f\n                    for f in next(os.walk(d))[2]\n                    if os.path.splitext(f)[1] == \'.po\']\n        for po_file in po_files:\n            filename, extension = os.path.splitext(po_file)\n            mo_file = filename + \'.mo\'\n            msgfmt_cmd = \'msgfmt {} -o {}\'.format(d + po_file, d + mo_file)\n            subprocess.call(msgfmt_cmd, shell=True)\n            mo_files.append(d + mo_file)\n        data_files.append((d, mo_files))\n    return data_files\n
Run Code Online (Sandbox Code Playgroud)\n\n

(您必须导入ossubprocess使用它)

\n