2010-04-06 138 views
2

我有,我想一定條件下提前退出的腳本:退出命令行Python中

if not "id" in dir(): 
    print "id not set, cannot continue" 
    # exit here! 
# otherwise continue with the rest of the script... 
print "alright..." 
[ more code ] 

我運行使用execfile("foo.py")從Python的交互提示這個劇本,我想腳本退出會回到交互式翻譯。我該怎麼做呢?如果我使用sys.exit(),則Python解釋器完全退出。

回答

3

把你的代碼塊的方法,並從該方法返回,就像這樣:

def do_the_thing(): 
    if not "id" in dir(): 
     print "id not set, cannot continue" 
     return 
     # exit here! 
    # otherwise continue with the rest of the script... 
    print "alright..." 
    # [ more code ] 

# Call the method 
do_the_thing() 

而且,除非有很好的理由使用的execfile(),這個方法也許應該把一個模塊中,它可以從另一個Python腳本導入叫:

import mymodule 
mymodule.do_the_thing() 
+0

更簡單的方法是反轉if條件並僅在滿足此條件時才執行腳本的其餘部分。我只是覺得可能有更簡單的方法來停止腳本的執行。但顯然沒有:) – fuenfundachtzig 2010-04-07 12:15:55

+0

其實,它*是一個好主意,以確保您的前提條件在方法開始時得到滿足。因此,如果所有條件都正確,首先檢查並繼續,這是一個好方法。 – Frederik 2010-04-07 14:38:57

7

在交互式解釋;趕上SystemExit通過sys.exit提高,忽略它:

try: 
    execfile("mymodule.py") 
except SystemExit: 
    pass 
0

而不是使用的execfile的,你應該讓腳本可導入( ==」 主要保護,分隔成函數等),然後調用解釋器的功能。

2

我對ipython的交互式工作有點癡迷,但請查看shell embedding上的教程,以獲得比this one(這是您的最直接路由)更可靠的解決方案。

+0

我知道我對這個派對來說太遲了兩年,但是有沒有更新的鏈接? – Glycerine 2012-10-15 09:44:56

+1

Shell嵌入由ipython項目維持。最新的一個在這裏:http://ipython.org/ipython-doc/rel-0.13.1/interactive/reference.html#embedding-ipython。 – colgur 2012-11-16 23:01:01

+0

男人!!!!我一直在尋找這個sooooooo!非常感謝!讓懶惰的人更容易:從IPython import embed導入ipython',然後在想要停止執行的地方使用embed()並進行交互式工作 'embed()#這個調用在程序中的任何地方都會啓動IPython ' – 2014-06-17 23:35:37