当前位置:首页>python>才知道python还可以这样发消息提醒的

才知道python还可以这样发消息提醒的

  • 2026-08-26 07:23:15
才知道python还可以这样发消息提醒的

之前一直以为python发消息,必须依赖第三方库,比如plyer

今天使用 AI 编写消息提醒功能,才发现还可以这样玩的。

import subprocessps_script = f'''            Add-Type -AssemblyName System.Windows.Forms            $global:balloon = New-Object System.Windows.Forms.NotifyIcon            $path = (Get-Process -Id $pid).Path            $balloon.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($path)            $balloon.BalloonTipIcon = [System.Windows.Forms.ToolTipIcon]::Info            $balloon.BalloonTipText = '提醒内容'            $balloon.BalloonTipTitle = '提醒标题'            $balloon.Visible = $true            $balloon.ShowBalloonTip(10000)            Start-Sleep -Seconds 10            $balloon.Dispose()            '''# 执行powershell脚本result = subprocess.run(    ['powershell''-Command', ps_script],    capture_output=True,    text=True,    timeout=15)

python通过调用powershell脚本来让powershell发送消息,好巧妙啊。

相应的,也可以在MacOSLinux环境这样发消息。

def _show_macos_notification(self, title, message):    """在macOS系统显示通知"""    try:        script = f'display notification "{message}" with title "{title}"'        subprocess.run(['osascript''-e', script], timeout=5)    except Exception as e:        print(f"显示macOS通知失败: {e}")def _show_linux_notification(self, title, message):    """在Linux系统显示通知"""    try:        subprocess.run([            'notify-send',            title,            message        ], timeout=5)    except Exception as e:        print(f"显示Linux通知失败: {e}")

再配合上一个环境识别的API——platform.system(),完全不依赖第三方,真完美!

好啦,今天就分享这个小技巧,欢迎三连哦!

最新文章

随机文章