完成后如何以编程方式告诉 CPython 解释器进入交互模式?

发布于 2024-07-13 20:14:17 字数 122 浏览 6 评论 0原文

如果您使用 -i 选项调用 cpython 解释器,它将在完成指定要运行的任何命令或脚本后进入交互模式。 有没有办法在程序中让解释器执行此操作,即使没有给出 -i ? 明显的用例是在发生异常情况时通过交互式检查状态来进行调试。

If you invoke the cpython interpreter with the -i option, it will enter the interactive mode upon completing any commands or scripts it has been given to run. Is there a way, within a program to get the interpreter to do this even when it has not been given -i? The obvious use case is in debugging by interactively inspecting the state when an exceptional condition has occurred.

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

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

发布评论

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

评论(4

江湖正好 2024-07-20 20:14:17

您需要代码模块

#!/usr/bin/env python

import code    
code.interact("Enter Here")

You want the code module.

#!/usr/bin/env python

import code    
code.interact("Enter Here")
胡大本事 2024-07-20 20:14:17

设置 PYTHONINSPECT 环境变量。 这也可以在脚本本身中完成:

import os
os.environ["PYTHONINSPECT"] = "1"

为了调试意外异常,您还可以使用这个不错的配方 http: //code.activestate.com/recipes/65287/

Set the PYTHONINSPECT environment variable. This can also be done in the script itself:

import os
os.environ["PYTHONINSPECT"] = "1"

For debugging unexpected exceptions, you could also use this nice recipe http://code.activestate.com/recipes/65287/

花开半夏魅人心 2024-07-20 20:14:17

使用sys.excepthook在另一个答案中提到的食谱,听起来像你想要的。 否则,您可以在程序退出时运行 code.interact

import code
import sys
sys.exitfunc = code.interact

The recipe metioned in the other answer using sys.excepthook, sounds like what you want. Otherwise, you could run code.interact on program exit:

import code
import sys
sys.exitfunc = code.interact
风尘浪孓 2024-07-20 20:14:17

据我所知,执行此操作的最佳方法是:

from IPython import embed
embed()

它允许访问当前范围内的变量,并为您带来 IPython 的全部功能。

The best way to do this that I know of is:

from IPython import embed
embed()

which allows access to variables in the current scope and brings you the full power of IPython.

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