Run arbitrary code in a sandboxed environment
This example demonstrates how to run arbitrary code in multiple languages in a Modal Sandbox.
Setting up a multi-language environment
Sandboxes allow us to run any kind of code in a safe environment. We’ll use an image with a few different language runtimes to demonstrate this.
We’ll now create a Sandbox with this image. We’ll also enable output so we can see the image build logs. Note that we don’t pass any commands to the Sandbox, so it will stay alive, waiting for us to send it commands.
Running bash, Python, Node.js, Ruby, and PHP in a Sandbox
We can now use Sandbox.exec to run a few different
commands in the Sandbox.
The output should look something like
We can use multiple languages in tandem to build complex applications. Let’s demonstrate this by piping data between Python and Node.js using bash. Here we generate some random numbers with Python and sum them with Node.js.
For long-running processes, you can use stdout as an iterator to stream the output.
This should print something like
Since Sandboxes are safely separated from the rest of our system, we can run very dangerous code in them!
This command has deleted the entire filesystem, so we can’t run any more commands. Let’s terminate the Sandbox to clean up after ourselves.