exec
statementExecutes a string of a python code.
Suppose you which to write a program which reads a config-file ~/.myprogrc
:
# Configuration file for my progamm
verbose = True
errorlog = "/var/log/myprogram/error.log"
colors = { "fore" : "#ae2020",
"back" : "#f7d8c2" }
Instead of scanning, parsing and analyzing the config-file yourself, write the config-file in python syntax and let python do all the work for you:
#!/usr/bin/python
import os.path
exec(file(os.path.expanduser('~/.myprogrc')))
if verbose:
print 'Welcome to my program!'
print 'Background-color is:', colors['back']
Running the program in a shell:
$ ./myprog.py
Welcome to my program!
Background-color is: #f7d8c2