在 Google Colab html 中导入外部 JS 脚本

des*_*des 6 html javascript python google-colaboratory

我很难将我的自定义外部 JS 文件导入到 Google Colab。我使用 html + js,遵循以下工作流程:

1 / 进口

from IPython.display import HTML, SVG
from IPython.core.magic import register_cell_magic
Run Code Online (Sandbox Code Playgroud)

2 / 挂载驱动

from google.colab import drive
drive.mount('/content/drive')
Run Code Online (Sandbox Code Playgroud)

3 / html

@register_cell_magic
def dojs(line, src):
  return HTML(f"""
  <canvas id="renderCanvas" touch-action="none" width="1280px" height="720px"></canvas> 
  <script src="content/drive/My Drive/Colab Notebooks/files/testJavascript.js"></script>
  <script>
  {src} 
  </script>
  """)
Run Code Online (Sandbox Code Playgroud)

4 / js

%%dojs
//...trying to use functions from testJavascript.js
Run Code Online (Sandbox Code Playgroud)

也许如何做到这一点真的很简单,但我是 Colab 的新手。我收到“加载资源失败:服务器响应状态为 500 ()”。

Bob*_*ith 0

像这样的线路script src="content/drive...行不通。原因是您的云端硬盘文件存在于执行您的代码的后端虚拟机上。但是,使用<script>标签将由您的浏览器根据当前的基本源进行解析,即colab.research.google.com,它不为您的云端硬盘文件提供服务。

在此处的高级输出示例中,有一些用于提供本地文件的方法:

https://colab.research.google.com/notebooks/snippets/advanced_outputs.ipynb#scrollTo=R8ZvCXC5A0wT