【问题标题】:How to execute a (safe) bash shell command within setup.py?如何在 setup.py 中执行(安全)bash shell 命令?
【发布时间】:2015-01-14 19:04:12
【问题描述】:

我在 python 项目中使用 nunjucks 模板化前端。 Nunjucks 模板必须在生产中进行预编译。我不在 nunjucks 模板中使用扩展或异步过滤器。比起使用 grunt-task 来监听我的模板的变化,我更喜欢使用 nunjucks-precompile 命令(通过 npm 提供)将整个模板目录扫描到 templates.js 中。

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

我发现 a setuptools overridea distutils scripts argument 可能有正确的用途,但我不太确定这两种方法是否是最简单的执行方法。

另一种方法是使用subprocess 直接在 setup.py 中执行命令,但我已被警告不要这样做(恕我直言)。我不太明白为什么不这样做。

有什么想法吗?肯定?确认?

更新 (04/2015): - 如果您没有可用的 nunjucks-precompile 命令,只需使用 Node Package Manager 安装 nunjucks,如下所示:

$ npm install nunjucks

【问题讨论】:

    标签: python setuptools nunjucks


    【解决方案1】:

    请原谅快速的自我回答。我希望这可以帮助外面的人。现在我想分享这个,因为我已经找到了一个我满意的解决方案。

    这是基于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},
          ...
         )
    

    【讨论】:

      【解决方案2】:

      我认为链接here 封装了您想要实现的目标。

      【讨论】:

        猜你喜欢
        • 2014-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-11-03
        • 2019-09-27
        • 1970-01-01
        • 1970-01-01
        • 2015-01-03
        相关资源
        最近更新 更多