我不太明白Python模块中的imports和function定义在哪里visibile。 这是我的案例的简化:
from scapy.all import *
def getA():
return 0
def getB():
return getA() + 1
def getC():
code.interact(local=locals())
return 3
def main():
print getA()
print getB()
print getC()
exit()
if __name__ == '__main__':
main()
现在,一切都很顺利,直到我达到功能
getC
并出现命令提示符,很多我应该看到的丢失了。
为什么会出现这种情况?我错了什么?
locals()
和globals()
。在函数作用域中,locals()
仅列出函数本身定义的名称。
请使用 globals()
来代替。
>>> bar = 'baz'
>>> def foo():
... spam ='eggs'
... print locals()
...
>>> foo()
{'spam': 'eggs'}
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'foo': <function foo at 0x108a027d0>, '__doc__': None, '__package__': None}
code.interact
操作:
def repl():
"""This starts a REPL with the callers globals and locals available
Raises:
RuntimeError: Is raised when the callers frame is not available
"""
import code
import inspect
frame = inspect.currentframe()
if not frame:
raise RuntimeError('No caller frame')
code.interact(local=dict(frame.f_back.f_globals, **frame.f_back.f_locals))