Python: Import custom module in Google Colab

Viewed 869

I'm trying to import a module that I created in Google Colab and use the functions therein in another module.

I've followed the instructions here which seems similar to other instructions, and have the following code:

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

import sys
sys.path.append('/content/drive/MyDrive/python_scripts/')

import myscript
dir(myscript)

I'm unable, however, to see the functions I created, and instead just see the following

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

I can't, then, access any of the functions within this module.

I've also created an __init__py file in the relevant folder, but that hasn't seemed to help.

Any ideas would be great!

Thanks!

Mike

1 Answers

/content folder is a current working directory for Colab notebook execution and I recommend you to copy your scripts repo to /content:

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

!cp -r /content/drive/MyDrive/python_scripts /content

from python_scripts.myscript import smth
smth()

Alternative approach would be adding __init__.py on path from /content to your folder. But I found that /content/drive is read-only, so you cannot add __init__.py there and this "solution" couldn't work:

!cp -rv $path/__init__.py /content/drive
> '/content/drive/MyDrive/script_folder/__init__.py' -> '/content/drive/__init__.py'
> cp: cannot create regular file '/content/drive/__init__.py': Operation not supported
Related