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文件也可打开,