lunes, 21 de diciembre de 2020

How to permanently install a module on Google Colab

 How to permanently install a module on Google Colab


https://ayoolafelix.hashnode.dev/how-to-permanently-install-a-module-on-google-colab-ckixqrvs40su044s187y274tc


Let's do some coding to implement this solution. We'll use Spacy as an example, Spacy is a Python library, used for Natural Language Processing. You can check the documentation at spacy.io, I'm using this module because I've never installed it on my Colab.


  1. 1. Open Google Colab
  2. 2. Mount Google Drive
    import os, sys 
    #to be able to interact with Google Drive's operating system
    from google.colab import drive 
    #drive is a module that allows us use Python to interact with google drive
    drive.mount('/content/gdrive') 
    #mounting google drive allows us to work with its contents
    nb_path = '/content/notebooks'
    os.symlink('/content/gdrive/My Drive/Colab Notebooks', nb_path)
    sys.path.insert(0, nb_path)  # or append(nb_path)
    #The last three lines are what changes the path of the file.
    
  3. 3. Install the module in the notebook folder permanently

    !pip install --target=$nb_path spacy
    

    4. In your case, just change 'spacy' to the name of the module you wish to install.

  4. Import the module to confirm that it has been installed

    import spacy
    

    The bulk of our work is done


Now let's test if the module will be imported if we come back next time. To test this,

  1. 1. Open a new Colab notebook
  2. 2. Try to import the module
import spacy

You should get an error, why? because you haven't switched the path to where the module is located. Let's import it the right way

  1. 1. Mount your Google drive
    from google.colab import drive
    drive.mount('/content/gdrive')
    
  2. 2. Change the path to the directory where the module is located
    import sys
    sys.path.append('/content/gdrive/My Drive/Colab Notebooks')
    
  3. 3. import the module
    import spacy

No hay comentarios:

Publicar un comentario