pythonconfigurationexecfile

Execution of execfile() in a method with Python


I have a config.py script that has PREAMBLE information. I can use execfile() function to read the contents of the configuration file.

execfile("config.py")
print PREAMBLE
>>> "ABC"

However, when execfile() is called in a method, I have an error.

def a():
    execfile("config.py")
    print PREAMBLE

a()
>>> NameError: "global name 'PREAMBLE' is not defined"

What's wrong and how to solve this issue?


Solution

  • You need to pass the global dictionary to execfile to achieve the same result:

    def a():
        execfile("config.py",globals())
        print PREAMBLE
    
    a()
    >>> "some string"
    

    If you don't want to pollute your global namespace, you can pass a local dictionary and use that:

    def a():
        config = dict()
        execfile('/tmp/file',config)
        print config['PREAMBLE']
    
    a()
    >>> "some string"
    

    For reference, in both cases above, /tmp/file contained PREAMBLE = "some string".