Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Colab - How to 'restart runtime' using python code or command line interface?

Can someone suggest me programatically 'restart runtime'? Any programmatically restarting option is fine, python or CLI (Command Line Interface), without using GUI.

like image 615
Milind Deore Avatar asked Nov 05 '18 12:11

Milind Deore


People also ask

How do I use command prompt with Colab?

It's already possible to run terminal commands in a Colab notebook — all you need to do is prepend an exclamation to the command, or use the %%shell command, but sometimes you might prefer the convenience an interactive shell.

How do I restart and clear output in Colab?

To clear outputs, go to 'EDIT' and 'clear all outputs'. If you want to reset all packages, data files etc. installed, you have got to the runtime as you mentioned.

How do I run a colab code in Python?

To run the code in any cell, you can click the run button on the left side of the code cell (looks like a “play” button with a triangle in a circle) or you can click [shift] + [enter]. The output will appear right below the code cell.


2 Answers

Run a cell with the following code snippet:

import os
os.kill(os.getpid(), 9)

That will kill the current Python runtime process, which will be automatically restarted by the manager.

like image 92
Bob Smith Avatar answered Sep 17 '22 10:09

Bob Smith


To add to Bob's answer - once you kill yourself, there's no going back. So you won't be able to programmatically resume the execution after the self-destruct call.

But you can make it work without changing code - i.e. there's a limited number of reasons to restart (e.g. installing modules, especially if they were imported, switching Tensorflow versions etc.), and in your final run of the notebook, they shouldn't be necessary.

Here's a complete example of installing Detectron2 on top of a notebook about object detection:

%%time
# deps installation
try:
  import detectron2
except ImportError:
  !git clone https://github.com/facebookresearch/detectron2 detectron2_repo
  !pip install -e detectron2_repo
  print('Stopping RUNTIME! Please run again.')
  import os
  os.kill(os.getpid(), 9)
like image 37
Tomasz Gandor Avatar answered Sep 19 '22 10:09

Tomasz Gandor