理解Python中sys.exit()||os._exit()||quit()||exit()

  • Preface

    The functions quit(), exit(), sys.exit() and os._exit() have almost same functionality as they raise SystemExit exception by which the Python interpreter exits and no stack traceback is printed.

    When we run a program in Python, we simply execute all the code in file, from top to bottom. Scripts normally exit when the interpreter reaches the end of the file, but we may also call for the program to exit explicitly with the built-in exit functions.

  • quit()

    It works only if the site module is imported so it should not be used in production code.

    Production code means the code is being used by the intended audience in a real-world situation. This function should only be used in the interpreter.

    It raises the SystemExit exception behind the scence.

  • exit()

    exit() is defined in site.py and it works only if the site module is imported so it should be used in the interpreter only.

    It is like a synonym of quit() to make the Python more user-friendly.

    It too gives a message when printed.

  • sys.exit([arg])

    Unlike quit() and exit(), sys.exit() is considered good to be used in production code for the sys module is always avaiable.

    The optional argument arg can be an integer giving the exit or another type of object.

    If it is an integer, ***zero is considered “successful termination”***.

    A string can also be passed to the sys.exit() method.

  • os._exit(n)

    os._exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buffers, etc.

    This method is normally used in child process after os.fork() system call. The standard way to exit the process is sys.exit(n) method.

  • 總結

    exit is a helper for the interactive shell, while the sys.exit is intended for use in programs.

  • References

  1. Geeks for Geeks : Python exit commands: quit(), exit(), sys.exit() and os._exit()
  2. Difference between exit() and sys.exit() in Python
  3. Python101 : Chapter 20 : The sys Module
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章