korakot
korakot

Reputation: 40888

How can I run shell (terminal) in Google Colab?

I know that I can call !ls to issue ls command to shell.

But I want features like history or tab-completion.

Is it possible to do so in Google Colab?

Upvotes: 47

Views: 144097

Answers (8)

Prabhudayal Global
Prabhudayal Global

Reputation: 11

ive just beautified the code of korakot, this version updates the working directory too, when you navigate

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)

next cell

#@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"/>
<style>
  #term_demo {
      font-size: 20px;  /* Adjust the font size here */
  }
</style>
<script>
  let currentPath = '{current_path}';

  $('#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];
              
              if (command.startsWith('cd ')) {
                  // Update the current path on 'cd' commands
                  currentPath = await google.colab.kernel.invokeFunction('shell', ['pwd']);
                  currentPath = currentPath.data['application/json'][0].trim();
              }

              this.set_prompt(currentPath + '> ');
              this.echo(new String(out));
          } catch(e) {
              this.error(new String(e));
          }
      } else {
          this.echo('');
      }
  }, {
      greetings: 'Welcome to Colab Shell',
      name: 'colab_demo',
      height: 300,
      prompt: currentPath + '> ',
      onClear: function() {
          this.set_prompt(currentPath + '> ');
      }
  }).css("font-size", "20px"); // Set font size here;
</script>

ss: enter image description here

Upvotes: 1

Zibri
Zibri

Reputation: 9857

The most complete and easy shell:

!pip install git+https://github.com/0wwafa/shell &>/dev/null && echo OK || echo Fail.
from shell import shell
shell(True)

copy the code above in a cell. That's all. enter image description here

Upvotes: -3

Kirmola
Kirmola

Reputation: 37

!sh should work, it doesn't takes commands in asterisk form as mentioned by some people here. Currently working fine as of December 7, 2023

Upvotes: -1

popcorny
popcorny

Reputation: 1936

I just wrote a tool to run xterm in colab. Just three lines of code and you can get an interactive terminal.

!pip install colab-xterm
%load_ext colabxterm
%xterm

If you feel it is useful, please star this project. ⭐️

Screenshot

enter image description here

Upvotes: 48

Kuldeep Singh Sidhu
Kuldeep Singh Sidhu

Reputation: 3856

Google Colab Shell

Free Terminals for everyone
Displays a terminal for Google Colab

https://github.com/singhsidhukuldeep/Google-Colab-Shell

Setup

pip install google-colab-shell

Usage

https://colab.research.google.com/github/singhsidhukuldeep/Google-Colab-Shell/blob/master/Google_Colab_Shell.ipynb

# import the module once
from google_colab_shell import getshell
## Anytime you want to open a terminal

getshell()

getshell(height=400) # custom height of the terminal

IMPORTANT: Make sure getshell is the last command in the cell.

Documentation

Displays a terminal for Google Colab. <3 Google

Make sure this is the last command in the cell.

    Parameters
    ----------
    height : int, default 400
        height of the rendered terminal

    Returns
    -------
    IPython.display.HTML
        Displays the terminal

    Examples
    --------
    >>> getshell()

    >>> getshell(height=400)

https://github.com/singhsidhukuldeep/Google-Colab-Shell

Please Contribute: https://github.com/singhsidhukuldeep/Google-Colab-Shell#todo-want-to-contribute 🙌

Upvotes: 11

Rajan saha Raju
Rajan saha Raju

Reputation: 840

Just type the following. It will spawn a bash session.

!bash

It displays commands in a password format. If you change the input type from password to text using browser dev tools, it will be really helpful.

Upvotes: 19

korakot
korakot

Reputation: 40888

You can use jQuery Terminal Emulator backed with google.colab.kernel.invokeFunction

Here's an example notebook.

The key part is here, where you back it with shell function.

def shell(command):
  return JSON([getoutput(command)])
output.register_callback('shell', shell)

And here's how you use invokeFunction:

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));
}

Here's a screenshot.

enter image description here

Update (7/2020)

I have taken @Anant's answer and add it into my library. Now you can run console easily with just

!pip install kora
from kora import console
console.start()  # and click link

Update (12/2020)

If you subscribe to Colab Pro, terminal is now available. Just click the 'Terminal' icon on the left pane.

Terminal Icon

Upvotes: 62

Anant
Anant

Reputation: 424

Better try this -

  1. Install Teleconsole on Colab, its a package to use terminal over internet -
     !curl https://www.teleconsole.com/get.sh | sh
    
  2. Run below code on colab notebook to use Teleconsole -
     import subprocess as sp
     process = sp.Popen("teleconsole",shell=True,stdin=sp.PIPE,stdout=sp.PIPE,stderr=sp.PIPE)
     for i in range(6):
       print(process.stdout.readline().decode()) 
    
    You should get output something like -
     Starting local SSH server on localhost...
     Requesting a disposable SSH proxy on eu.teleconsole.com for root...
     Checking status of the SSH tunnel...
    
     Your Teleconsole ID: eu88d75d24084905shgdjhjhfgd1934e55c3786438a3
    
     WebUI for this session: 
     https://eu.teleconsole.com/s/88d75d24084905shgdjhjhfgd1934e55c3786438a3
    
  3. Either open the web interface by following the link for accessing the terminal or open a local shell terminal and install Teleconsole using the command -
     curl https://www.teleconsole.com/get.sh | sh
    
    Then use the below code to join the terminal using Teleconsole Id you got in step No. 2-
     teleconsole join <Teleconsole ID>
    

This method can also be tunneled through ssh with some additional steps.

Upvotes: 10

Related Questions