我想在Python代码中使用类似于code.interact()的方法启动Python交互式控制台(REPL),但是code.interact()所启动的控制台看不到当前命名空间中的变量. 我要如何实现下面这样的功能:
mystring="hello"
code.interact()
...然后在启动的交互式控制台中,输入mystring应该返回"hello". 这可行吗?我需要将code.interact()函数的"local"参数设置为什么?应该如何调用它?
我想在Python代码中使用类似于code.interact()的方法启动Python交互式控制台(REPL),但是code.interact()所启动的控制台看不到当前命名空间中的变量. 我要如何实现下面这样的功能:
mystring="hello"
code.interact()
...然后在启动的交互式控制台中,输入mystring应该返回"hello". 这可行吗?我需要将code.interact()函数的"local"参数设置为什么?应该如何调用它?
尝试:
code.interact(local=locals())
code.interact(local=dict(globals(), **locals()))
- m01进行调试时,我通常使用以下方法:
from pdb import set_trace; set_trace()
可能会有所帮助
另一种方法是启动调试器,然后运行interact
:
import pdb
pdb.set_trace()
(Pdb) help interact
interact
Start an interactive interpreter whose global namespace
contains all the (global and local) names found in the current scope.
(Pdb) interact
*interactive*
>>>
import code
try:
import readline
except ImportError:
pass
class MyInteractiveConsole(code.InteractiveConsole):
"""Extends InteractiveConsole to also pass globals to exec."""
def __init__(self, globals, *args, **kwargs):
code.InteractiveConsole.__init__(self, *args, **kwargs)
self.globals = globals
def runcode(self, code):
try:
exec(code, self.globals, self.locals)
except SystemExit:
raise
except:
self.showtraceback()
code.interact
一样使用它。MyInteractiveConsole(globals(), locals()).interact()
x = 7
将设置一个局部变量global x; x = 7
将设置一个全局变量globals()
和 locals()
中。因此,在关键任务中不要依赖于对不应该修改这个字典的内容;对解释器使用的局部变量和自由变量的值可能不会受到影响。
locals()
的这些修改。PEP 558 和 PEP 667 提供了更详细的信息,并且可能会使 locals()
在未来的 Python 版本中行为更加一致。