无法获取Python函数源代码:咨询是否需重装及环境排查
Python inspect.getsource 无法获取函数源代码问题解答
问题说明
无法通过inspect.getsource()获取函数源代码,报错OSError: could not get source code,且使用marvin库的@ai_fn装饰器时也出现相同错误。涉及环境为conda-forge打包的Python 3.7.6(Linux)及Python 3.10。
交互式定义函数报错示例
# python Python 3.7.6 | packaged by conda-forge | (default, Mar 23 2020, 22:25:07) [GCC 7.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> def foo(arg1,arg2): ... #do something with args ... a = arg1 + arg2 ... return a ... >>> import inspect >>> lines = inspect.getsource(foo) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/root/miniforge3/lib/python3.7/inspect.py", line 973, in getsource lines, lnum = getsourcelines(object) File "/root/miniforge3/lib/python3.7/inspect.py", line 955, in getsourcelines lines, lnum = findsource(object) File "/root/miniforge3/lib/python3.7/inspect.py", line 786, in findsource raise OSError('could not get source code') OSError: could not get source code
使用marvin装饰器报错示例
>>> from marvin import ai_fn >>> @ai_fn ... @ai_fn ... def rhyme(word: str) -> str: ... "Returns a word that rhymes with the input word." ... >>> rhyme("blue") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.10/site-packages/marvin/bots/ai_functions.py", line 128, in ai_fn_wrapper return_value = fn(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/marvin/bots/ai_functions.py", line 141, in ai_fn_wrapper function_def = inspect.cleandoc(inspect.getsource(fn)) File "/usr/local/lib/python3.10/inspect.py", line 1139, in getsource lines, lnum = getsourcelines(object) File "/usr/local/lib/python3.10/inspect.py", line 1121, in getsourcelines lines, lnum = findsource(object) File "/usr/local/lib/python3.10/inspect.py", line 958, in findsource raise OSError('could not get source code') OSError: could not get source code
原因分析
inspect.getsource()依赖磁盘上的物理源文件读取函数代码,而Python交互式命令行(stdin)中定义的函数仅存在于内存中,没有对应的源文件,因此无法被inspect模块定位。- marvin库的
@ai_fn装饰器内部调用了inspect.getsource(),当装饰的函数是在交互式环境中定义时,同样会触发上述错误。
结论与解决方案
- 无需重装Python,当前Python环境完全正常,该报错是
inspect模块的预期行为,而非环境损坏。 - 解决方案:
- 将需要获取源代码的函数写入
.py文件,而非在交互式命令行中定义。 - 运行该
.py文件或在文件内调用inspect.getsource(),即可正常获取函数源代码。 - 使用marvin的
@ai_fn装饰器时,需将装饰的函数放在.py文件中执行,避免使用交互式环境。
- 将需要获取源代码的函数写入
内容的提问来源于stack exchange,提问作者shantanuo
相关产品推荐
相关产品推荐

