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

82 阅读1分钟

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

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

import subprocess

ps_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(),完全不依赖第三方,真完美!


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