python - 使用 PyBabel 以编程方式提取消息

标签 python setuptools python-babel

现在,我正在使用提取消息

pybabel extract -F babel.cfg -o messages.pot .

这会遍历我的所有 Python 文件并正确提取消息。但是,我通过 subprocess.call() 调用它,这非常难看,因为 PyBbel 也是用 Python 编写的。

我查看了 PyBabel,它使用 setuptools 命令来完成其工作。我可以将 extract_messages.run() 方法复制到我的 Python 脚本中,但感觉不太优雅。有更好的方法吗?有大量关于如何创建新的 setuptools 命令的文章,但没有人写关于调用它们的文章......

最佳答案

也许这就是您正在寻找的:How do i run the python 'sdist' command from within a python automated script without using subprocess?

我将展示一些从较高级别到较低级别运行 Babel Python 代码的替代方案,而无需创建新的子进程。

这是一种黑客攻击,取自上面链接的答案:

from setuptools.dist import Distribution
from babel.messages.frontend import extract_messages

dist = Distribution({'name': 'my-project', 'version': '1.0.0'}) # etc.
dist.script_name = 'setup.py'
cmd = extract_messages(dist)
cmd.ensure_finalized()
cmd.run()  # TODO: error handling

pylabel 脚本实际上做了这样的事情:

from babel.messages.frontend import main

sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())

但是您可以避免通过 sys.argv 发送命令,并实际从 babel 调用 CommandInterface python 代码。

这是我最喜欢的称呼方式:

from babel.messages.frontend import CommandLineInterface

CommandLineInterface().run(['pybabel','extract','-F','babel.cfg','-k','lazy_gettext','-o','messages.pot','sample_project'])
CommandLineInterface().run(['pybabel','init','-i','messages.pot','-d','translations','-l','en'])
CommandLineInterface().run(['pybabel','compile','-d','translations'])
CommandLineInterface().run(['pybabel','update','-d','translations'])

这是您可以获得的最接近低级代码的结果,除非您想开始复制/粘贴并自定义 python 代码。再次强调,这是一个 100% python 解决方案,并且它不会调用新进程。

祝你好运

关于python - 使用 PyBabel 以编程方式提取消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45485057/

相关文章:

python - Matplotlib plt.show() 不显示图表

python - 如何在 travis 构建期间更新 tox 上的设置工具

python - 获取导入错误 : No module named control when following google cloud endpoint tutorial

python - Conda setuptools install 将 shebangs 更改为默认 python 安装

python - 如何在不使用 setup.py 文件的情况下构建源代码分发?

python - 如何以多种语言显示日期/时间?

python - 如何在 View 和模板之外使用 Pyramid i18n?

python - 在 Jinja2 中使用 babel 链接

python - 即使在专门包含之后,PyInstaller 仍然缺少模块错误

python - 在 Pandas DataFrame 中格式化 Float64Index