تنفيذ وقف برنامج نصي دعا مع execfile
-
06-07-2019 - |
سؤال
هل من الممكن للخروج من تنفيذ برنامج نصي بايثون دعا مع وظيفة execfile دون استخدام إذا / بيان آخر؟ لقد حاولت 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();
وأجد هذا الجانب من بيثون (و__name__
== "__main__
"، وما إلى ذلك) غضب.
ما هو الخطأ في معالجة الاستثناء سهل القديمة؟
و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