如何在setup.py中执行(安全)bash shell命令?

发布于 2021-01-29 17:28:55

我使用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
关注者
0
被浏览
175
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    请原谅快速的自我解答。我希望这可以帮助以太坊之外的人。现在,我想分享一个我满意的解决方案。

    这是一个安全的解决方案,基于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},
          ...
         )
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看