Search code examples
pythonipythonreadlines

Why can't exit() terminate the program immediately while in the readlines loop?


Part of my program is:

f = open('test.txt')
for line in f.readlines():
    print 'test'
    exit()

Why can't I exit the program immediately when first meet the exit? Instead, my program will exit while the loop has finished.

EDIT

It happened in the interactive mode:

In [1]: f = open('test.txt', 'r')

In [2]: for line in f.readlines():
   ...:     print 'test'
   ...:     exit()
   ...:     
test
test
test
test
test
test

Solution

  • exit in IPython is not the same function as exit in Python. In IPython, exit is an instance of IPython.core.autocall.ExitAutocall:

    In [6]: exit?
    Type:       ExitAutocall
    String Form:<IPython.core.autocall.ExitAutocall object at 0x9f4c02c>
    File:       /data1/unutbu/.virtualenvs/arthur/local/lib/python2.7/site-packages/ipython-0.14.dev-py2.7.egg/IPython/core/autocall.py
    Definition: exit(self)
    Docstring:
    An autocallable object which will be added to the user namespace so that
    exit, exit(), quit or quit() are all valid ways to close the shell.
    Call def:   exit(self)
    
    In [7]: type(exit)
    Out[7]: IPython.core.autocall.ExitAutocall
    

    It's definition looks like this:

    class ExitAutocall(IPyAutocall):
        """An autocallable object which will be added to the user namespace so that
        exit, exit(), quit or quit() are all valid ways to close the shell."""
        rewrite = False
    
        def __call__(self):
            self._ip.ask_exit()
    

    The self._ip.ask_exit() call runs this method:

    def ask_exit(self):
        """ Ask the shell to exit. Can be overiden and used as a callback. """
        self.exit_now = True
    

    So it really does not exit IPython, it just sets a flag to exit when control returns to the IPython prompt.