Thursday, March 18, 2010

Python for else block

Found interesting thing in python a "for else" block wow

The else block will get executed if the for is not terminated by a break

            pobj = subprocess.Popen(cmd, bufsize=1024)
            for i in range(4):
                retcode = pobj.poll()
                if retcode is not None:
                    break
                time.sleep(30)
            else:
                try:
                    logger.warn('killing process %d' % pobj.pid)
                    os.kill(pobj.pid, signal.SIGKILL)
                except:
                    logger.exception('Error killing process')