Ensure file handles are always closed

We are seeing a case where an exception is being raised in Popen and we leak a file handle every time that happens.

This fix stops the leaking of file handles