python - 无法从评估的 lambda 函数中获取源代码
问题描述
我遇到了这个有趣的事实,我想知道如何克服它。通过使用inspect
很容易获得 lambda 的源代码。但是,一旦您从eval
语句中返回相同的 lambda,get source 函数就会失败。
import inspect
f = lambda a: a*2
f2 = eval("lambda a: a*2")
inspect.getsource(f), inspect.getsource(f2)
/usr/lib/python3.7/inspect.py in getsource(object)
971 or code object. The source code is returned as a single string. An
972 OSError is raised if the source code cannot be retrieved."""
--> 973 lines, lnum = getsourcelines(object)
974 return ''.join(lines)
975
/usr/lib/python3.7/inspect.py in getsourcelines(object)
953 raised if the source code cannot be retrieved."""
954 object = unwrap(object)
--> 955 lines, lnum = findsource(object)
956
957 if istraceback(object):
/usr/lib/python3.7/inspect.py in findsource(object)
784 lines = linecache.getlines(file)
785 if not lines:
--> 786 raise OSError('could not get source code')
787
788 if ismodule(object):
OSError: could not get source code
有没有办法解决这个问题并获得评估代码的来源?
解决方案
函数不记得它们的源代码——它们只知道它们来自的文件名和行号。如果函数定义不在仍然可用的物理文件中,那么 inspect.getsource() 完全不可能工作。相反,您需要一个反编译器。
谢谢,杰森哈珀
推荐阅读
- json - 如何在表格视图中快速显示可编码 JSON 数据?
- amazon-web-services - 我的 CodePipeline 没有在 s3 事件触发器上触发
- python - 为什么使用以下代码和 __name__ == "__main__?
- javascript - 使用节点客户端库在 Elasticsearch 中插入数字(浮点数)
- git - 如何使用 Jenkins Freestyle Project 访问远程 Git 存储库
- r - 使用 rvest 进行网络抓取:用 NA 替换 html_nodes 的缺失值
- string - SQLite 连接
- cmake - 为现代 CMake 中的所有目标导出编译器标志
- sql - 在 oracle 中的更新表上未调用触发器
- graphics - 使用栅栏清理命令缓冲区并同时同步交换链图像