【问题标题】:Google Colab custom module has no attributeGoogle Colab 自定义模块没有属性
【发布时间】:2019-08-07 04:18:18
【问题描述】:

我想做的是在 Google Colab 的自定义模块中定义一个函数。 我创建了一个 *.py 文件来定义函数。这是

/content/gdrive/My Drive/Colab/myfunc.py

然后我在同一个文件夹中创建了一个 *.ipynb 文件。这是

/content/gdrive/My Drive/Colab/test.ipynb

在myfunc.py中,代码是

def somefunc(a)
  return a*2

在test.ipynb中,代码是

cd /content/gdrive/My\ Drive/Colab
import myfunc
myfunc.somefunc(2)

然后出现错误“AttributeError: module 'myfunc' has no attribute 'somefunc'”

我也用过

   dir(myfunc)

在test.ipynb中,显示

['__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__']

我的函数 'somefunc' 不在属性中!!!

此问题仅发生在 Colab 上。我在我的电脑和在线 Jupyter 笔记本上进行了尝试。它们都工作正常。

PS:不管我把一个空的__init__.py文件放在同一个文件夹下,问题一直存在。

【问题讨论】:

    标签: python python-3.x attributeerror google-colaboratory


    【解决方案1】:

    如果其他人偶然发现此问题,请将您需要的所有内容复制到 /content 级别:

    !cp -r ../drive/MyDrive/Colab .
    

    并从那里使用它们。

    【讨论】:

      【解决方案2】:

      您可能需要调整您的sys.path

      这是一个完整的示例,展示了如何创建模块并将其导入 Colab: https://colab.research.google.com/drive/1PtYW0hZit-B9y4PL978kV2ppJJPhjQua

      我相信,这个例子中你要补充的关键是:

      # Add the local_modules directory to the set of paths
      # Python uses to look for imports.
      import sys
      sys.path.append('local_modules')
      

      您需要将路径从'local_modules' 调整为/content/gdrive/My\ Drive/Colab

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-11-14
        • 1970-01-01
        • 2023-04-06
        • 2019-03-14
        • 1970-01-01
        • 1970-01-01
        • 2023-02-22
        相关资源
        最近更新 更多