Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
441 views
in Technique[技术] by (71.8m points)

python - How to import custom modules in google colab?

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() 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...