本地启动http服务器打开html文件

def start_http_server():
    """启动HTTP服务器用于访问"""
    current_dir = Path(__file__).parent
    html_file = current_dir / "web.html"
    
    if not html_file.exists():
        print("错误: 找不到HTML文件")
        return None
    
    try:
        # 启动简单的HTTP服务器
        import http.server
        import socketserver
        
        # 切换到HTML文件所在目录
        os.chdir(current_dir)
        
        # 创建HTTP服务器
        handler = http.server.SimpleHTTPRequestHandler
        httpd = socketserver.TCPServer(("", 8000), handler)
        
        print("🌐 HTTP服务器已启动")
        print(f"📱 手机访问地址: http://[你的电脑IP]:8000/web.html")
        print("💻 本地访问地址: http://localhost:8000/web.html")
        print("按 Ctrl+C 停止HTTP服务器")
        
        return httpd
        
    except Exception as e:
        print(f"启动HTTP服务器失败: {e}")
        return None

上面的代码是在某个后台py文件中的

首先,若后台需要websockets服务,则安装依赖:pip install websockets

然后启动HTTP服务器 (新开一个终端):

   python -m http.server 8000

这里的端口8000、7000任意都可以, python -m http.server 7000

然后在浏览器中打开: `http://localhost:8000/web.html`即可

在浏览器中 127.0.0.1:7000其他html文件也可打开,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值