在尝试使用Python的"exec"语句时,我收到以下错误:
TypeError: exec: arg 1 must be a string, file, or code object
Run Code Online (Sandbox Code Playgroud)
我不想传入字符串或文件,但什么是代码对象,我该如何创建?
Lie*_*yan 31
创建代码对象的一种方法是使用compile内置函数:
>>> compile('sum([1, 2, 3])', '', 'single')
<code object <module> at 0x19ad730, file "", line 1>
>>> exec compile('sum([1, 2, 3])', '', 'single')
6
>>> compile('print "Hello world"', '', 'exec')
<code object <module> at 0x19add30, file "", line 1>
>>> exec compile('print "Hello world"', '', 'exec')
Hello world
Run Code Online (Sandbox Code Playgroud)
此外,函数具有函数属性__code__(也称为func_code旧版本),您可以从中获取函数的代码对象:
>>> def f(s): print s
...
>>> f.__code__
<code object f at 0x19aa1b0, file "<stdin>", line 1>
Run Code Online (Sandbox Code Playgroud)
Dan*_*ner 22
Dan Crosta有一篇很好的博客文章解释了这个主题,包括如何手动创建代码对象,以及如何再次反汇编它们: