Stop execution of a script called with execfile

后端 未结 3 1700
既然无缘
既然无缘 2021-02-07 06:37

Is it possible to break the execution of a Python script called with the execfile function without using an if/else statement? I\'ve tried exit(), but it doesn\'t a

3条回答
  •  旧巷少年郎
    2021-02-07 07:22

    main can wrap the execfile into a try/except block: sys.exit raises a SystemExit exception which main can catch in the except clause in order to continue its execution normally, if desired. I.e., in 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"
    

    and whatever.py can use sys.exit(0) or whatever to terminate its own execution only. Any other exception will work as well as long as it's agreed between the source to be execfiled and the source doing the execfile call -- but SystemExit is particularly suitable as its meaning is pretty clear!

提交回复
热议问题