使用Python的subprocess.Popen时的异常处理

2024-05-16 11:15:25 发布

您现在位置:Python中文网/ 问答频道 /正文

当处理打开的文件时,Python有with语法,它确保文件在离开块时关闭—不管是否有异常等等

with open('foo.txt') as f:
    foo = f.read()

由于进程也是资源,我想知道:在使用Popen时,是否有类似的可能或建议?例如,^{}是否应该在finally子句中运行-假设在进程完成之前我不介意阻塞?在


Tags: 文件txtreadfoo进程aswith语法
3条回答

您可以只向任何类添加两个自定义方法来实现与with语句的兼容性。在

class CustomObject(object):
    def __enter__(self):
        """ This method execudes when entering block. """
        return thing_you_want_to_use

    def __exit__(self, type, value, traceback):
        """ This method execudes on block exit. """
        # Tear things down.

对于2.7,您还可以使用^{}

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()

例如:

^{2}$

从python3.2开始,Popen是一个上下文管理器。在

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.

这应该能满足你的需要。在

这是来自标准库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()

现在您可以在Python2.7中使用了

^{2}$

相关问题 更多 >