考虑一个支持多语言的 python 包(使用 gettext
)。如何在执行setup.py
时将*.po
文件动态编译成*.mo
文件?我真的不想分发预编译的 *.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'
]
)
提前致谢!
最佳答案
我知道这个问题开始有点老了,但如果有人还在寻找答案:可以向 setup.py
添加一个函数来编译 po 文件并返回 data_files
list .我没有选择将它们包含在 package_data
中,因为 data_files
的描述看起来更合适:
configuration files, message catalogs, data files, anything which doesn’t fit in the previous categories.
当然你只能将这个列表附加到你已经使用的列表中,但是假设你只有这些 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
才能使用它)
关于python - 如何在 setup.py python 脚本中编译 *.po gettext 翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34070103/