Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

%%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

like image 761
user2458922 Avatar asked Jul 05 '18 14:07

user2458922


People also ask

How do I run a .PY file in Google Colab?

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. Now, you are ready to use the contents of your drive in Colab.

Can Google colab open .PY files?

Python script files can also be run on Google colab by a very simple trick. This is a very useful trick, as it enables you to make use of the GPU/TPU provided by Colab to run your . py file. First, you have to create a new notebook or open an existing one.

How do I convert a colab notebook to a Python script?

You need to convert the packages to make it fully python compatible. Simply exporting your colabs (via colabs–> File –> Download.py) into python sctipt.py will results in lines being automatically commented out.


3 Answers

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

like image 98
Ganesh M S Avatar answered Oct 18 '22 00:10

Ganesh M S


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
like image 25
Bernard Swart Avatar answered Oct 17 '22 22:10

Bernard Swart


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

from google.colab import files
files.upload()
like image 9
korakot Avatar answered Oct 18 '22 00:10

korakot