Search code examples
pythonsconsconan

Read a file and extract data and assign to a variable from a python file


I am trying to extract BINPATH, LIBPATH,CPPPATH from a conan.txt file which looks like:

conan = {

    "conan" : {
        "CPPPATH"     : ['something'],
        "BINPATH"     : ['something'],
        "LIBS"        : ['something'],
        "CPPDEFINES"  : [],
        "CXXFLAGS"    : [],
        "CCFLAGS"     : [],
        "SHLINKFLAGS" : [],
        "LINKFLAGS"   : [],
    },
    "conan_version" : "None",

    "boost" : {
        "CPPPATH"     : ['C:\\.conan\\123456\\1\\include'],
        "LIBPATH"     : ['C:\\.conan\\123456\\1\\lib'],
        "BINPATH"     : ['C:\\.conan\\123456\\1\\lib'],
        "LIBS"        : [],
        "CPPDEFINES"  : [],
        "CXXFLAGS"    : [],
        "CCFLAGS"     : [],
        "SHLINKFLAGS" : [],
        "LINKFLAGS"   : [],
    },
    "boost_version" : "1.69.0"
}
Return('conan')

I have a scons /python file which needs CPPPATH,BINPATH,LIBPATH values as variable. I am trying to extract these values in following function in Sconscript :

def getCPPPath():
          data = {'Return': lambda x: False}
            with open(file.txt, 'r') as f:
             exec(f.read(), data)
             return (data["conan"]["conan"]["CPPPATH"][0])
             print ("Path is:", ["conan"]["conan"]["CPPPATH"][0])

This gives me an error:

scons: *** Return of non-existent variable ''conan''

How can I achieve this?


Solution

  • You can use the following code. Note that exec is insecure as it runs all the code that is in your file.txt. You also need to pass a dummy Return function into exec.

    data = {"Return": lambda x: False}
    
    with open("file.txt", "r", encoding="utf-8") as f:
        exec(f.read(), data)
    
    print(data['conan']['conan']['BINPATH'][0])
    print(data['conan']['boost']['LIBPATH'][0])
    print(data['conan']['conan']['CPPPATH'][0])
    

    Prints

    ['something']
    ['C:\\.conan\\123456\\1\\lib']
    ['something']