How to run a Python script in a '.py' file from a Google Colab notebook? How to run a Python script in a '.py' file from a Google Colab notebook? python python

How to run a Python script in a '.py' file from a Google Colab notebook?


If you have the test.py file in the corresponding folder in drive as in the below attached image, then the command which you use to run the test.py file is as mentioned below,

!python gdrive/My\ Drive/Colab\ Notebooks/object_detection_demo-master/test.py

Additional Info:

If you jusst want to run !python test.py then you should change directory, by the following command before it,

%cd gdrive/My\ Drive/Colab\ Notebooks/object_detection_demo-master/

Folder Structure in Google Drive


When you run your notebook from Google drive, an instance is created only for the notebook. To make the other files in your Google drive folder available you can mount your Google drive with:

from google.colab import drivedrive.mount('/content/gdrive')

Then copy the file you need into the instance with:

!cp gdrive/My\ Drive/path/to/my/file.py .

And run your script:

!python file.py


You should not upload to gdrive. You should upload it to Colab instead, by calling

from google.colab import filesfiles.upload()