54 lines
1.8 KiB
Python
54 lines
1.8 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""非阻塞式 Windows Toast 通知工具。
|
|
|
|
用法:
|
|
python Notify.py "标题(任务事项内容)" ["正文(可选)"]
|
|
|
|
替代旧的阻塞式 `msg *` 弹窗,通知右下角弹出后自动消失,无需手动点击。
|
|
"""
|
|
|
|
import subprocess
|
|
import sys
|
|
|
|
|
|
def SendToast(Title: str, Body: str = ""):
|
|
"""发送一条非阻塞式 Windows Toast 通知(Balloon Tip)。
|
|
|
|
参数:
|
|
Title: 通知标题,即"本次完成的任务事项内容",用于识别是谁完成了什么任务。
|
|
Body: 通知正文,可省略。
|
|
"""
|
|
# 转义 PowerShell 单引号,防止任务内容中的特殊字符破坏脚本
|
|
# BalloonTipText 不能为空,Body 省略时用默认正文
|
|
TitleEsc = Title.replace("'", "''")
|
|
BodyEsc = (Body if Body else "任务完成").replace("'", "''")
|
|
PsScript = (
|
|
"Add-Type -AssemblyName System.Windows.Forms; "
|
|
"Add-Type -AssemblyName System.Drawing; "
|
|
"$n = New-Object System.Windows.Forms.NotifyIcon; "
|
|
"$n.Icon = [System.Drawing.SystemIcons]::Information; "
|
|
"$n.BalloonTipIcon = 'Info'; "
|
|
"$n.BalloonTipTitle = '{0}'; "
|
|
"$n.BalloonTipText = '{1}'; "
|
|
"$n.Visible = $true; "
|
|
"$n.ShowBalloonTip(5000); "
|
|
"Start-Sleep -Milliseconds 6000; "
|
|
"$n.Dispose()"
|
|
).format(TitleEsc, BodyEsc)
|
|
try:
|
|
subprocess.run(
|
|
["powershell", "-NoProfile", "-WindowStyle", "Hidden", "-Command", PsScript],
|
|
check=True,
|
|
timeout=15,
|
|
)
|
|
except Exception as Ex:
|
|
sys.stderr.write("Notify failed: %s\n" % Ex)
|
|
sys.exit(1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) < 2:
|
|
sys.stderr.write("Usage: python Notify.py <Title> [Body]\n")
|
|
sys.exit(2)
|
|
SendToast(sys.argv[1], sys.argv[2] if len(sys.argv) > 2 else "")
|