【问题标题】:How can i get inspect.getsource to respond to changes in source code?我怎样才能让 inspect.getsource 响应源代码的变化?
【发布时间】:2013-05-07 00:30:54
【问题描述】:

我制作了两个文件:

#test_func.py
def test():
    print('hello')

#test_inspect.py
import inspect
import test_func

reload(inspect)
reload(test_func)
reload(inspect)
reload(test_func)

print inspect.getsource(test_func.test)

从 IPython 或其他交互式 shell 运行 import test_inspect 会打印正确的内容:

def test():
    print('hello')

但如果我将 test_func.py 编辑并保存为:

#test_func.py
def test():
    print('good bye')

我仍然得到:

def test():
    print('hello')

当我从 shell 运行 reload(test_inspect) 时。如何说服inspect 模块重新读取源文件?

(如果您必须知道我为什么要这样做,我将在 cmets 中详细说明,但现在,我只想知道是否有解决方法或者是否检查模块有一些基本的东西可以防止这种情况发生)

【问题讨论】:

    标签: python inspection


    【解决方案1】:

    这应该可以解决问题:

    import linecache
    linecache.clearcache()
    

    【讨论】:

    • 啊。好多了。谢谢。
    • 我认为这实际上是linecacheinspect 中的一个错误,应该在python 3.5 中修复。感谢您的解决方法。见bugs.python.org/issue1218234
    猜你喜欢
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多