如何在setup.py中执行(安全)bash shell命令?
我使用nunjucks在python项目中模板化前端。Nunjucks模板 必须
在生产中预先编译。我在nunjucks模板中不使用扩展名或异步过滤器。我宁愿使用nunjucks-
precompile命令(通过npm提供)而不是使用grunt-task来监听对模板的更改,而是将整个模板目录扫入template.js。
这个想法是让nunjucks-precompile --include ["\\.tmpl$"] path/to/templates >
templates.js
命令在setup.py中执行,因此我可以简单地搭载我们的部署脚本的常规执行。
我发现setuptools覆盖和distutils
scripts参数可能用于正确的目的,但是我不确定这是否是最简单的执行方法。
另一种方法是用于subprocess
直接在setup.py中执行命令,但是我已经被警告不要这样做(而是先发地恕我直言)。我不太了解为什么不这样做。
有任何想法吗?肯定吗 确认吗?
更新(04/2015): -如果您没有nunjucks-precompile
可用的命令,只需使用Node Package
Manager来安装nunjucks,如下所示:
$ npm install nunjucks
-
请原谅快速的自我解答。我希望这可以帮助以太坊之外的人。现在,我想分享一个我满意的解决方案。
这是一个安全的解决方案,基于Peter Lamut的文章。请注意,这在子流程调用中 不 使用shell =
True。您可以绕过python部署系统上的grunt-task要求,也可以将其用于混淆和JS打包。from setuptools import setup from setuptools.command.install import install import subprocess import os class CustomInstallCommand(install): """Custom install setup to help run shell commands (outside shell) before installation""" def run(self): dir_path = os.path.dirname(os.path.realpath(__file__)) template_path = os.path.join(dir_path, 'src/path/to/templates') templatejs_path = os.path.join(dir_path, 'src/path/to/templates.js') templatejs = subprocess.check_output([ 'nunjucks-precompile', '--include', '["\\.tmpl$"]', template_path ]) f = open(templatejs_path, 'w') f.write(templatejs) f.close() install.run(self) setup(cmdclass={'install': CustomInstallCommand}, ... )