也许这就是你要找的东西: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 解决方案,它不会调用新进程。
祝你好运