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

在苹果Sonoma 14.6系统中通过自定义URL协议启动Python应用时捕获启动参数的问题求助

在苹果Sonoma 14.6系统中通过自定义URL协议启动Python应用时捕获启动参数的问题求助

我现在需要实现一个功能:让我的Python应用能通过自定义URL协议(比如MyApp://1234)被唤起,并且捕获URL里的参数(比如这里的1234),把它作为Tornado Web服务器启动时的端口号。

我已经在info.plist里配置好了自定义URL协议,现在应用确实能通过这个协议被唤起,但我始终没办法获取到用户输入的完整URL内容。

我尝试用Apple Events来处理这个逻辑,写了如下代码:

import struct
import re
import base64
import json
from Foundation import NSObject, NSAppleEventManager, signature

class AppDelegate(NSObject):

    def applicationWillFinishLaunching_(self, notification):
        
        try:
            eventclass1 = struct.unpack('>I', b'GURL')
            eventid1 = struct.unpack('>I', b'GURL')

            eventclass2 = struct.unpack('>I', b'WWW!')
            eventid2 = struct.unpack('>I', b'OURL')

            man = NSAppleEventManager.sharedAppleEventManager()
            man.setEventHandler_andSelector_forEventClass_andEventID_(
                self,
                "openURL:withReplyEvent:",
                eventclass1[0],  # Clase de evento (GetURL)
                eventid1[0]   # ID del eventotid[0])
            )

            man.setEventHandler_andSelector_forEventClass_andEventID_(
                self,
                "openURL:withReplyEvent:",
                eventclass2[0],  # Clase de evento (GetURL)
                eventid2[0]   # ID del eventotid[0])
            )


            print('okk')
        except Exception as e:
            print(e)
            
    @signature(b'v@:@@')
    def openURL_withReplyEvent_(self, event, replyEvent):
        print("1")
        keyDirectObject = struct.unpack(">i", "----")[0]
        url = event.paramDescriptorForKeyword_(keyDirectObject).stringValue().decode('utf8')

        urlPattern = re.compile(r"^(.*?)://(.*)$")
        match = urlPattern.match(url)

        schema = match.group(1)
        hier_part = match.group(2)

        strjson = base64.b64decode(hier_part)
        params = json.loads(strjson)

        #t1.start()
        procesa_accion(params)
        #t1.cancel()

但这段代码完全不起作用,我试了很多不同的Apple Event类和ID组合,都没办法触发openURL_withReplyEvent_方法,也不知道到底是方法用错了、事件类/ID组合不对,还是整个处理流程就有问题。

另外我的代码必须是单Python文件,不能调用Swift文件来读取URL;也不能在启动后再让用户输入端口号,因为有一个第三方设备依赖这个URL唤起并传参的逻辑,我没法修改这个设备的行为。

除了Apple Events,我还试过用Selenium和Urllib3来获取URL,但这两个都需要先打开浏览器窗口,不符合我的需求;也考虑过启动后再询问端口,但这个方案也被排除了,原因刚才说过。

我当前的开发环境是macOS Sonoma 14.6,Python版本是3.12。

备注:内容来源于stack exchange,提问作者Zirzeus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 11:03:06