How to execute a (safe) bash shell command within setup.py?

后端 未结 2 956
情歌与酒
情歌与酒 2020-12-10 21:13

I use nunjucks for templating the frontend in a python project. Nunjucks templates must be precompiled in production. I don\'t use extensions or asynchronous filt

相关标签:
2条回答
  • 2020-12-10 21:45

    I think that the link here encapsulates what you are trying to achieve.

    0 讨论(0)
  • 2020-12-10 21:53

    Pardon the quick self-answer. I hope this helps someone out there in the ether. I want to share this now that I've worked out a solution I'm satisfied with.

    Here's a solution that's safe and based on Peter Lamut's write-up. Note that this does not use shell=True in the subprocess invocation. You may bypass grunt-task requirements on your python deployment system and also use this for obfuscation and JS packaging all the same.

    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 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题