Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to embed a Python interpreter on a website

I am attempting to build an educational coding site, similar to Codecademy, but I am frankly at a loss as to what steps should be taken. Could I be pointed in the right direction in including even a simple python interpreter in a webapp?

like image 243
twoxmachine Avatar asked Jun 29 '12 15:06

twoxmachine


People also ask

Can you embed a Python script in HTML?

It is possible to run embed Python within a HTML document that can be executed at run time.

Can you embed Python?

Embedding provides your application with the ability to implement some of the functionality of your application in Python rather than C or C++. This can be used for many purposes; one example would be to allow users to tailor the application to their needs by writing some scripts in Python.

Can you add Python to a website?

The Python language uses CGI to execute on a Web page. You must import the "cgitb" library for the Python language to execute and display the results in a Web browser. The Python language uses small statements that make it suitable for large or small Web projects.


2 Answers

One option might be to use PyPy to create a sandboxed python. It would limit the external operations someone could do.

Once you have that set up, your website would take the code source, send it over ajax to your webserver, and the server would run the code in a subprocess of a sandboxed python instance. You would also be able to kill the process if it took longer than say 5 seconds. Then you return the output back as a response to the client.

See these links for help on a PyPy sandbox:
http://doc.pypy.org/en/latest/sandbox.html
http://readevalprint.com/blog/python-sandbox-with-pypy.html

To create a fully interactive REPL would be even more involved. You would need to keep an interpreter alive to each client on your server. Then accept ajax "lines" of input and run them through the interp by communicating with the running process, and return the output.

Overall, not trivial. You would need some strong dev skills to do this comfortably. You may find this task a bit daunting if you are just learning.

like image 125
jdi Avatar answered Oct 20 '22 01:10

jdi


There's more to do here than you think.

The major problem is that you cannot let people run arbitrary Python code on your webserver. For example, what happens if they do

import os
os.system("rm -rf *.*")

So clearly you have to run this Python code securely. But then you have the problem of securing Python, which is basically impossible because of how dynamic it is. And so you'll probably have to run the Python shell in a virtual machine, which comes with its own headaches.


Have you seen e.g. http://code.google.com/p/google-app-engine-samples/downloads/detail?name=shell_20091112.tar.gz&can=2&q=?

like image 31
Katriel Avatar answered Oct 20 '22 02:10

Katriel