Using custom packages on Google-Colaboratory

2019-08-22 11:55发布

问题:

I'm trying to use my custom package on Google Colaboratory and I'm facing some weird errors while doing that. Note that the package I'm trying to use works without any error on my computer/s.

It is a Python 3.6 package called rohan. It is very basic in terms of functionalities.

At first I installed it through pip command (pip install rohan). But I got a ModuleNotFoundError error.

import rohan
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-1-9046ed7b4857> in <module>()
----> 1 import rohan

ModuleNotFoundError: No module named 'rohan'

Then I installed it from the source.

%%bash
git clone https://github.com/rraadd88/rohan.git
cd rohan
pip install -e .

This time, I could import the main module without any error (import rohan). However if I try to import submodule (dandage), I get an ImportError.

from rohan import dandage
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-5-6ea35256170e> in <module>()
----> 1 from rohan import dandage

ImportError: cannot import name 'dandage'

To me, the structure of the the package looks ok.

rohan
├── MANIFEST.in
├── rohan
│   ├── dandage
│   │   ├── subsubmodule
│   │   │   ├── script.py
│   │   │   └── __init__.py
|   |   ├── script.py
|   |   └── __init__.py
|   ├── script.py
│   └── __init__.py
├── setup.cfg
└── setup.py

Source: https://github.com/rraadd88/rohan

Also as I said, the package works very well on my computer/s. So I'm not sure why I'm not able to use it on Colaboratory.

回答1:

You'll need to add the directory where you cloned the repo to sys.path. For example:

!git clone https://github.com/rraadd88/rohan.git
import sys
sys.path.append('/content/rohan')
from rohan import dandage

Here's a complete notebook: https://colab.research.google.com/drive/1LSC_HyfbuOlEn7pfZYAjiOSE1fp6uipl