import contextlib
@contextlib.contextmanager
def manage_process(process):
try:
yield process
finally:
for stream in [process.stdout, process.stdin, process.stderr]:
if stream:
stream.close()
process.wait()
Popen objects are supported as context managers via the with statement: on exit, standard file descriptors are closed, and the process is waited for.
这应该能满足你的需要。在
这是来自标准库subprocess.py的相关部分
在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()
您可以只向任何类添加两个自定义方法来实现与
with
语句的兼容性。在对于2.7,您还可以使用^{} :
例如:
^{2}$从python3.2开始,
Popen
是一个上下文管理器。在从docs:
这应该能满足你的需要。在
这是来自标准库
subprocess.py
的相关部分 在Python 3.4中:现在您可以在Python2.7中使用了
^{2}$相关问题 更多 >
编程相关推荐