2015-02-11 64 views
5

我有一些像這樣的代碼:我可以從調用代碼中退出ipython嗎?

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

如果我再與

python my_example_program.py 
通過循環的第一次迭代

我得到放入IPython的外殼,可以檢查item和運行這個程序我願意的環境。

退出ipython後,循環繼續,然後我可以檢查下一個item和環境,就像你期望的那樣。

有沒有一種方法可以讓我在ipython中退出這段代碼(這樣我就可以返回到shell提示符下)。以任何方式打開另一個殼並殺死這個過程?

回答

7

在IPython中有一個%kill_embedded命令。
它不會讓您直接回到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(2016年6月3日):似乎%kill_embedded功能在IPython的4.0種破裂;你可以使用%exit_raise這會引發異常並返回到shell。

+0

跳過其他嵌入實例正是我想要的,謝謝。 – 2015-02-11 11:40:47

+0

@ MikeH-R不客氣! – 2015-02-11 11:49:44

+0

你最後一次輸入是做什麼的,只是一個普通的CTRL + D?我試圖在IPython 4.0中重現這個例子,但我總是必須經歷循環中的所有「嵌入」。看起來像'%kill_embedded'實際上沒有效果。 – bluenote10 2016-02-29 14:53:32

相關問題