Starting from Python 3.2 Popen is a context manager.
from the docs:
Popen objects are supported as context managers via the with statement: on exit, standard file descriptors are closed, and the process is waited for.
This should do pretty much what you want.
This is the relevant part from subprocess.py from the standard lib
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()
# Wait for the process to terminate, to avoid zombies.
self.wait()
Now you can do 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()
# Wait for the process to terminate, to avoid zombies.
self.wait()
if __name__ == '__main__':
with MyPopen(['ls']) as p:
print(p)
__enter__and__exit__magic methods to usewith.