2015-01-14 47 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封裝了你試圖實現的內容。