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

Mik*_*H-R 8 python ipython

我有一些像这样的代码:

form IPython import embed
for item in my_item_list:
    embed()
Run Code Online (Sandbox Code Playgroud)

如果我然后运行此程序

python my_example_program.py
Run Code Online (Sandbox Code Playgroud)

在循环的第一次迭代中,我被放入一个ipython shell中,可以item像我想的那样检查和环境.

在退出ipython时,循环恢复,然后我可以item按照您的预期检查下一个和环境.

有没有办法让我从ipython中退出这段代码(这样我就会返回shell提示符).以任何方式打开另一个shell并杀死进程?

Igo*_*ist 16

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

from IPython import embed

for item in range(5):
    print 'embedding', item
    embed()
Run Code Online (Sandbox Code Playgroud)

这是输出:

 $ 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
 $ 
Run Code Online (Sandbox Code Playgroud)

UPD(06.03.2016):看起来这个%kill_embedded功能在IPython 4.0中有点破碎; 您可以使用%exit_raise哪个会引发异常并返回shell.

  • @bluenote10 那可能是因为根据 [issue] (https://github.com/ipython/ipython/pull/9150) 在 4.1 中添加了 `%exit_raise`。`%kill_embedded` 在 IPython 5.1.0 中工作正常 (2认同)