1

Why doesn't exit() stop the script after the first iteration?

In my opinion, it has to stop after the first iteration.

>>> def func(q):
...     def funct(y):
...         try:
...             print(y)
...             exit()
...         except:
...             pass
...     funct(q)
...
>>> a=['1','2','3','4','5','6','7']
>>> for x in a:
...     func(x)
...
1
2
3
4
5
6
7
>>>
Pro
  • 673
  • 2
  • 6
  • 15
  • 1
    @LydiavanDyke I see, I do not break the script, 'cause I have the exception. And `except` do nothing and script go on. Thanks. – Pro Dec 29 '20 at 13:12

2 Answers2

2

try: sys.exit(0) and move it to the scope of the global function

import sys 
def func(q):
    def funct(y):
        try:
            print(y)
        except:
             pass
    funct(q)
    sys.exit(0)

a=['1','2','3','4','5','6','7']
for x in a:
     func(x)

Output: 1
ljuk
  • 701
  • 3
  • 12
2

To answer your question as directly as possible,

Why doesn't exit() stop the script after the first iteration?

Because a bare except will catch BaseException and Exception, and since exit() raises a SystemExit, which is a BaseException subclass, your code will swallow the exception and pass on each iteration.

Note the difference if you catch Exception only, which does not suppress a BaseException:

>>> from sys import exit
>>> 
>>> def func(q):
...     def funct(y):
...         try:
...             print(y)
...             exit()
...         except Exception:
...             pass
...     funct(q)
... 
>>> a = ['1','2','3','4','5','6','7']
>>> for x in a: func(x)
... 
1 # exits
Brad Solomon
  • 38,521
  • 31
  • 149
  • 235