Starting with Python 3.2, Popen is a context manager.
from docs :
Popen objects are supported as context managers through the with statement: upon exit, the standard file descriptors are closed and the process waits.
This should do pretty much what you want.
This is the corresponding part from subprocess.py from the standard lib library in Python 3.4:
def __enter__(self): return self def __exit__(self, type, value, traceback): if self.stdout: self.stdout.close() if self.stderr: self.stderr.close() if self.stdin: self.stdin.close()
Now you can do it in Python 2.7
from subprocess import Popen class MyPopen(Popen): def __enter__(self): return self def __exit__(self, type, value, traceback): if self.stdout: self.stdout.close() if self.stderr: self.stderr.close() if self.stdin: self.stdin.close()
source share