I write a python function such as replace strings and called in scons script.
def Replace(env, filename, old, new):
with open(filename,"r+") as f:
d = f.read()
d = d.replace(old, new)
f.truncate(0)
f.seek(0)
f.write(d)
f.close()
env.AddMethod(Replace,'Replace')
In SConscript
lib = env.SharedLibrary('lib', object, extra_libs)
tmp = env.Command([],[],[env.Replace(somefile, 'A', 'b')] )
env.Depends(tmp,lib )
What i expect is to run the Replace() method after the lib built.
but scons always run the Replace() in the first round script parsing phrase.
it seems i am missing some dependency.
I believe that you’re probably looking for builders that execute python functions.
The tricky bit is that SCons doesn’t really want to work the way you’re forcing it to. Build actions should be repeatable and non-destructive, in your code you’re actually destroying the original contents of
somefile. Instead, you can use the target/source paradigm and some kind of template file to achieve the same result.Note that in my testing, the replace function wasn’t playing nicely with multi-line data, so I’ve just swapped to using full regular expressions (
re.sub). This is probably slower, but offers significantly more flexibility.