2009-06-22 34 views
10

是否有可能打破Python腳本中調用該函數的execfile執行不使用if/else語句?我試過exit(),但它不允許main.py完成。停止執行調用的execfile

# main.py 
print "Main starting" 
execfile("script.py") 
print "This should print" 

# script.py 
print "Script starting" 
a = False 

if a == False: 
    # Sanity checks. Script should break here 
    # <insert magic command>  

# I'd prefer not to put an "else" here and have to indent the rest of the code 
print "this should not print" 
# lots of lines below 
+0

你爲什麼要使用的execfile(),而不是導入? – ephemient 2009-06-22 18:04:48

+0

我認爲當我在一個單獨的窗口中編輯腳本並執行它們時,execfile允許更大的靈活性 – JcMaco 2009-06-22 18:09:40

回答

15

main可以包裝execfiletry/except塊:sys.exit引發一個例外SystemExit這main可以在except子句中趕上以正常地繼續其執行(如果需要)即,在main.py

try: 
    execfile('whatever.py') 
except SystemExit: 
    print "sys.exit was called but I'm proceeding anyway (so there!-)." 
print "so I'll print this, etc, etc" 

whatever.py可以使用sys.exit(0)或任何終止自己的只執行。因爲它的源之間的約定是execfile d和源做execfile呼叫其他異常將工作以及長 - 但SystemExit特別適合作爲它的意義是相當清楚的!

3
# script.py 
def main(): 
    print "Script starting" 
    a = False 

    if a == False: 
     # Sanity checks. Script should break here 
     # <insert magic command>  
     return; 
     # I'd prefer not to put an "else" here and have to indent the rest of the code 
    print "this should not print" 
    # lots of lines bellow 

if __name__ == "__main__": 
    main(); 

我發現的Python的這個方面(該__name__ == "__main__」等)刺激性

+0

您發佈的代碼中存在兩個小錯誤:「print」這個不應該打印「」的縮進太多並且返回不需要分號。謝謝,我想我會用這個。 – JcMaco 2009-06-22 18:29:09

1

有什麼不對普通的舊的異常處理?

scriptexit.py

class ScriptExit(Exception): pass 

main.py

from scriptexit import ScriptExit 
print "Main Starting" 
try: 
    execfile("script.py") 
except ScriptExit: 
    pass 
print "This should print" 

script.py

from scriptexit import ScriptExit 
print "Script starting" 
a = False 

if a == False: 
    # Sanity checks. Script should break here 
    raise ScriptExit("A Good Reason") 

# I'd prefer not to put an "else" here and have to indent the rest of the code 
print "this should not print" 
# lots of lines below