Python script to parse text file and execute inline python code
Question: I am new to python and trying to create a script that could do the following:

    
    
    infile = open("input.txt", "r")
    outfile = open("output.txt", "w")
    print ("Starting file transformation...")
    
    for line in infile:
    
        # If the line is not encapsulated in between two markers: 
        # //START_PY & //END_PY then print the line verbatim. If 
        # it is between the markers then execute the inline python code
    
    infile.close()
    outfile.close()
    

So an input.txt like the following:

* * *
    
    
    Hello World
    
    //START_PY
    
        for count in range(1,2):
            print ("More Hello World");
    
    //END_PY
    
    Even More Hello World
    

* * *

This would output the following:

    
    
    Hello World
    
    More Hello World
    
    More Hello World
    
    Even More Hello World
    

I could create an intermediate python script and execute that from within the
parent script. Is there a way to do this in one pass i.e. directly create the
output file?


Answer: It can be done withe the help of abstract syntax trees "ast" module:

    
    
    >>> import ast
    >>> # let's assume you already parsed your code sections
    >>> code_text = "for count in range(2):\n\tprint('[%d] More hello worlds' % count)\n"
    >>> po = ast.parse(code_text)
    >>> co = compile(po, "<unknown>", "exec")
    >>> namespace = {}
    >>> exec(co, namespace)
    [0] More hello worlds
    [1] More hello worlds
    >>>
    

