在尝试使用 Python 的 exec
语句时,出现以下错误:
TypeError: exec: arg 1 must be a string, file, or code object
我不想传入字符串或文件,但什么是代码对象,如何创建?
最佳答案
创建代码对象的一种方法是使用 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
另外,函数具有函数属性__code__
(在旧版本中也称为func_code
),您可以从中获取函数的代码对象:
>>> def f(s): print s
...
>>> f.__code__
<code object f at 0x19aa1b0, file "<stdin>", line 1>
关于python - 此 TypeError 消息中提到的 "code object"是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5768684/