如何在当前命名空间中获取Python交互式控制台?
我想让我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试:
Try:
对于调试,我通常使用它,
它可能会有所帮助
For debug I usually use this
it may help
另一种方法是启动调试器,然后运行
interact
:然后从调试器中运行:
Another way is to start the debugger, and then run
interact
:Then from the debugger:
对于 Python 3.10.0:
请参阅 Python 文档 了解更多详细信息。
For Python 3.10.0:
See the Python documentation for more details.
如何从 code.interact 改变 globals() 和 locals()
不幸的是
code.interact
不允许您同时传递globals()
和locals()
除非您将它们复制到像code.interact(local={**globals(), **locals()})
这样的单个字典中,但随后进行更改到globals()
并且locals()
将不会被持久化。不过,您可以通过子类化控制台并覆盖其
runcode
方法来解决此问题:在某处定义了此方法后,您可以像
code.interact
一样使用它:除了这会让您读取并改变全局变量和局部变量:
x = 7
将设置本地global x; x = 7
将设置一个全局变量,当您使用 Ctrl+D(或在 Windows 上按 Ctrl+Z 然后 Enter)离开交互式控制台时,您所做的更改应保留在
globals()
和locals()
。警告:locals() 文档 警告:
因此,不要依赖
locals()
的这些突变来完成任何关键任务。 PEP 558 和 PEP 667 更详细,并且可能使locals()
在未来版本的 Python 中表现得更加一致。How to mutate both globals() and locals() from code.interact
Unfortunately
code.interact
doesn't let you pass bothglobals()
andlocals()
from the current namespace unless you copy them into a single dict likecode.interact(local={**globals(), **locals()})
, but then changes you make toglobals()
andlocals()
won't be persisted.However you can work around this by subclassing the console and overriding its
runcode
method:Having defined this somewhere, you can use it similarly to
code.interact
:Except that this will let you read and mutate both globals and locals:
x = 7
will set a localglobal x; x = 7
will set a globaland 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()
andlocals()
.Caveat: The docs for locals() warn:
so don't rely on these mutations to
locals()
for anything mission-critical. PEP 558 and PEP 667 go into more detail, and might makelocals()
behave more consistently in future versions of Python.