python.lang.correctness.exit.use-sys-exit

Community Favorite
profile photo of semgrepsemgrep
Author
38,301
Download Count*

Detected use of exit. Use sys.exit over the python shell exit built-in. exit is a helper for the interactive shell and may not be available on all Python implementations.

Run Locally

Run in CI

Defintion

rules:
  - id: use-sys-exit
    languages:
      - python
    message: Detected use of `exit`. Use `sys.exit` over the python shell `exit`
      built-in. `exit` is a helper for the interactive shell and may not be
      available on all Python implementations.
    patterns:
      - pattern: exit($X)
      - pattern-not: sys.exit($X)
    severity: WARNING
    fix: sys.exit($X)
    metadata:
      category: correctness
      technology:
        - python
      references:
        - https://stackoverflow.com/questions/6501121/difference-between-exit-and-sys-exit-in-python
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

exit.py

import sys

if False:
    # ok: use-sys-exit
    sys.exit(2)

if True:
    # ruleid: use-sys-exit
    exit(3)

def check_db(user):
    if user is None:
        # ruleid: use-sys-exit
        exit(4)
    else:
        print(user)
        # ok: use-sys-exit
        sys.exit(0)

if False:
    # ok: use-sys-exit
    from sys import exit

    exit(0)