Question

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
Était-ce utile?

La 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.

Autres conseils

It works just fine for me:

sandbox $ wc -l test.tex
       9 test.tex
sandbox $ python test.py | wc -l
       1

So this probably isn't your actual code.

There's a few reasons that might make you think you're not exiting when you want to however. file.readlines() stores all of the lines in a list. Further file.read* will act like you've hit the end of the file (because you have!).

To iterate over a file line by line, use the idiom:

for line in f:
    do_something_with(line)

Alternatively, use sys.exit. The "builtin" exit function is really only meant to be used interactively. (In fact, it's not a "builtin" at all according to the documentation, so you could definitely get funny behavior from it using different python implementations).

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top