2015-01-14 40 views
1

我使用nunjucks模拟python项目中的前端。必须在生产中预编译Nunjucks模板必须。我不在nunjucks模板中使用扩展或异步过滤器。我宁愿使用nunjucks-precompile命令(通过npm提供)将整个模板目录扫描到templates.js中,而不是使用grunt-task来监听对模板的更改。如何在setup.py中执行(安全)bash shell命令?

想法是在setup.py中执行nunjucks-precompile --include ["\\.tmpl$"] path/to/templates > templates.js命令,这样我就可以简单地搭载我们的部署者脚本的常规执行。

我发现a setuptools overridea distutils scripts argument可能有正确的目的,但我不太确定哪一种是最简单的执行方法。

另一种方法是使用subprocess直接在setup.py中执行该命令,但我已被告诫不要这(相当抢先恕我直言)。我真的不明白为什么不。

任何想法?誓?确认?

更新(04/2015): - 如果你没有nunjucks-precompile命令可用做什么,只需使用节点包管理器安装nunjucks像这样:

$ npm install nunjucks 

回答

3

赦免快速自答案。我希望这可以帮助那些以外的人。现在我想分享一下我已经制定出满意的解决方案。

这是一个安全的解决方案,基于Peter Lamut's write-up。请注意,这是而不是在子流程调用中使用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}, 
     ... 
    ) 
0

我认为链接here封装了你试图实现的内容。