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

发布于 2024-11-30 19:14:03 字数 297 浏览 0 评论 0原文

我想让我的 Python 代码在运行代码的过程中使用 code.interact() 之类的东西启动一个 Python 交互式控制台 (REPL)。但是 code.interact() 启动的控制台看不到当前命名空间中的变量。我该如何做类似的事情:

mystring="hello"

code.interact()

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

I would like to have my Python code start a Python interactive console (REPL) in the middle of running code using something like code.interact(). But the console that code.interact() starts doesn't see the variables in the current namespace. How do I do something like:

mystring="hello"

code.interact()

... and then in the interactive console that starts, I should be able to type mystring and get "hello". Is this possible? Do I need to set the "local" argument of code.interact() to something? What would this be set to? How should it be called?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

浪推晚风 2024-12-07 19:14:03

尝试:

code.interact(local=locals())

Try:

code.interact(local=locals())
一杆小烟枪 2024-12-07 19:14:03

对于调试,我通常使用它,

from pdb import set_trace; set_trace()

它可能会有所帮助

For debug I usually use this

from pdb import set_trace; set_trace()

it may help

↘紸啶 2024-12-07 19:14:03

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

Another way is to start the debugger, and then run interact:

import pdb
pdb.set_trace()

Then from the debugger:

(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*
>>>
难以启齿的温柔 2024-12-07 19:14:03

对于 Python 3.10.0:

code.InteractiveConsole(locals=locals()).interact()

请参阅 Python 文档 了解更多详细信息。

For Python 3.10.0:

code.InteractiveConsole(locals=locals()).interact()

See the Python documentation for more details.

ゞ记忆︶ㄣ 2024-12-07 19:14:03

如何从 code.interact 改变 globals() 和 locals()

不幸的是 code.interact 不允许您同时传递 globals()locals() 除非您将它们复制到像 code.interact(local={**globals(), **locals()}) 这样的单个字典中,但随后进行更改到globals()并且 locals() 将不会被持久化。

不过,您可以通过子类化控制台并覆盖其 runco​​de 方法来解决此问题:

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 将设置一个全局变量

,当您使用 Ctrl+D(或在 Windows 上按 Ctrl+Z 然后 Enter)离开交互式控制台时,您所做的更改应保留在 globals()locals()

警告locals() 文档 警告:

本词典的内容不得修改;更改可能不会影响解释器使用的局部变量和自由变量的值。

因此,不要依赖 locals() 的这些突变来完成任何关键任务。 PEP 558PEP 667 更详细,并且可能使 locals() 在未来版本的 Python 中表现得更加一致。

How to mutate both globals() and locals() from code.interact

Unfortunately code.interact doesn't let you pass both globals() and locals() from the current namespace unless you copy them into a single dict like code.interact(local={**globals(), **locals()}), but then changes you make to globals() and locals() won't be persisted.

However you can work around this by subclassing the console and overriding its runcode method:

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()

Having defined this somewhere, you can use it similarly to code.interact:

MyInteractiveConsole(globals(), locals()).interact()

Except that this will let you read and mutate both globals and locals:

  • x = 7 will set a local
  • global x; x = 7 will set a global

and when you leave the interactive console with Ctrl+D (or Ctrl+Z then Enter on Windows), the changes you made should persist in your globals() and locals().

Caveat: The docs for locals() warn:

The contents of this dictionary should not be modified; changes may not affect the values of local and free variables used by the interpreter.

so don't rely on these mutations to locals() for anything mission-critical. PEP 558 and PEP 667 go into more detail, and might make locals() behave more consistently in future versions of Python.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文