如何在文件中保存代码对象(_ _ code _ _)?
>>> c
<code object foo at 0x022E7660, file "<console>", line 1>
>>> pickle.dump(c, f)
Traceback (most recent call last):
File "<console>", line 1, in <module>
_pickle.PicklingError: Can't pickle <class 'code'>: attribute lookup builtins.code failed
>>> f.write(c)
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'code' does not support the buffer interface
答案 0 :(得分:9)
不确定您要执行的操作但您可以使用marshal模块:
>>> import marshal
>>> def f():
... print 'f'
>>> marshal.dump(f.__code__, open('test.dump'))
>>> code = marshal.load(open('test.dump'))
>>> f.__code__ == code
True
>>> import dis
>>> dis.dis(code)
2 0 LOAD_CONST 1 ('f')
3 PRINT_ITEM
4 PRINT_NEWLINE
5 LOAD_CONST 0 (None)
8 RETURN_VALUE
答案 1 :(得分:-3)
我用Google搜索并发现了一些有用的内容: http://python.about.com/od/pythonstandardlibrary/a/pickle_intro.htm
问候