Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I install Python packages in Google's Colab?

In a project, I have e.g. two different packages, How can I use the setup.py to install these two packages in the Google's Colab, so that I can import the packages?

like image 266
Lin Jianjie Avatar asked Jul 14 '18 18:07

Lin Jianjie


People also ask

Do I need to install package everytime Google Colab?

The accepted answer is indeed correct, you will need to install your packages to the virtual machine every time you run it.


3 Answers

You can use !setup.py install to do that.

Colab is just like a Jupyter notebook. Therefore, we can use the ! operator here to install any package in Colab. What ! actually does is, it tells the notebook cell that this line is not a Python code, its a command line script. So, to run any command line script in Colab, just add a ! preceding the line.

For example: !pip install tensorflow. This will treat that line (here pip install tensorflow) as a command prompt line and not some Python code. However, if you do this without adding the ! preceding the line, it'll throw up an error saying "invalid syntax".

But keep in mind that you'll have to upload the setup.py file to your drive before doing this (preferably into the same folder where your notebook is).

Hope this answers your question :)

like image 63
Ashutosh Pathak Avatar answered Oct 20 '22 03:10

Ashutosh Pathak


A better, more modern, answer to this question is to use the %pip magic, like:

%pip install scipy

That will automatically use the correct Python version. Using !pip might be tied to a different version of Python, and then you might not find the package after installing it.

And in colab, the magic gives a nice message and button if it detects that you need to restart the runtime if pip updated a packaging you have already imported.

BTW, there is also a %conda magic for doing the same with conda.

like image 62
Doug Blank Avatar answered Oct 20 '22 04:10

Doug Blank


Let's say you want to install scipy. Here is the code to install it:

!pip install scipy
like image 52
Ravi Avatar answered Oct 20 '22 04:10

Ravi