17

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
4

3 に答える 3

22

mainexecfiletry/exceptブロックにラップできます: sys.exitSystemExit 例外を発生させます。この例外は、必要に応じて、通常どおり実行を継続するために句で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)を終了できます。d されるソースと呼び出しを行うソースとの間で合意されている限り、他の例外も同様に機能しますが、その意味が非常に明確であるため、特に適しています!execfileexecfileSystemExit

于 2009-06-22T18:04:03.970 に答える
4
# 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__" など) はいらいらさせられます。

于 2009-06-22T18:02:36.123 に答える
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
于 2009-06-22T20:44:27.600 に答える