Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SCons:如何在SCons脚本中调用自定义python函数并建立正确的依赖关系_Python_Scons - Fatal编程技术网

SCons:如何在SCons脚本中调用自定义python函数并建立正确的依赖关系

SCons:如何在SCons脚本中调用自定义python函数并建立正确的依赖关系,python,scons,Python,Scons,我编写了一个python函数,比如replace strings,并在scons脚本中调用 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,'Re

我编写了一个python函数,比如replace strings,并在scons脚本中调用

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')
讽刺地

lib = env.SharedLibrary('lib', object, extra_libs)
tmp = env.Command([],[],[env.Replace(somefile, 'A', 'b')] )
env.Depends(tmp,lib )
我希望在构建lib之后运行Replace()方法。 但是SCON总是在第一轮脚本解析阶段运行Replace()。
看来我缺少了一些依赖性。

我相信您可能正在寻找

棘手的一点是,SCons并不真的想按你强迫它的方式工作。构建操作应该是可重复和非破坏性的,在您的代码中,您实际上是在破坏
somefile
的原始内容。相反,您可以使用目标/源范例和某种模板文件来实现相同的结果

import os
import re

def replace_action(target, source, env):
    # NB. this is a pretty sloppy way to write a builder, but
    #     for things that are used internally or infrequently
    #     it should be more than sufficient
    assert( len(target) == 1 )
    assert( len(source) == 1 )
    srcf = str(source[0])
    dstf = str(target[0])
    with open(srcf, "r") as f:
        contents = f.read()
        # In cases where this builder fails, check to make sure you
        # have correctly added REPLST to your environment
        for old, new in env['REPLST']:
            contents = re.sub( old, new, contents )
        with open( dstf, "w") as outf:
            outf.write(contents)

replace_builder = Builder(action = replace_action)

env = Environment( ENV = os.environ )
env.Append( BUILDERS = {'Replace' : replace_builder } )
b = env.Replace( 'somefile', ['somefile.tmpl'], REPLST=[('A','b')] )
lib = env.SharedLibrary('lib', object + [b], extra_libs )
请注意,在我的测试中,replace函数不能很好地处理多行数据,因此我只使用了完整的正则表达式(
re.sub
)。这可能较慢,但提供了更大的灵活性