#!/usr/bin/env python

# The purpose of this script is to test the behaviour of the 'execfile' function
# with respect to the two dictionaries passed as (optional) arguments.
# If you supply a command-line argument to this script, it will pass a copy
# of the script's 'globals' dictionary instead of the original. This avoids
# any possibility of the execfile code changing this script's 'globals'.
# Cameron Hayne (macdev@hayne.net)  March 2010

import os
import sys
import tempfile
from pprint import pprint

def createSamplePythonFile():
    (fd, filepath) = tempfile.mkstemp()
    file = os.fdopen(fd, 'w')
    file.write("""
import optparse
a = 42
global BBB
BBB = 99
def foo():
    f = 2.72
    return 123
class bar():
    b = 3.14
    def __init__(self):
        self.value = 24
    def show(self):
        print "value:", self.value
z = foo()
""")
    file.close()
    return filepath

def main(argv):
    passCopyOfGlobals = (True if len(argv) > 0 else False)
    sampleFilepath = createSamplePythonFile()
    if passCopyOfGlobals:
        myGlobalDict = dict(globals())
    else:
        myGlobalDict = globals()
    myLocalDict = dict()

    print "globals before:"
    pprint(globals())
    print
    print "locals before:"
    pprint(locals())
    print

    execfile(sampleFilepath, myGlobalDict, myLocalDict)

    print "globals after:"
    pprint(globals())
    if not passCopyOfGlobals:
        print
        print "Note that 'BBB' is now in this script's globals"
        print "The value of BBB is:", BBB
    print
    print "locals after:"
    pprint(locals())
    print

    print "myGlobalDict:"
    pprint(myGlobalDict)
    print
    print "myLocalDict:"
    pprint(myLocalDict)
    print

if __name__ == "__main__":
    main(sys.argv[1:])
