[Scons-users] Importing Module That is a Build Product

Keith F Prussing kprussing74 at gmail.com
Thu Sep 15 13:32:28 EDT 2016


Hello,

I am trying to understand the behavior of SCons when trying to import a
module in one build rule that is the product of another build rule.
Consider the following example SConstruct:

    def writeit(target, source, env):
        """Generate a mfe module."""
        with open(str(target[0]), "w") as fid:
            fid.write("string = 'hello'\nconst = 1\n")

        return

    def useit(target, source, env):
        """Use the mfe module."""
        # import imp, os
        # path, base = os.path.split(os.path.realpath(str(source[0])))
        # name, _ = os.path.splitext(base)
        # file, pathname, description = imp.find_module(name, [path])
        # imp.load_module(name, file, pathname, description)

        import mfe
        with open(str(target[0]), "w") as fid:
            fid.write("{0}\n{1}\n".format(mfe.string, mfe.const+1))

        return

    test1 = Builder(action=writeit)
    test2 = Builder(action=useit)

    env = Environment(BUILDERS={"writeit" : test1, "useit" : test2})
    mod = env.writeit(target=["mfe.py"], source=[])
    out = env.useit(target=["test.txt"], source=mod)

If I run this as is, the build for 'test.txt' will fail with an
ImportError claiming that it cannot find 'mfe' even if I build 'mfe.py' 
explicitly before building 'test.txt'.  On the other hand, if there is a 
module in the current SConstruct directory, SCons will happily import 
that module with no problems.  My end goal is to generate a module of 
constants to use in the Python parts of my build from a source in a 
different language so that all pieces are using the same values.

I suspected that the problem revolved around the module search path, so
I played around and came up with the commented work around (lines
10-14).  With these lines uncommented, the build for 'test.txt' proceeds
as expected.

So, my question is: How does SCons establish the module search path?  Is
there a better way to actually get the generated module imported?

Searching for variations on 'scons import error' and 'scons import
ignoring current directory' primarily turned up hits revolving around
importing SCons components or where to put custom builders and tools.

Keith

-- 
Keith F Prussing


More information about the Scons-users mailing list