close

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

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How to run a Python script in a ‘.py’ file from a Google Colab notebook in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

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

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

    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:

  2. run a Python script in a '.py' file from a Google Colab notebook

    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:

Method 1

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

Method 2

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 drive
drive.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

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read