【问题标题】:Need to restart runtime before import an installed package in Colab在 Colab 中导入已安装的包之前需要重新启动运行时
【发布时间】:2019-09-07 06:10:17
【问题描述】:

我正在尝试在 Google Colab 中安装和使用现有的 python 包。为此,我在 Colab 中从 Github 下载代码并安装包,但是在尝试导入已安装的包时,我收到 ModuleNotFoundError: No module named 'gem' 错误。

但是,如果我重新启动运行时并再次运行导入单元,则不会出现错误。

我想知道为什么我需要在安装包之后和导入之前重新启动运行时。

任何聪明的回应将不胜感激。

我的代码是:

[1] !wget --show-progress --continue -O /content/gem.zip https://github.com/palash1992/GEM/archive/master.zip

[2] !unzip gem.zip

# Installing Dependencies
[3] ! pip install keras==2.0.2

[4] %cd GEM-master
!sudo python3 setup.py install
%cd-

[5] from gem.utils import graph_util, plot_util

我得到的错误是:

ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-5-af270a37878a> in <module>()
      1 import matplotlib.pyplot as plt
      2 
----> 3 from gem.utils import graph_util, plot_util
      4 from gem.evaluation import visualize_embedding as viz
      5 from gem.evaluation import evaluate_graph_reconstruction as gr

ModuleNotFoundError: No module named 'gem'

---------------------------------------------------------------------------
NOTE: If your import is failing due to a missing package, you can
manually install dependencies using either !pip or !apt.

To view examples of installing some common dependencies, click the
"Open Examples" button below.
---------------------------------------------------------------------------

但是,如果我在安装包之后和导入之前使用os.kill(os.getpid(), 9) 重新启动运行时,则不会出现上述错误。

【问题讨论】:

    标签: jupyter-notebook google-colaboratory


    【解决方案1】:

    似乎除了简单的!pip installs 之外的所有内容似乎都没有包含在 colab 的模块注册表中,除非在运行时重新启动之后。很可能,colab 有一种相当幼稚的方式来跟踪可用模块。如果您导入以前安装的包的不同版本,您还必须重新启动运行时。

    可能他们只是有一个脚本,在运行时将piply 安装包的元数据附加到一个类似列表的对象。而imports 只是从列表顶部搜索(这就是为什么不同版本的包需要重新启动的原因)。

    但是,当一个新的运行时启动时,类似列表的注册表会通过搜索相关目录进行初始化和填充。

    【讨论】:

    • 那么除了重启运行时还有其他方法可以解决这个问题吗?
    • 我不知道...也许只是集体从 Colaboratory 向 Google 发送垃圾邮件以“报告错误”或“发送反馈”——呵呵
    【解决方案2】:

    强制重启:

    try:
      from gem.utils import graph_util, plot_util
    except (ImportError, KeyError, ModuleNotFoundError):
      ## code to install gem
      print('Stopping RUNTIME. Colaboratory will restart automatically. Please run again.')
      exit()
    

    基于对Google Colab - How to 'restart runtime' using python code or command line interface? 的多个回答。

    【讨论】:

      猜你喜欢
      • 2020-10-29
      • 2021-05-10
      • 2020-04-13
      • 2016-03-20
      • 1970-01-01
      • 2010-09-19
      • 2012-03-09
      • 1970-01-01
      相关资源
      最近更新 更多