Python中如何将ngrok.get_tunnels()返回的类对象转为自定义格式隧道URL?
实现方案
1. 修正导入错误
你原有代码的导入语句写法错误,正确导入pyngrok的语句为:
from pyngrok import ngrok
2. 提取隧道URL的完整代码
ngrok.get_tunnels()返回的NgrokTunnel类对象已经封装好了相关属性,不需要手动解析对象打印字符串,直接读取属性即可:
from pyngrok import ngrok # 开启本地5000端口的HTTP隧道 ngrok.connect(5000, "http") # 获取所有已创建的隧道列表 tunnel_list = ngrok.get_tunnels() http_tunnel = "" https_tunnel = "" for tunnel in tunnel_list: # 直接读取隧道的协议和公网URL属性 if tunnel.proto == "https": https_tunnel = tunnel.public_url else: http_tunnel = tunnel.public_url # 按要求格式输出 print(f"HTTP tunnel: {http_tunnel}") print(f"HTTPS tunnel: {https_tunnel}")
属性说明
NgrokTunnel.proto:返回隧道的协议类型,值为http或httpsNgrokTunnel.public_url:返回隧道对应的公网访问地址
内容的提问来源于stack exchange,提问作者kalalua
相关产品推荐
相关产品推荐

