Google Colab - Executing External Python Files


Advertisements

Suppose, you already have some Python code developed that is stored in your Google Drive. Now, you will like to load this code in Colab for further modifications. In this chapter, we will see how to load and run the code stored in your Google Drive.

Mounting Drive

Tools / Command palette

You will see the list of commands as shown in this screenshot −

Mounting Drive

Type a few letters like “m” in the search box to locate the mount command. Select Mount Drive command from the list. The following code would be inserted in your Code cell.

# Run this cell to mount your Google Drive.
from google.colab import drive
drive.mount('/content/drive')

If you run this code, you will be asked to enter the authentication code. The corresponding screen looks as shown below −

Authentication Code

Open the above URL in your browser. You will be asked to login to your Google account. Now, you will see the following screen −

Google Aaccount

If you grant the permissions, you will receive your code as follows −

Google Sign In

Cut-n-paste this code in the Code cell and hit ENTER. After a while, the drive will be mounted as seen in the screenshot below −

Drive Mounted Enter

Now, you are ready to use the contents of your drive in Colab.

Listing Drive Contents

You can list the contents of the drive using the ls command as follows −

!ls "/content/drive/My Drive/Colab Notebooks"

This command will list the contents of your Colab Notebooks folder. The sample output of my drive contents are shown here −

Greeting.ipynb hello.py LogisticRegressionCensusData.ipynb LogisticRegressionDigitalOcean.ipynb MyFirstColabNotebook.ipynb SamplePlot.ipynb

Running Python Code

Now, let us say that you want to run a Python file called hello.py stored in your Google Drive. Type the following command in the Code cell −

!python3 "/content/drive/My Drive/Colab Notebooks/hello.py"

The contents of hello.py are given here for your reference −

print("Welcome to Howcodex!")

You will now see the following output −

Welcome to Howcodex!

Besides the text output, Colab also supports the graphical outputs. We will see this in the next chapter.

Advertisements