Windows平台Toast通知不显示:股票价格告警程序异常
股价阈值通知程序Toast无法正常显示
我开发了一款当股价突破设定阈值时发送通知的程序,但Toast通知无法正常显示。
测试以下代码时可正常运行:
from winotify import Notification notification = Notification('Test Notification', title='Hello', msg='This is a test notification.') notification.show()
但主程序仅输出股价信息,无法触发Toast通知,主代码如下:
import os import time import yfinance as yf from winotify import Notification, audio tickers = ['AAPL', 'META', 'NVDA', 'GS', 'WFC'] upper_limits = [170, 450, 500, 450, 100] lower_limits = [150, 440, 350, 300, 35] while True: last_prices = [yf.Ticker(ticker).history(period="1d")['Close'].iloc[-1] for ticker in tickers] print(last_prices) time.sleep(1) for i in range(len(tickers)): if last_prices[i] > upper_limits[i]: toast = Notification('Stock Alarm Bot', title='Price Alert ' + tickers[i], msg=f'{tickers[i]} has reached a price of {last_prices[i]}. You might want to sell.', icon=os.path.join(os.getcwd(), 'alert_red.png'), duration='long') toast.add_actions(label='Go To XTB', launch='https://xstation5.xtb.com/?branch=pl&_ga=2.223201755.1920106019.1692334076-2008092090.1692334076&_gl=1*1blay5h*_ga*MjAwODA5MjA5MC4xNjkyMzM0MDc2*_ga_CBPL72L2EC*MTY5MjMzNDA3Ni4xLjEuMTY5MjMzNDA5NS4wLjAuMA..#/_/login') toast.set_audio(audio.LoopingAlarm6, loop=True) toast.show() elif last_prices[i] < lower_limits[i]: toast = Notification('Stock Alarm Bot', title='Price Alert ' + tickers[i], msg=f'{tickers[i]} has reached a price of {last_prices[i]}. You might want to buy.', icon=os.path.join(os.getcwd(), 'alert_green.png'), duration='long') toast.add_actions(label='Go To XTB', launch='https://xstation5.xtb.com/?branch=pl&_ga=2.223201755.1920106019.1692334076-2008092090.1692334076&_gl=1*1blay5h*_ga*MjAwODA5MjA5MC4xNjkyMzM0MDc2*_ga_CBPL72L2EC*MTY5MjMzNDA3Ni4xLjEuMTY5MjMzNDA5NS4wLjAuMA..#/_/login') toast.set_audio(audio.LoopingAlarm8, loop=True) toast.show() time.sleep(1)
问题排查与解决方法
1. 验证图标路径
主程序指定了alert_red.png和alert_green.png作为通知图标,如果当前工作目录下没有这两个文件,会导致winotify无法生成通知:
- 临时测试:注释掉
icon参数,重新运行程序看通知是否弹出 - 彻底解决:确保图标文件存在,或使用绝对路径指定图标位置
2. 降低请求频率避免线程阻塞
主程序每秒请求一次股价数据,频繁的网络IO可能阻塞线程,导致Toast通知无法触发:
- 修改
while True循环中的time.sleep(1)为time.sleep(60)(或更长时间),减少请求频率 - 进阶优化:把股价获取逻辑放到单独线程中执行,避免阻塞通知线程
3. 移除循环音频设置测试
使用loop=True的循环音频可能与通知机制冲突,导致通知无法显示:
- 注释掉
toast.set_audio相关代码,测试通知是否正常弹出
4. 检查Windows通知权限
确保系统允许Python程序发送通知:
- 打开Windows设置 → 系统 → 通知
- 找到Python程序(或对应脚本进程),开启通知权限
5. 格式化价格字符串
msg中的浮点数价格可能存在格式问题,尝试格式化后再传入:
msg=f'{tickers[i]} 价格达到 {last_prices[i]:.2f},建议卖出。'
内容的提问来源于stack exchange,提问作者MichalS
相关产品推荐
相关产品推荐

