execfileで呼び出されたスクリプトの実行を停止します
-
06-07-2019 - |
質問
if / elseステートメントを使用せずに、execfile関数で呼び出されたPythonスクリプトの実行を中断することは可能ですか? exit()
を試しましたが、 main.py
を終了できません。
# 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
解決
main
は execfile
を try
/ 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
意味がはっきりしているので特に適しています!
他のヒント
# 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 __
== &quot; __ main __
&quot;など)はいらいらします。
単純な古い例外処理の何が問題になっていますか
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
所属していません StackOverflow