对象破坏和过程

时间:2014-03-20 23:15:09

标签: python multithreading

所以我为Web API编写了一个包装器WebApiSession。创建实例时,将完成登录等操作并创建会话。会话需要保持活动状态,因此构造函数会启动一个单独的进程处理它。方法close()会退出会话并停止进程。理想情况下,我不想要调用close()。相反,我希望在不再需要实例时发生这种情况,即我希望能够删除下面的session.close()调用。这可能吗?

import time
from multiprocessing import Process

class WebApiSession:
    def __init__(self):
        # start session, login etc
        # ...
        # start touch loop
        self.touchLoop = Process(target = self.runTouchLoop)
        self.touchLoop.start()
    def runTouchLoop(self):
        self.touch()
        time.sleep(1)
        self.runTouchLoop()
    def touch(self):
        # touch session
        pass
    def close(self):
        # logout etc
        # ...
        self.touchLoop.terminate()
    def doSomething(self):
        pass

if __name__ == '__main__':
    session = WebApiSession()
    session.doSomething()
    session.close()

1 个答案:

答案 0 :(得分:1)

听起来您可以从实施WebApiSession as a context manager中受益。然后,您可以像处理任何其他"上下文一样对待您的会话​​。具有特殊方法,必须在打开和关闭时调用,如文件或其他连接。它还可以给你额外的奖励,整齐地包装错误等等。

class WebApiSession(object):
    def __init__(self):
        pass # other init stuff here, but don't connect yet.

    def __enter__(self): # entering the context.
        # start session, login, start touch loop
        self.touchLoop = Process(target = self.runTouchLoop)
        self.touchLoop.start()
        return self
    def __exit__(self, exc_type, exc_val, traceback): # leaving the context.
        # Bonus feature: handle exception info here as needed!
        self.close()


if __name__ == '__main__':
    with WebApiSession() as session:
        session.doSomething()