我是python的新手,现在已经玩了一段时间.我一直在玩与周围的内置compile()功能,随着exec和内置simple.py.我注意到一些我似乎无法找到答案的东西.请考虑以下脚本:
def foo():
print "Inside foo()..."
def main():
print "This is a simple script that should count to 3."
for i in range(1, 4):
print "This is iteration number", i
foo()
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
这通过以下方式运行时工作正常:
with open('simple.py', 'r') as f:
code = f.read()
exec code
Run Code Online (Sandbox Code Playgroud)
但是,当编译成代码对象时,通过exec序列化compile(),保存到文件然后从文件中读取,反序列化marshal.dump(),并通过marshal.load()它运行错误,并foo声明全局名称dir()未定义.
我查看了给出的输出foo,当我dis.dis()编写代码时,我可以看到它有一个定义marshal.load().我也注意到,当我使用LOAD_NAME反序列化的代码对象(read via CALL_FUNCTION)时,我唯一看到的是main()和importfor import(而不是做类似的事情compile(),然后做compile(),这给你整个反汇编按预期).
我是否更正,有某种查询表可以exec咨询这些地址?(为了记录,我检查了http://svn.python.org/projects/python/trunk/Lib/py_compile.py以及我在字节码中看到的唯一差异,这是通过simple.py内置生成的,而内置的exec是compile(),以及32位时间戳).如果存在这样的表,是否有一个好的方法来咨询它?
谢谢!
小智 0
该脚本成功执行了您的 simple.py 代码 3 次。这能澄清什么吗?或者我误解了你的问题?
# from original example
with open('simple.py', 'r') as f:
code = f.read()
exec(code)
# compile and run again
a = compile(code, "simple_compiled_this_file_not_created", "exec")
exec(a)
# marshal and unmarshal
import marshal
f = open("./marshalfoo.bin", "wb")
marshal.dump(a,f)
f.close()
b = marshal.load(open("./marshalfoo.bin", "rb"))
exec(b)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
810 次 |
| 最近记录: |