如何在当前命名空间中获取Python交互式控制台?

时间:2011-08-23 18:02:28

标签: python variables namespaces console read-eval-print-loop

我希望我的Python代码在运行代码的过程中使用code.interact()之类的东西启动Python交互式控制台(REPL)。但是code.interact()启动的控制台没有看到当前命名空间中的变量。我该怎么做:

了mystring = “你好”

code.interact()

...然后在启动的交互式控制台中,我应该能够输入mystring并获得“hello”。这可能吗?我需要将code.interact()的“local”参数设置为什么?这会是什么?该怎么称呼?

3 个答案:

答案 0 :(得分:18)

尝试:

code.interact(local=locals())

(在此处找到:http://aymanh.com/python-debugging-techniques

答案 1 :(得分:4)

对于调试我通常使用这个

from pdb import set_trace; set_trace()

它可能会有所帮助

答案 2 :(得分:0)

另一种方法是启动调试器,然后运行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*
>>>