Python Glossary Русский

all Python 3sysfunction

sys.exit()

control

Ends the program. The argument 0 means success, anything non-zero an error. It raises SystemExit.

Syntax

sys.exit([arg])
# arg: None или 0 — успех, другое число — ошибка, строка — в stderr и код 1

SystemExit inherits from BaseException, not Exception, so except Exception lets it through while a bare except: or except BaseException silently swallows the exit and the program keeps running; finally blocks always execute either way. A non-integer argument is printed to stderr and the exit status becomes 1, so sys.exit('file not found') reports a failure, not a clean finish.

Examples

import sys
for code in (0, 1, 'Error!'):
    try:
        sys.exit(code)
    except SystemExit as e:
        print(e.code)  # → 0 / 1 / Error!
print(issubclass(SystemExit, Exception))  # → False — except Exception его не ловит
print(issubclass(SystemExit, BaseException))  # → True

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy