我想在 Google Colab 中开发网络应用。唯一的问题是您需要连接到本地主机的浏览器才能查看网络应用程序,但 Google colab 笔记本内没有浏览器。
但似乎有办法解决这个问题。例如 run_with_ngrok 是一个用于在 colab/jupyter 笔记本中运行 Flaks 应用程序的库
https://github.com/gstaff/flask-ngrok#inside-jupyter--colab-notebooks
当你使用它时,它会给出一个随机地址,“在http://.ngrok.io上运行”
不知何故,在 Google colab 上运行的网络应用程序正在该地址上运行。
对于 Flask 应用程序来说,这是一个很好的解决方案,但我希望在 Google Colab 上运行一般的 Web 应用程序,而不仅仅是 Flask 应用程序。是否有在 colab/jupyter 笔记本中运行 Web 应用程序的通用方法?
最佳答案
您可以计划在端口上启动服务器,例如端口=8000。找到要使用此方式的 URL。
from google.colab.output import eval_js
print(eval_js("google.colab.kernel.proxyPort(8000)"))
# https://z4spb7cvssd-496ff2e9c6d22116-8000-colab.googleusercontent.com/
然后,启动服务器,例如
!python -m http.server 8000
然后单击上面的第一个链接(而不是 localhost 或 127.0.0.1),它将在新选项卡中打开。
在单元格中显示
您可以在输出部分的 iframe 中显示结果。我把它变成了一个易于调用的函数。
from IPython.display import Javascript
def show_port(port, height=400):
display(Javascript("""
(async ()=>{
fm = document.createElement('iframe')
fm.src = await google.colab.kernel.proxyPort(%s)
fm.width = '95%%'
fm.height = '%d'
fm.frameBorder = 0
document.body.append(fm)
})();
""" % (port, height) ))
现在你可以在后台启动一个web应用程序(这里是http.server)。并将结果显示为其下方的 iframe。
get_ipython().system_raw('python3 -m http.server 8888 &')
show_port(8888)
要停止服务器,您可以调用 ps
并终止该进程。
关于python - 是否有在 Google Colab 上运行 Web 应用程序的通用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59741453/