Build a stateful, sandboxed code interpreter
This example demonstrates how to build a stateful code interpreter using a Modal Sandbox.
We’ll create a Modal Sandbox that listens for code to execute and then
executes the code in a Python interpreter. Because we’re running in a sandboxed
environment, we can safely use the “unsafe” exec() to execute the code.
Setting up a code interpreter in a Modal Sandbox
Our code interpreter uses a Python “driver program” to listen for code
sent in JSON format to its standard input (stdin), execute the code,
and then return the results in JSON format on standard output (stdout).
We run this driver program in a Modal Sandbox.
We have to convert the driver program to a string to pass it to the Sandbox.
Here we use inspect.getsource to get the source code as a string,
but you could also keep the driver program in a separate file and read it in.
We then kick off the program with Sandbox.exec,
which creates a process inside the Sandbox (see modal.container_process for details).
Running code in a Modal Sandbox
Now we need a way to run code inside that running driver process.
Our driver program already defined a JSON interface on its stdin and stdout,
so we just need to write a quick wrapper to write to the remote stdin and read from the remote stdout.
Now we can execute some code in the Sandbox!
The Sandbox and our code interpreter are stateful, so we can define variables and use them in subsequent code.
We can also see errors when code fails.
Finally, let’s clean up after ourselves and terminate the Sandbox.