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

如何在PyScript中导入sklearn等机器学习包?解决本地访问报错

在PyScript中导入机器学习包(如scikit-learn)的解决方法

问题描述

我在项目目录中配置了pyscript.toml和main.py文件:

pyscript.toml内容:

name = "scikit-learn and matplotlib"
packages = ["scikit-learn", "matplotlib"]

main.py内容:

import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np
# 从JS导入json数组
from js import arrr

from sklearn.model_selection import train_test_split

导入sklearn后出现错误:

Polyscript: Access to local files
(using [[fetch]] configurations in )
is not available when directly opening a HTML file;
you must use a webserver to serve the additional files.
See <a style = " text -decoration: underline; href= "https://github.com/pyscript
on starting a simple webserver with Python.

核心原因

直接双击打开本地HTML文件时,浏览器的安全限制会阻止PyScript访问本地配置文件(如pyscript.toml)和依赖包资源,必须通过本地Web服务器托管项目文件才能正常加载。

具体解决步骤

  • 启动本地Web服务器
    进入项目目录打开终端,执行对应Python命令启动简易服务器:

    # Python 3.x版本
    python -m http.server 8000
    
    # 若系统默认是Python 2,改用
    python3 -m http.server 8000
    
  • 通过服务器访问页面
    打开浏览器,访问地址 http://localhost:8000/你的HTML文件名.html,此时PyScript可正常读取pyscript.toml并下载安装scikit-learn等依赖包。

  • 验证HTML文件配置
    确保HTML文件正确关联PyScript、main.py和pyscript.toml,示例结构:

    <!DOCTYPE html>
    <html>
      <head>
        <link rel="stylesheet" href="https://pyscript.net/latest/pyscript.css" />
        <script defer src="https://pyscript.net/latest/pyscript.js"></script>
        <py-config src="./pyscript.toml"></py-config>
      </head>
      <body>
        <py-script src="./main.py"></py-script>
      </body>
    </html>
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 11:56:01