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

Question:

%%javascript
IPython.OutputArea.prototype._should_scroll = function(lines) {
    return false;
}

%run rl_base.py

I run this giving error saying rl_base.py file not found. I have uploaded the same to gdrive in colab and from the same folder I am running my .ipynb file, containing the above code

Asked By: user2458922

||

Answers:

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

from google.colab import files
files.upload()
Answered By: korakot

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
Answered By: Bernard Swart

It seems necessary to put the .py file’s name in “”
!python "file.py"

Answered By: Hu Xixi

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

Answered By: Ganesh M S
##  1. Check in which directory you are using the command
!ls
##  2.Navigate to the directory where your python script(file.py) is located using the command
%cd path/to/the/python/file
## 3.Run the python script by using the command
!python file.py
Answered By: Samruddhi Chitnis

A way is also using colabcode.. You will have full ssh access with Visual Studio Code editor.

# install colabcode
!pip install colabcode

# import colabcode
from colabcode import ColabCode

# run colabcode with by deafult options.
ColabCode()

# ColabCode has the following arguments:
# - port: the port you want to run code-server on, default 10000
# - password: password to protect your code server from being accessed by someone else. Note that there is no password by default!
# - mount_drive: True or False to mount your Google Drive

!ColabCode(port=10000, password="abhishek", mount_drive=True)

It will prompt you with a link to visual studio code editor with full access to your colab directories.

Here is a simple answer along with a screenshot

  1. Mount the google drive
from google.colab import drive
drive.mount('/content/drive')
  1. Call the py file path
import sys
import os

py_file_location = "/content/drive/MyDrive/Colab Notebooks"
sys.path.append(os.path.abspath(py_file_location))

Call y file in colab otebook

Answered By: Siddhesh Shankar