Ensure file handles are always closed

Prevent leaking of file handle when an exception is raised in Popen.

Thanks to Andrew Boot(@bootany)