3 steps to emulate a terminal in Google Colab

Samuel Guedj
2 min readJun 8, 2020

Let’s make it confortable

photo by Anders Jildén on unsplash

A demo is available here. Below the process to emulate a terminal in your Google Colab.

Part 1

Just copy past this code in a cell of your colab and run:

from IPython.display import JSON
from google.colab import output
from subprocess import getoutput
import os
def shell(command):
if command.startswith('cd'):
path = command.strip().split(maxsplit=1)[1]
os.chdir(path)
return JSON([''])
return JSON([getoutput(command)])
output.register_callback('shell', shell)

Part 2

In another cell copy/past/run the following:

#@title Colab Shell
%%html
<div id=term_demo></div>
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery.terminal/js/jquery.terminal.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/jquery.terminal/css/jquery.terminal.min.css" rel="stylesheet"/>
<script>
$('#term_demo').terminal(async function(command) {
if (command !== '') {
try {
let res = await google.colab.kernel.invokeFunction('shell', [command])
let out = res.data['application/json'][0]
this.echo(new String(out))
} catch(e) {
this.error(new String(e));
}
} else {
this.echo('');
}
}, {
greetings: 'Welcome to Colab Shell',
name: 'colab_demo',
height: 250,
prompt: 'colab > '
});

You should be close to that:

Part 3

Hide the code:

and the magic happen

the part on the below is the terminal

Sharing is caring !

--

--