使用PyBab以编程方式提取消息

2024-04-30 01:49:35 发布

您现在位置:Python中文网/ 问答频道 /正文

现在,我正在用

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

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

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


Tags: 文件方法消息文章extractcallcfgsetuptools
2条回答

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

我将展示一些运行babelpython代码的替代方法,而不创建新的子进程,从高到低。在

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

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脚本实际上是这样做的:

^{pr2}$

但是你可以避免在系统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解决方案,它不调用新进程。在

祝你好运

我现在使用操作系统来执行此脚本:

#!venv/bin/python
import os

pybabel = 'venv/bin/pybabel'
os.system(pybabel + ' extract -F babel.cfg -k lazy_gettext -o messages.pot app')
os.system(pybabel + ' update -i messages.pot -d app/translations')
os.unlink('messages.pot')

希望它能给你一个主意

相关问题 更多 >