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
>>>
1
  • 1
    @LydiavanDyke I see, I do not break the script, 'cause I have the exception. And except do nothing and script go on. Thanks. Commented Dec 29, 2020 at 13:12

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.