osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

What is the Difference Between quit() and exit() commands in Python?


On 9/16/19, Hongyi Zhao <hongyi.zhao at gmail.com> wrote:
>
> What is the Difference Between quit() and exit() commands in Python?

They're different instances of the Quitter class, which is available
if site.py is imported (i.e. not with the -S command-line option).
They're created by site.setquit():

    def setquit():
        """Define new builtins 'quit' and 'exit'.

        These are objects which make the interpreter exit when called.
        The repr of each object contains a hint at how it works.

        """
        if os.sep == '\\':
            eof = 'Ctrl-Z plus Return'
        else:
            eof = 'Ctrl-D (i.e. EOF)'

        builtins.quit = _sitebuiltins.Quitter('quit', eof)
        builtins.exit = _sitebuiltins.Quitter('exit', eof)

exit(code) or quit(code) closes sys.stdin and raises SystemExit(code):

    >>> quit.__class__
    <class '_sitebuiltins.Quitter'>

    >>> print(inspect.getsource(type(quit)))
    class Quitter(object):
        def __init__(self, name, eof):
            self.name = name
            self.eof = eof
        def __repr__(self):
            return 'Use %s() or %s to exit' % (self.name, self.eof)
        def __call__(self, code=None):
            # Shells like IDLE catch the SystemExit, but listen when their
            # stdin wrapper is closed.
            try:
                sys.stdin.close()
            except:
                pass
            raise SystemExit(code)

For example:

    >>> try:
    ...     quit(42)
    ... except BaseException as e:
    ...     print(repr(e))
    ...
    SystemExit(42,)
    >>> sys.stdin.closed
    True

Alternatively, sys.exit is a builtin function that's equivalent to
`raise SystemExit(code)` but does not close sys.stdin. For example:

    >>> try:
    ...     sys.exit(42)
    ... except BaseException as e:
    ...     print(repr(e))
    ...
    SystemExit(42,)
    >>> sys.stdin.closed
    False