-1

Just now , I read a piece of code which was written in Python, I feel very doubtful to some python native API. the code as following:

filename = os.path.join(self.root_path, filename)
d = imp.new_module('config')
d.__file__ = filename
try:
    with open(filename) as config_file:
        exec(compile(config_file.read(), filename, 'exec'), d.__dict__)
except IOError as e:
    if silent and e.errno in (errno.ENOENT, errno.EISDIR):
        return False
    e.strerror = 'Unable to load configuration file (%s)' % e.strerror
    raise

I have two doubts about the code ,please help to answer them.

doubt 1.

compile(config_file.read(), filename, 'exec')

What's the functions about the compile function's second argument filename ?

doubt 2.

exec(compile(config_file.read(), filename, 'exec'), d.__dict__)

What's the functions about the exec function's second argument d.__dict__ ?

Thanks!

jrd1
  • 10,358
  • 4
  • 34
  • 51
  • possible duplicate of [What's the difference between eval, exec, and compile in Python?](http://stackoverflow.com/questions/2220699/whats-the-difference-between-eval-exec-and-compile-in-python) – Ankit Jaiswal May 07 '14 at 03:42

1 Answers1

0

The compile and eval functions are builtin to the Python interpreter. You should read their documentation online. These seem to be the relevant bits for your questions:

Regarding compile's filename parameter:

The filename argument should give the file from which the code was read; pass some recognizable value if it wasn’t read from a file ('<string>' is commonly used).

Regarding exec's globals parameter:

If only globals is provided, it must be a dictionary, which will be used for both the global and the local variables.

Blckknght
  • 100,903
  • 11
  • 120
  • 169