Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I have figured out the problem where I was stuck and I have come up with this solution:-</p> <ol> <li>When I press Ctrl + C (on Windows), the KeyboardInterrupt actually happens in fd.readline(). So, I just placed a try...except there, so that the generator function yields the file descriptor whenever Ctrl + C is hit. If there is no KeyBoardInterrupt , then, just print a newly read line from tempfile</li> <li>This file descriptor is checked using isinstance() in the main body, and if it is found to be a file, then, I'm closing the file as well as the generator</li> </ol> <p><strong>PS</strong>: (this KeyboardInterrupt might vary on Linux..probably SigTerm will be raised, but, please check. So, in order to make the code generic, just remove KeyBoard Interrupt and use just normal except)</p> <pre><code>import sys, traceback filename = 'tempfile' def tail(filename): fd = open(filename) while True: try: line = fd.readline() except KeyboardInterrupt: print 'keyboard interrupt here' yield fd if not line: continue else: yield line try: genObj = tail(filename) valfromgen= genObj.next() while valfromgen: if isinstance(valfromgen, file): print 'Closing this file now as `tail` yielded a file descriptor' valfromgen.close() genObj.close() break print 'Yielded line: ', valfromgen valfromgen= genObj.next() print 'Just in order to check that things are in order, the following line will raise StopIteration. If it raises, it means we are good.' print genObj.next() except: traceback.print_exc() </code></pre> <hr>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload