python - 此 TypeError 消息中提到的 "code object"是什么?

标签 python cpython

在尝试使用 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/

相关文章:

python - 迁移后的 Django South 迁移从初始开始

python - 如何在 Python 中找到 for - 控制流构造的实现

c++ - 如何使用 API 将 map<string,string> 传递给 py?

python - CPython 的垃圾收集是否进行压缩?

python - PyInstaller "You may load I/O plugins with the ` skimage.io.use_plugin`"

python - 如何通过主题建模制作主题的百分比条形图?

python - 在 CPython 中,Py_Main 的范围在哪里?

python - 设置 __all__ 然后使用前导下划线是否有意义?

python - 如何在Python shell脚本中使用pipenv?

Python:打开一个文件,搜索然后追加,如果不存在