python - 我可以让 ipython 从调用代码中退出吗?

标签 python ipython

我有这样的代码:

form IPython import embed
for item in my_item_list:
    embed()

如果我然后运行这个程序

python my_example_program.py

在循环的第一次迭代中,我进入了一个 ipython shell,并且可以检查 item 和我想要的环境。

退出 ipython 后循环恢复,然后我可以检查下一个 item 和您期望的环境。

有没有办法让我从 ipython 中退出此代码(以便我返回到 shell 提示符)。以任何方式打开另一个外壳并终止进程?

最佳答案

有一个 %kill_embedded IPython 中的命令。
它不会让您直接返回 shell 提示符,但会跳过其他嵌入实例。

from IPython import embed

for item in range(5):
    print 'embedding', item
    embed()

这是输出:

 $ python my_example_program.py
embedding 0
Python 2.7.9 (default, Dec 13 2014, 22:30:33)
Type "copyright", "credits" or "license" for more information.

IPython 1.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: print item
0

In [2]: ^D

embedding 1
Python 2.7.9 (default, Dec 13 2014, 22:30:33)
Type "copyright", "credits" or "license" for more information.

IPython 1.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [2]: %kill_embedded
Are you sure you want to kill this embedded instance (y/n)? [y/N]  y
This embedded IPython will not reactivate anymore once you exit.

In [3]: print item
1

In [4]:

embedding 2
embedding 3
embedding 4
 $ 

UPD (06.03.2016): %kill_embedded 功能似乎在 IPython 4.0 中被破坏了;您可以使用 %exit_raise 这将引发异常并返回到 shell。

关于python - 我可以让 ipython 从调用代码中退出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28453165/

相关文章:

python - 如何在 mac 上为 2.7 设置 python 路径?

ipython - 如何使用 .ipynb 文件在 IPython 笔记本中保存 .py 文件

python - 使用剪贴板将 excel 数据复制到 IPython 中的 python 列表中?

python - DataFrame 列中的字符串长度

python - 将 IPython 变量作为参数传递给 bash 命令

python - 在本地提供 Jupyter 孵化器仪表板的最简单方法

ssl - ipython 笔记本服务器 SSL 错误

python - 如何模拟在不同模块的导入方法中导入的函数

python - 在脚本中操作和打印到 PDF 文件

python - 使用 OpenPyXL 在工作表的页眉/页脚插入图像