快乐学python

Can't get source code for a meth

2019-06-24  本文已影响0人  DS事务所

研究Python自省时发现的一个问题

python inspect 模块无法读取exec所创建的函数的源代码

import inspect

code = 'def a(): return 1;\n'
exec(code)
print(a())
print(inspect.getsourcelines(a))

执行后报错

Traceback (most recent call last):
  File "./PycharmProjects/spider-demo/1.py", line 9, in <module>
    print(inspect.getsourcelines(a))
 File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/inspect.py", line 955, in getsourcelines
    lines, lnum = findsource(object)
  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/inspect.py", line 786, in findsource
    raise OSError('could not get source code')
OSError: could not get source code

分析源码

分析inspect.py发现inspect是通过读取系统所加载的py文件来查找函数源代码的

def findsource(object):
    """Return the entire source file and starting line number for an object.

    The argument may be a module, class, method, function, traceback, frame,
    or code object.  The source code is returned as a list of all the lines
    in the file and the line number indexes a line in that list.  An **IOError
    is raised if the source code cannot be retrieved.**"""
    try:
        file = open(getsourcefile(object))  
    except (TypeError, IOError):
        raise IOError, 'could not get source code'
    lines = file.readlines()               #reads the file
    file.close()

原因

原因就在于执行顺序
*.py>>>编译器>>>机器码>>>执行脚本>>>exec产生无源码、但有机器码的“无码”函数
然而inspect.py只会去分析一开始传入的的*.py内是否有该函数,所以只进行exec而不回写py文件的话,就无法读取到源码

上一篇 下一篇

猜你喜欢

热点阅读