如何在Google Colab中导入自定义模块? [英] How to import custom modules in google colab?

查看:808
本文介绍了如何在Google Colab中导入自定义模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为imutils.py的文件,它只有一个定义,即abc(),它返回2个整数的和.

现在,我想在单独的collab文件中使用此定义,但是我无法使用.

我使用的方法是首先将文件imutils.py上传到驱动器,然后将其导入并使用定义.错误提示模块'imutils'没有属性'abc'

要上传,我首先使用了2种方法: 首先,我使用驱动器GUI上传,然后我也使用代码尝试了上述操作.在两种情况下均成功上传

from google.colab import files
files.upload() 

解决方案

如果您的Python文件位于云端硬盘中,则挂载云端硬盘比上传文件要容易得多,例如

from google.colab import drive
drive.mount('/content/gdrive')

然后,如果您有一个模块,则可以像这样导入它:

https://colab.research.google.com/drive/1uvHuizCBqFgvgCfEhK7FvU8JW0A /p>

笔记本的内容如下:

在浏览器中转到以下URL: !ls /content/gdrive/My\ Drive/*.py >>> /content/gdrive/My Drive/mylib.py !cat '/content/gdrive/My Drive/mylib.py' def MyFunction(): print ('My imported function') # We'll need to update our path to import from Drive. import sys sys.path.append('/content/gdrive/My Drive') # Now we can import the library and use the function. import mylib mylib.MyFunction()

I have a file named imutils.py that has just one definition namely abc() which returns the sum of 2 integers.

Now I want to use this definition in a separate collab file but I am unable to.

The method I used was to first upload the file imutils.py to drive and then importing it and using the definition. The error says module 'imutils' has no attribute 'abc'

To upload I first used 2 methods : First I uploaded using the drive GUI and then I also tried the above using the code. Uploading in both cases was successful

from google.colab import files
files.upload() 

解决方案

If your Python file is in Drive, it's likely simpler to mount your Drive than to upload the file, e.g.,

from google.colab import drive
drive.mount('/content/gdrive')

Then, if you have a module, you can import it like so:

https://colab.research.google.com/drive/1uvHuizCBqFgvbCwEhK7FvU8JW0AfxgJw

Contents of the Notebook follow:

Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&scope=email%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdocs.test%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive.photos.readonly%20https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fpeopleapi.readonly&response_type=code

Enter your authorization code:

··········

Mounted at /content/gdrive

I happen to have an existing .py file in Drive.

!ls /content/gdrive/My\ Drive/*.py
>>> /content/gdrive/My Drive/mylib.py

!cat '/content/gdrive/My Drive/mylib.py'

def MyFunction():
    print ('My imported function')

# We'll need to update our path to import from Drive.

import sys
sys.path.append('/content/gdrive/My Drive')

# Now we can import the library and use the function.

import mylib
mylib.MyFunction()

这篇关于如何在Google Colab中导入自定义模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆