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

冷暖自知 提交于 2020-08-21 19:54:06

问题


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?


回答1:


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.




回答2:


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.




回答3:


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

!bash


来源:https://stackoverflow.com/questions/59318692/how-can-i-run-shell-terminal-in-google-colab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!