code.interact 和导入/定义可见性

问题描述 投票:0回答:3

我不太明白Python模块中的importsfunction定义在哪里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
并出现命令提示符,很多我应该看到的丢失了

  • getA() 和 getB() 不可见
  • 导入中的 scapy 也不可见

为什么会出现这种情况?我错了什么?

python function scope visibility python-import
3个回答
30
投票

正如我在上面的评论中所写,解决方案是:

code.interact(local=dict(globals(), **locals())) 

(拍摄于此处


8
投票

您混淆了

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}
    

0
投票
此函数对调用者的局部变量和全局变量执行

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))
    
© www.soinside.com 2019 - 2024. All rights reserved.