You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python WinRT中获取通知监听器权限?

解决Python WinRT获取UserNotificationListener权限被拒绝的问题

核心原因

UserNotificationListener 要求应用必须声明userNotificationListener权限能力。普通Python脚本属于未打包的桌面应用,没有对应的应用清单声明该能力,因此系统直接拒绝权限请求,不会弹出授权提示。

解决方法:将Python脚本打包为带权限声明的MSIX应用

步骤1:创建应用清单文件

新建Package.appxmanifest文件,填入以下内容:

<?xml version="1.0" encoding="utf-8"?>
<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
         xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
         xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
         IgnorableNamespaces="uap rescap">
  <Identity Name="PythonNotificationListenerApp"
            Publisher="CN=YourName"
            Version="1.0.0.0" />
  <Properties>
    <DisplayName>Python Notification Listener</DisplayName>
    <PublisherDisplayName>YourName</PublisherDisplayName>
    <Logo>Assets\StoreLogo.png</Logo>
  </Properties>
  <Dependencies>
    <TargetDeviceFamily Name="Windows.Desktop" MinVersion="10.0.17763.0" MaxVersionTested="10.0.22621.0" />
  </Dependencies>
  <Resources>
    <Resource Language="en-us" />
  </Resources>
  <Applications>
    <Application Id="PythonApp" Executable="python.exe" EntryPoint="Windows.FullTrustApplication">
      <uap:VisualElements DisplayName="Python Notification Listener"
                          Description="Python app to listen to system notifications"
                          BackgroundColor="#FFFFFF"
                          Square150x150Logo="Assets\Square150x150Logo.png"
                          Square44x44Logo="Assets\Square44x44Logo.png">
        <uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png" />
        <uap:SplashScreen Image="Assets\SplashScreen.png" />
      </uap:VisualElements>
    </Application>
  </Applications>
  <Capabilities>
    <rescap:Capability Name="userNotificationListener" />
    <Capability Name="internetClient" />
  </Capabilities>
</Package>
  • 注意:userNotificationListener属于受限权限,必须通过rescap命名空间声明。

步骤2:打包Python脚本为MSIX包

可以使用两种方式打包:

  • 微软MSIX Packaging Tool:官方可视化工具,按照向导将Python脚本及依赖打包,过程中关联上述清单文件。
  • PyInstaller + MSIX打包:先用PyInstaller将Python脚本打包为独立exe,再用MSIX Packaging Tool将exe打包为MSIX包并关联清单。

步骤3:安装并授权

安装打包好的MSIX应用后,运行时调用request_access_async()会弹出权限授权提示,授权后即可正常使用UserNotificationListener。

临时测试方案(不推荐生产环境)

若仅用于临时测试,可手动在系统设置中授权:

  1. 打开「设置」>「隐私和安全性」>「通知」
  2. 滚动到「通知访问」区域
  3. 找到打包后的应用并开启权限

未打包的Python脚本不会出现在该列表中,此方法仅适用于已打包应用。


内容的提问来源于stack exchange,提问作者Aaron

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 18:00:57