Python - detect when my object is written to stdout?

前端 未结 2 2166
深忆病人
深忆病人 2021-02-20 11:07

I have a rather unusual request, I think... I\'ll explain the why after I explain the what.

What

I want to detect whenever my object is written

2条回答
  •  情深已故
    2021-02-20 11:40

    Why not monkeypatch stdout.write?

    stdoutRegistry = set()
    
    class A(object):
        def __init__(self):
            self.stdoutRegistry.add(self)
    
        def stdoutNotify(self):
            pass
    
    original_stdoutWrite = sys.stdout.write
    def stdoutWrite(*a, **kw):
        if a in stdoutRegistry:
            a.stdoutNotify()
        original_stdoutWrite(*a, **kw)
    sys.stdout.write = stdoutWrite
    

提交回复
热议问题