如何将代码对象保存在文件中?

ato*_*era 4 python

如何在文件中保存代码对象(_ _ 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
Run Code Online (Sandbox Code Playgroud)

mou*_*uad 10

不确定你要做什么,但你可以使用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  
Run Code Online (Sandbox Code Playgroud)