How can I get SCons to replace text in installed text files

旧街凉风 提交于 2019-12-07 06:46:15

问题


I'd like to be able to replace a template variable ('$(SOFTWARE_VERSION)') while installing some python scripts from scons. Does scons already have such functionality? If not, what's the best way to hook into the scons install process so I can do this during install?


回答1:


You could use the Substfile method. This takes a input file and produces an output file substituting marked variables. So if you have script.py.in:

#!/usr/bin/python
print "$SOFTWARE_VERSION"

Then you can use the following SConsctruct file to generate an output:

env = Environment(tools=['textfile'])
script_dict = {'\$SOFTWARE_VERSION': '1.0'}
env.Substfile('script.py.in', SUBST_DICT = script_dict)

You need to escape the $ in the string '\$SOFTWARE_VERSION' otherwise SCons interprets it as an internal environment variable. The result would be a file script.py with this contents:

#!/usr/bin/python
print "1.0"

You can then install this resulting substituted file using env.Install.




回答2:


You can can define a Builder that takes the template file as an input and produces the substituted data as output. The most flexible way is to use a Python function as the Action of your builder. This way you can use Python's rich regular expression support to perform the substitution. As for the variables and their values, you could tap into the construction variables from the "env" argument to the function. If all the variables happen to be construction variables, you can use env.subst() to do the search and replace for you.

Alternatively, if this is a one-off, you can simply use a Command that shells out to "sed" or similar program and do all the work for you.



来源:https://stackoverflow.com/questions/5010320/how-can-i-get-scons-to-replace-text-in-installed-text-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!