我的模块path = "..\blah\blah\myfolder\mymodule.py"
包含:
print('hi')
代码执行:
exec(compile(open(path, 'rb').read(), path, 'exec'))
和
exec(open(path, 'rb').read())
给出同样的结果.
为什么需要compile()
个?
我的模块path = "..\blah\blah\myfolder\mymodule.py"
包含:
print('hi')
代码执行:
exec(compile(open(path, 'rb').read(), path, 'exec'))
和
exec(open(path, 'rb').read())
给出同样的结果.
为什么需要compile()
个?
它们在您的情况下是相同的,即,如果将字符串作为输入,则exec
和eval
使用compile
.但是compile
可以用来预编译将用exec
(或eval
)重复执行的代码,使它运行得更快,因为您不需要每次都编译代码.请考虑:
compiled_code = compile(open(path, 'rb').read(), path, 'exec')
for _ in range(10**9):
exec(compiled_code)