关于python:execfile和exec的区别

有时候想把一个文件内容赋给一个变量,能够用execfile和exec
execfile3.0以上版本不反对,可用exec代替

例子:

import os

test_path = os.path.dirname(__file__)
config_path = os.path.join(os.path.split(test_path)[0], 'config')


def parse_conf(conf_file, variable_scope):
    exec(open(os.path.join(config_path, conf_file)).read(), variable_scope)
    variable_scope.pop('__builtins__', None)


log_config = {
    'module': 'test',
}
parse_conf("log.conf", log_config)

print(log_config)

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理