feat(messenger): 添加install_stdio_hook统一拦截脚本stdout按通道分发
This commit is contained in:
@@ -127,6 +127,31 @@ def send_action_recommendation(title, content, source=None):
|
||||
return send(title=title, content=content, source=source, channel="xmpp")
|
||||
|
||||
|
||||
|
||||
class _MessengerStdout:
|
||||
def __init__(self, orig, script):
|
||||
self.orig = orig
|
||||
self.script = script
|
||||
self.channel = get_channel(script)
|
||||
self._buf = ""
|
||||
def write(self, s):
|
||||
if self.channel in ("xmpp", "both"):
|
||||
self.orig.write(s); self.orig.flush()
|
||||
else:
|
||||
self._buf += s
|
||||
return len(s)
|
||||
def flush(self):
|
||||
if self.channel in ("xmpp", "both"):
|
||||
self.orig.flush()
|
||||
|
||||
|
||||
def install_stdio_hook(script_name=None):
|
||||
"""在脚本入口调用:重定向 stdout 到 messenger 通道控制"""
|
||||
if script_name is None:
|
||||
script_name = os.path.basename(sys.argv[0]) if sys.argv else "mofin"
|
||||
sys.stdout = _MessengerStdout(sys.stdout, script_name)
|
||||
return get_channel(script_name)
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("=== messenger 自测 ===")
|
||||
mapping = _load_script_channels()
|
||||
|
||||
Reference in New Issue
Block a user