python實現(xiàn)發(fā)消息提醒功能的常見方法
之前一直以為 python 發(fā)消息,必須依賴第三方庫,比如 plyer。

今天使用AI編寫消息提醒功能,才發(fā)現(xiàn)還可以這樣玩的。
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()
'''
# 執(zhí)行PowerShell腳本
result = subprocess.run(
['powershell', '-Command', ps_script],
capture_output=True,
text=True,
timeout=15
)
python 通過調用 powershell 腳本來讓 powershell 發(fā)送消息,好巧妙啊。
相應的,也可以在 MacOS 和 Linux 環(huán)境這樣發(fā)消息。
def _show_macos_notification(self, title, message):
"""在macOS系統(tǒng)顯示通知"""
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系統(tǒng)顯示通知"""
try:
subprocess.run([
'notify-send',
title,
message
], timeout=5)
except Exception as e:
print(f"顯示Linux通知失敗: {e}")
再配合上一個環(huán)境識別的 API —— platform.system(),完全不依賴第三方,真完美!
知識擴展
用Python實現(xiàn)消息提醒的方式不少,從簡單的桌面彈窗到跨平臺的即時通訊(IM)軟件推送,各有各的適用場景。
我的建議是,日常使用可以優(yōu)先選擇統(tǒng)一通知庫(如Apprise)來提高效率;而工作中,直接使用平臺的官方API往往是更穩(wěn)定、長久的選擇。
桌面通知(Windows / macOS / Linux)
日常開發(fā)或本地測試用很方便,適合腳本運行完成、報錯等場景??缙脚_推薦用 Plyer,僅在Win10/11上可考慮 win10toast。提示:務必從官網獲取證書和詳細操作指南,勿使用不明來源的庫。
示例:使用 Plyer(跨平臺)
from plyer import notification
notification.notify(
title="任務完成",
message="數(shù)據(jù)處理已完成!",
timeout=5 # 通知顯示時長(秒)
)示例:使用 win10toast(僅 Windows)
from win10toast import ToastNotifier
toaster = ToastNotifier()
toaster.show_toast("提醒", "該休息一下啦", duration=10)電子郵件通知
通過 SMTP 發(fā)送郵件,適合不需要即時回復的場景,推薦用于系統(tǒng)告警、日志等。
import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg['Subject'] = '報告生成完畢'
msg['From'] = 'sender@example.com'
msg['To'] = 'receiver@example.com'
msg.set_content('您的月度報告已生成,請查收附件。')
# 以 Gmail 為例,使用 SMTP 發(fā)送
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as server:
server.login('your_email@gmail.com', 'your_password')
server.send_message(msg)手機短信通知
配合 Twilio 等服務商 API,適合驗證碼、重要警報等必須保證接收的場景。
from twilio.rest import Client
account_sid = 'your_account_sid'
auth_token = 'your_auth_token'
client = Client(account_sid, auth_token)
message = client.messages.create(
body='服務器負載過高,請檢查!',
from_='+1234567890', # Twilio 提供的號碼
to='+0987654321' # 你的手機號
)即時通訊機器人(IM)
國內最常用的是釘釘/飛書/企業(yè)微信,國外多用 Slack/Telegram,適合團隊協(xié)作和反饋。
示例:釘釘群機器人
import requests, json
webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=xxx'
data = {"msgtype": "text", "text": {"content": "構建失敗,請檢查日志!"}}
requests.post(webhook_url, json=data)統(tǒng)一通知庫:Apprise
如果你厭倦了為每個平臺寫不同代碼,Apprise 可以讓你一套代碼通吃幾乎所有平臺。
安裝與使用
import apprise
ap = apprise.Apprise()
# 一行代碼接入一個平臺,支持 70+ 服務
ap.add('telegram://bot_token/chat_id')
ap.add('mailto://user:pass@gmail.com')
ap.add('dingtalk://access_token?secret=xxx')
ap.add('slack://token_a/token_b/token_c')
# 一鍵群發(fā)
ap.notify(title='系統(tǒng)通知', body='所有服務運行正常')命令行用法
apprise -t "磁盤告警" -b "根分區(qū)使用率超過90%" "mailto://user:pass@gmail.com"
進階:NotifyAll還有像notifyall這樣的替代庫,提供了條件發(fā)送、延遲發(fā)送等高級功能:
import notifyall
n = notifyall.Notify()
n.add("telegram://bot_token/chat_id")
n.notify_if(cpu_usage > 90, "CPU負載過高!")
n.notify_repeat("這是一個提醒", times=3, interval=300)到此這篇關于python實現(xiàn)發(fā)消息提醒功能的常見方法的文章就介紹到這了,更多相關python消息提醒內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
如何利用Python統(tǒng)計正數(shù)和負數(shù)的個數(shù)
Python檢查數(shù)據(jù)中的正/負數(shù)是一種常見的數(shù)據(jù)處理操作,可以通過編寫代碼來實現(xiàn),下面這篇文章主要給大家介紹了關于如何利用Python統(tǒng)計正數(shù)和負數(shù)的個數(shù)的相關資料,需要的朋友可以參考下2024-05-05
python使用tqdm庫實現(xiàn)循環(huán)打印進度條
tqdm是一個用于在Python中添加進度條的庫,它可以很容易地集成到while循環(huán)中,這篇文章主要介紹了python循環(huán)打印進度條,需要的朋友可以參考下2023-05-05
深入理解Python __init_subclass__的使用
本文主要介紹了Python __init_subclass__的使用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2026-05-05

