Python 执行字符串表达式函数(eval exec execfile)

eval:计算字符串中的表达式
exec:执行字符串中的语句
execfile:用来执行一个文件

在python 2中exec是语句,在python3中exec变为函数,后面要跟括号。在python3中取消了execfile语句,可以通过

with open('test1.py','r') as f:

    exec(f.read())

语句实现execfile语句。

eval可以直接将字符串转成list tuple 字典。但是如果字符串内的句子为执行语句,如“__import__('os').system('dir >dir.txt')”,会存在运行系统命令的危险。所以用eval时候需要谨慎。

原文地址:https://www.cnblogs.com/heshangaichirou/p/5432411.html