1. exec() 方法是 python3 中内置的方法, 通过帮助命令
>>> help(exec)
Help on built-in function exec in module builtins:
exec(source, globals=None, locals=None, /)
Execute the given source in the context of globals and locals.
The source may be a string representing one or more Python statements
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
可以看到 exec() 方法的作用是在给定的全局作用域和本地环境中执行原始代码
source 参数可以是一个字符串表达式, 比如:
(x*5+1)/15
还可以是多个 Python 变量, 方法或对象的定义代码, 比如:
if __name__ == '__main__':
command_string = """
def print_name_fun():
print('你的名字')
one_val = 'test value'
"""
exec(command_string)
print_name_fun()
print(one_val)
# 执行结果为:
你的名字
test value
通过执行结果我们可以看到 exec 的执行影响了当前环境, 这一点要注意
source 还可以是代码对象, 这个在文末和 execfile() 的替代方案一起讲解
globals 和 locals 参数看文档可以理解为一个字典对象和任意一个映射对象, 这两个参数用的不多, 不详述
2. eval() 方法是 python3 中内置的方法, 通过帮助命令
>>> help(eval)
Help on built-in function eval in module builtins:
eval(source, globals=None, locals=None, /)
Evaluate the given source in the context of globals and locals.
The source may be a string representing a Python expression
or a code object as returned by compile().
The globals must be a dictionary and locals can be any mapping,
defaulting to the current globals and locals.
If only globals is given, locals defaults to it.
可以看到大部分和 exec() 方法类似, 只有一个 source 参数只允许单个表达式字符串或一个代码对象, 因此不再赘述, 只展示一个表达式的示例代码:
if __name__ == '__main__':
x = 3
command_string = "(x*5+1)/2"
y = eval(command_string)
print(y)
# 执行结果
8.0
3. execfile() 的替代方案
在 python2 中有内置的 execfile 方法可以直接执行文件, 但 python3 中并没有提供对应的方法, 而是通过 exec() 方法执行, 用到的功能即 source 参数可以接收代码对象并执行这一个特性
def exec_file(file_name):
with open(file_name, 'r') as file:
exec(compile(file.read(), file_name, 'exec'))
if __name__ == '__main__':
exec_file('待执行的 python 文件路径和名称')
exec_file() 方法是自定义的方法, 可以根据需要修改, compile 方法还有很多其他参数, 可以通过帮助命令查阅, 在此不再赘述
注: 本文仅作为方法查阅记录, 更详细的用法见官方文档