Python - 检测我的对象何时写入标准输出? [英] Python - detect when my object is written to stdout?
问题描述
我有一个相当不寻常的要求,我想...我会在解释什么之后再解释原因.
I have a rather unusual request, I think... I'll explain the why after I explain the what.
什么
我想检测我的对象何时写入标准输出,以便我可以在那个时候执行副作用.例如,当我输入:
I want to detect whenever my object is written to stdout, so that I can perform side effects at that time. So, for example, when I type:
sys.stdout.write(instance_of_my_class)
它应该会产生副作用.我已经让我的类成为 str
的子类并覆盖了 __call__
、__unicode__
、__str__
、__repr__
、index
、decode
、encode
、format
、__format__
、__getattribute__
、__getitem__
和 __len__
以便他们每个人都打印一个声明,表明他们已被调用,但似乎 sys.stdout.write
不调用任何这些来打印对象.
it should perform side effects. I've made my class be a subclass of str
and overrode __call__
, __unicode__
, __str__
, __repr__
, index
, decode
, encode
, format
, __format__
, __getattribute__
,__getitem__
, and __len__
so that each of them prints a statement indicating that they've been called, but it seems that sys.stdout.write
calls none of those in order to print an object.
请注意,我专门讨论的是 sys.stdout.write
而不是例如 print
- 我发现 print
对给定的任何内容调用 __str__
.
Note that I'm specifically talking about sys.stdout.write
and not, for example, print
- I have found that print
calls __str__
on whatever it is given.
为什么
此问题从 Windows 中的彩色 Python 提示? 的答案继续关闭.
This question continues from where the answer to Colored Python Prompt in Windows? left off.
我发现python每次需要显示交互提示时,都会调用sys.ps1
和sys.ps2
上的__str__
,然后它保存结果以显示在命令行上.这意味着 sys.ps2.__str__
中的任何副作用都是在 sys.ps1.__str__
中的副作用之后引起的,但我想让这些等到显示的时候sys.ps2
.
I have found that each time python needs to display an interactive prompt, it calls __str__
on sys.ps1
and sys.ps2
, and then it saves the results to be displayed on the command line. This means any side effects in sys.ps2.__str__
are caused right after the ones in sys.ps1.__str__
, but I want to have those wait until it's time to display sys.ps2
.
因此,我没有返回 sys.ps2.__str__
中的 str
,而是返回了 str
的子类,我'我希望在调用 sys.stdout.write
时能够以某种方式捕获它.
So rather than return a str
in sys.ps2.__str__
, I've been returning my subclass of str
, which I'm hoping will somehow be capable of catching when sys.stdout.write
is called on it.
推荐答案
为什么不monkeypatch stdout.write?
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
这篇关于Python - 检测我的对象何时写入标准输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!