How to compile * .po gettext translations in setup.py python script

Consider a python package with multilingual support (with help gettext). How to compile files *.poto *.mofiles on the fly at runtime setup.py? I really don't want to distribute precompiled files *.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'
    ]
)

Thanks in advance!

+4
source share
2 answers

, , - : setup.py, po data_files list. package_data, data_files :

, , , , .

, , , , , mo data_files, :

setup(
    .
    .
    .
    data_files=create_mo_files(),
    .
    .
    .
)

create_mo_files(). , . , . , , , , , po, ; , , po - locale/language/LC_MESSAGES/*.po, :

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

( os subprocess, )

+3

*.mo:

import glob
import pathlib
import subprocess
(...)

PO_FILES = 'translations/locale/*/LC_MESSAGES/app_name.po'

def create_mo_files():
    mo_files = []
    prefix = 'app_name'

    for po_path in glob.glob(str(pathlib.Path(prefix) / PO_FILES)):
        mo = pathlib.Path(po_path.replace('.po', '.mo'))

        subprocess.run(['msgfmt', '-o', str(mo), po_path], check=True)
        mo_files.append(str(mo.relative_to(prefix)))

    return mo_files
(...)

setup(
    (...)
    package_data = {
        'app_name': [
            (...)
        ] + create_mo_files(),
    },
)

@edit :

, pl:

app_name/translations/locale/pl/LC_MESSAGES/app_name.po

create_mo_files() app_name.mo

app_name/translations/locale/pl/LC_MESSAGES/app_name.mo

app_name.mo

package/translations/locale/pl/LC_MESSAGES/app_name.po
0

Source: https://habr.com/ru/post/1618454/


All Articles