如何在Web服务器的Pyscript中配置自定义Python模块绝对路径并运行
解决Pyscript调用自定义模块的(PY1000)路径错误
问题背景
使用Pyscript在浏览器调用自定义Python模块时,触发错误:(PY1000): Couldn't determine the filename from the path , please supply 'to_file' parameter。服务器存在两种路径结构,尝试多种[[fetch]]配置均无效,需通过绝对路径正常调用模块。
服务器路径结构与对应解决方案
情况1:index.html与example.py同目录
|---https://test.com/lib/python/example/custom/ |---------------------------------------------/index.html |---------------------------------------------/example.py
正确配置方式:
通过to_file参数明确指定虚拟文件系统中的文件名,或使用能被Pyscript识别文件名的路径:
<py-config> [[fetch]] url = "https://test.com/lib/python/example/custom/example.py" to_file = "example.py" </py-config>
或使用同目录相对路径(更简洁):
<py-config> [[fetch]] paths = ["./example.py"] </py-config>
情况2:example.py在子目录py/下
|---https://test.com/lib/python/example/custom/ |---------------------------------------------/index.html |---------------------------------------------/py/example.py
正确配置方式:
同样通过to_file指定文件名,或使用相对路径:
<py-config> [[fetch]] url = "https://test.com/lib/python/example/custom/py/example.py" to_file = "example.py" </py-config>
或相对路径写法:
<py-config> [[fetch]] paths = ["./py/example.py"] </py-config>
核心原因说明
错误的本质是Pyscript无法从你配置的路径中自动解析出目标文件名,因此必须:
- 用
to_file参数显式指定模块保存到虚拟文件系统时的文件名; - 确保
paths中的路径包含明确的文件名(而非模糊的目录或格式错误的URL)。
完整可运行代码示例(以情况1为例)
<html> <head> <script defer src="https://pyscript.net/releases/2022.12.1/pyscript.js"></script> <link rel="stylesheet" href="https://pyscript.net/releases/2022.12.1/pyscript.css"/> </head> <body> <py-config> [[fetch]] url = "https://test.com/lib/python/example/custom/example.py" to_file = "example.py" </py-config> <py-script> import example example.hello() </py-script> </body> </html>
内容的提问来源于stack exchange,提问作者Damir Shaykxutd
相关产品推荐
相关产品推荐

