u/Henry_Python_RU57

The Awesome Architecture of Google Colab: Backend & Client-Side Execution

Google Colab is far more than just a hosted Python notebook—it's a flexible, dual-environment platform:

1. The Client-Side (Browser Tab) You can leverage HTML, CSS, and JavaScript (or PyScript/WASM) directly inside cell output frames to run local code, render custom UI components like Monaco editors, and build full interactive frontends without touching backend resources. While Colab places sandbox restrictions on certain browser APIs, tools like native <dialog> elements and local JS libraries give you immense flexibility.

2. The Cloud Backend (Linux VM) On the server side, Python and Bash give you full control over Google's Ubuntu environment. Using Bash magic (!), you can install and run virtually any compiled or interpreted language—from C/C++ and Rust to Go, Kotlin, or Node.js.

The Takeaway: When you combine local browser execution with cloud backend processing, you can turn Colab into a hybrid application engine.

Of course it's rare for someone to know that many languages to my understanding most Colab users are python users.

>

reddit.com
u/Henry_Python_RU57 — 1 day ago

Embedding a Full VS Code-Style Monaco Editor Inside Google Colab Outputs

You can embed a fully functional Monaco Editor (the engine behind VS Code) directly inside Google Colab cell outputs using JavaScript and CDN loading.

This gives you local syntax highlighting, line numbers, code folding, and multi-language editing right inside your output frames without spending any Colab CPU or RAM.

    from IPython.display import HTML, display
    display(HTML(r'''
    <head>
    <!--install the library -->
        <script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.46.0/min/vs/loader.min.js"></script> <!-- Monnacco syntax coloring -->
    </head>
    <body>
        <samp style="min-width:1000px;" ondblclick="runCode();">
          <div id="rustCode" style="width: 100%; height: 500px; border: 1px solid #ccc;"></div>
        </samp>
    
    <script>
    const editorRegistry = {'rustCode': null,'goCode':null, 'sandboxJsInput':null, 'sandboxHtmlInput':null};
    
    function lang_linting(lang=`rust`, value=``, id=`rustCode`, theme="vs-dark") {
    require.config({ paths: { 'vs': 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.46.0/min/vs' }});
    // old -> var editor
    require(['vs/editor/editor.main'], function () {
        // This connects Monaco to your HTML div
        editorRegistry[id] = monaco.editor.create(document.getElementById(`${id}`), {
            value: `${value}`, // ex: fn main() {\n\tprintln!("Hello, Rust!")\n}
            language: `${lang.toLowerCase()}`, // ex rust
            theme: 'vs-dark' // Classic "Dark Mode"
        });
        console.log(`Editor '${id}' initialized successfully.`);
    });
    }
    
    const rust_value = `
    #[no_mangle]
    pub fn main() {
        println!("Hello, world!");
    }
    `
    
    try {
      setTimeout(() => {
            lang_linting('rust',`${rust_value}`,'rustCode');
        }, 1);
    } catch (e) {
      console.error(e);
    } finally {
      console.log("Rust editor initialized successfully.");
    }
    
    </script>
    </body>
    
    '''))
    

>Key Capabilities: > * Zero Performance Impact: Renders entirely inside the browser tab's JavaScript thread. > * Custom Language & Themes: Easily change language: 'python' or 'javascript' and set dark/light themes (vs-dark). > * Extracting Code: You can programmatically fetch the written code inside JS via window.editor.getValue().

reddit.com
u/Henry_Python_RU57 — 1 day ago

Using Pyscript to run client-side Python

To run python in the browser.

from IPython.display import HTML, display
display(HTML(r''' # r string to avoid str conflicts
</head>
<script integrity="" type="module" src="https://pyscript.net/releases/2024.1.1/core.js" crossorigin="anonymous"></script> <!-- PyScript Core -->
</head>

<body>
<button id="run_code"> Click me </button>
<hr>
<!-- your dependencies go down here -->
<py-config>
      packages= ["numpy", "pandas","matplotlib","seaborn","scipy","sympy","requests","flask","simpleeval",
       "micropip","keyboard","openpyxl",]
</py-config>
<script type="py">
    from pyscript import display, when, window
    @when("click", "#run_code")
    def run_code():
        print("Printing to the browser console") 
        display("Printing to the ui")
</script>
</body>
'''))

Why this matters:

  • Zero Runtime Overhead: The Python code runs inside your browser tab (via WebAssembly), leaving your Colab Linux instance completely free for heavy backend compute tasks.

  • DOM Manipulation: You can access the browser's document object directly using standard Python code without writing JavaScript.

If your backend Colab runtime disconnects or times out, PyScript keeps running uninterrupted because it executes locally in your browser. I used this exact setup to run one of my own client-side tools locally!

If you want to interact with the DOM but prefer to avoid writing raw JavaScript, PyScript has you covered. Since Google Colab is browser-based, you aren't limited to just Google's Ubuntu backend—you can leverage your own local machine's hardware to create a hybrid local/cloud architecture.

Let me know if you'd like more deep dives on client-side setups or have questions in the comments!

reddit.com
u/Henry_Python_RU57 — 1 day ago

Rendering Custom HTML & CSS Directly in Google Colab Client-Side frontends

You can build custom web interfaces, dashboards, and styled cards directly inside Google Colab cell outputs using standard HTML and CSS.

Here are the two cleanest ways to render frontends in your notebooks:

  1. Using the IPython.display Module (Best for dynamic templates/variables):
from IPython.display import HTML, display
# you can use f strings or .replace() to inject python variables
html_content = f"""
<h1> Header </h1>
"""
display(HTML(html_content))

2. The %%html Cell Magic (Best for static HTML/CSS testing):

%%html
<style>
    .badge {
        background-color: #22c55e;
        color: white;
        padding: 6px 12px;
        border-radius: 9999px;
        font-weight: bold;
    }
</style>

<span class="badge">Active Runtime</span>

You can also embed <script> tags to run custom JavaScript alongside your layout. Combining HTML/CSS with JavaScript lets you build full-fledged web apps directly inside Google Colab cell outputs.

Pro-Tip on Modals: Standard browser popups like alert() and confirm() are blocked inside Colab's iframe sandbox until an explicit user action like rerunning the code cell unlocks permissions. Native HTML <dialog> elements work cleanly around this limitation—they render instantly without restrictions, auto-focus inside the cell output, and give you complete CSS styling control. I Stopped using alert() after adopting <dialog> tags for popups.

reddit.com
u/Henry_Python_RU57 — 1 day ago

Running Javascript locally in Google Colab

To run JavaScript locally in the browser, we have two main options:

  1. The IPython Library Allows you to mix Python and JS logic together within the same workflow:
from IPython.core.display import Javascript
display(Javascript(f"console.log(0);"))
  1. The %%javascript (or %%js) Cell Magic Dedicated whole-cell execution for raw JavaScript:
%%js
console.log(0);

Note: Because this code executes directly inside your browser's V8 engine (the output iframe), the backend Python runtime performance does not affect execution speed.

reddit.com
u/Henry_Python_RU57 — 1 day ago

Running Legacy COBOL in Google Colab with GnuCOBOL

Ever wanted to compile enterprise COBOL code inside a modern Jupyter environment? You can install gnucobol in seconds via apt-get and run standard .cbl programs directly in Colab cell outputs.

1. Install GnuCOBOL:

!apt-get update -y &amp;&amp; !apt-get install -y gnucobol
  1. Write your COBOL program:

    !apt-get update -y && !apt-get install -y gnucobol

  2. Compile and Run:

    Compile to a native executable (-free enables modern free-format COBOL)

    !cobc -free -x -o hello hello.cbl

    cobol was used for punch cards

    Execute binary

    !./hello

reddit.com
u/Henry_Python_RU57 — 1 day ago

Kotlin in Google Colab

You can run Kotlin directly inside Google Colab's Linux runtime without needing heavy custom Jupyter kernels. By installing kotlinc via apt-get, you can compile and execute .kt files using Java’s built-in runtime.

  1. Install the Kotlin compiler:
# install the Kotlin tooling
!apt-get install -y kotlin
  1. Write your source file:
%%writefile HelloWorld.kt
fun main() {
    println("Hello from Kotlin in Colab!");
}
  1. Compile and Run:
#        file name                      name of the new file
!kotlinc HelloWorld.kt -include-runtime -d HelloWorld.jar
!java -jar HelloWorld.jar # run it
reddit.com
u/Henry_Python_RU57 — 1 day ago

Typescript in Google Colab

Node.js is pre-installed so it can run Javascript and it has some support for typescript. No heavy compilation chains.

check version

!node --version

create the file

# Write your TypeScript file

%%writefile app.ts
const greeting: string = "Hello from TypeScript in Colab!";
console.log(greeting);

currently as I post this its version 20.19.0 so this script works better

# Run via tsx runner (no manual tsc build step needed)
!npx -y tsx app.ts

if node is version 22+ try this

!node --experimental-strip-types app.ts
reddit.com
u/Henry_Python_RU57 — 1 day ago

Native C / C++ in Google Colab GCC, G++

You don't need external libraries or custom kernels to compile C or C++ code in Google Colab. The gcc and g++ compilers are pre-installed in Colab's Linux environment out of the box.

Here is a lightweight, zero-setup workflow to compile C++, execute native binaries, and pass output directly back into Python: check version

!g++ --version # or gcc for C

Write the file

%%writefile main.cpp 
#include &lt;iostream&gt;
int main() {
    std::cout &lt;&lt; "Hello from native C++ in Google Colab!" &lt;&lt; std::endl;
    return 0;
}

Compilation and running

!g++ -O3 main.cpp -o main_app # -O3 for max speed !./main_app

  • Bonus: Pass binary output straight into Python variables:

&#8203;

output = !./main\_app 
print(f"Captured C++ Output: {output}")
  • For C code: Just swap %%writefile main.c and use !gcc main.c -o main_app.
reddit.com
u/Henry_Python_RU57 — 1 day ago

Running Go (Golang) in Google Colab — Installation &amp; Code Setup

Unlike Python, Go isn't pre-installed in the default Colab environment, but you can set up the Go compiler in seconds using apt-get.

Here is a quick workflow to install Go, write your source file, and execute it natively:

install the Go compiler

!apt-get update -y &amp;&amp; apt-get install golang-go -y

create your files

%%writefile main.go
package main

import "fmt"

func main() {
    fmt.Println("Hello, World!")
}

# Run directly without keeping a compiled binary
!go run main.go

# Compile into a native binary and execute
!go build main.go
!./main
reddit.com
u/Henry_Python_RU57 — 1 day ago

Java in Google Colab no runtime hacks

The Java compiler is pre-installed.

javac --version

  • create your file in a cell

%%writefile Main.java

public class Main { 
   public static void main(String[] args) { 
      System.out.println("Hello from native Java in Colab!"); 
   } 
}
  • bonus you can set the result equal to a python variable

    result = !java Main print(f"Captured Output: {result}")

reddit.com
u/Henry_Python_RU57 — 1 day ago

Vim is Built-In to Google Colab. Skip %%writefile for Quick Snippets

Vim is pre-installed in Google Colab's underlying Linux environment. I use this over %%writefile when I want to quickly create or test temporary code snippets without cluttering notebook cells.

* Open the terminal (bottom left)

# create file open it in vim
touch main.js &amp;&amp; vim main.js 
  • hit i and for insert/editing mode
  • To exit press esc
  • type :wq and hit enter

&#8203;

# run it I just chose node for this example
node main.js # node pre-installed in Google Colab

You just created a file opened it in vim, saved your changes and exited the program congrats. Did Vim scare you? Let me know in the comments.

reddit.com
u/Henry_Python_RU57 — 1 day ago

True Single-Cell Rust Execution for Google Colab (No Broken Jupyter Kernal)

The Problem: Most guides tell you to install the evcxr kernel to run Rust. While that works on a local Jupyter Notebook, doing it in Google Colab forces a webpage refresh, breaks your active workspace variables, and completely resets every time your Colab runtime disconnects.

🚀 The Cloud-Native Alternative

Now here is the bash code that allows RUST to be run in Google Colab that I rely on so you can use it too just here to help.

!curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs  | sh -s -- -y   # this installs the rust compiler chain



!rustup target add wasm32-unknown-unknown # or what ever target you want



!/root/.cargo/bin/rustup target add wasm32-unknown-unknown



# this sets up the linux enviroment so it can run rust

# now you can create rs files and compile its and run it in colab.

#hope this helps

The second approach I see works is in a notebook that I found, you may have heard of it already.

It installs

# Install dependencies for google colab
import os
import sys

IN_COLAB = "google.colab" in sys.modules
if IN_COLAB:
  %pip install rustimport_jupyter polars==0.20.2 
  !curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y 
  os.environ["PATH"] += ":/root/.cargo/bin" #configs the PATH

loads it

%load_ext rustimport_jupyter

and uses it

%%rustimport
use pyo3::prelude::*;


#[pyfunction]
Code_here

It seems to fail in the last few cells it may be due to a version mismatch with numpy I don't know. It may be a issue with certain libraries but it works great if you want python to be able to call rust functions.

reddit.com
u/Henry_Python_RU57 — 2 days ago