kg5425
kg5425

Reputation: 469

Google Colab, module not found when running python script

I have a Colab notebook open and have my files cloned from a github repo. I want to run a python script called models.py. In this file, I am using pandas. When I run this line in Colab:

!python3 models.py

I get the following error:

Traceback (most recent call last):
  File "models.py", line 1, in <module>
    import pandas as pd
ModuleNotFoundError: No module named 'pandas'

However, if I run in a cell on Google Colab:

!pip3 list

I find that pandas is indeed installed:

pandas                   0.25.3  

My assumption is that when I run the script, it is not able to see the libraries I have installed but I am unsure how to fix this issue.

If I run:

!which python3

I get:

/usr/local/bin/python3

The python file I am trying to run is under:

/content/my_project/models.py

Should I instead take a different approach to running this file?

Upvotes: 1

Views: 4151

Answers (2)

korakot
korakot

Reputation: 40948

Instead of

!python3 models.py

You can use

%run models.py

Upvotes: 6

jakevdp
jakevdp

Reputation: 86533

In a clean Colab runtime, the location of python 3 is different than what you show in your question:

!which python3
# /usr/bin/python3

It looks like you are installing another Python instance in your VM. To ensure you're using Colab's bundled Python 3 executable, try using

!/usr/bin/python3 models.py

If you actually want to use the new python instance you've installed, you'll have to also install whatever packages you need. For example

!/usr/local/bin/python3 -m pip install pandas

Upvotes: 3

Related Questions