Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run python script in webpage

Tags:

python

I'm very new to Python. I just know what Python is. I have created the below code (In Python IDLE):

print "Hi Welcome to Python test page\n"; print "Now it will show a calculation"; print "30+2=";  print 30+2; 

Then I saved this page in my localhost as index.py

I run the script using http://localhost/index.py

But it does not show executed python script. Instead, it showed the above code as HTML. Where is the problem? please anyone tell me how to run a Python file in a webpage?

like image 363
Haren Sarma Avatar asked Sep 18 '11 10:09

Haren Sarma


People also ask

Can you execute Python from HTML?

The new PyScript project lets you embed Python programs directly in HTML pages and execute them within the browser without any server-based requirements.

How do you run a script on a website?

To execute JavaScript in a browser you have two options — either put it inside a script element anywhere inside an HTML document, or put it inside an external JavaScript file (with a . js extension) and then reference that file inside the HTML document using an empty script element with a src attribute.


1 Answers

In order for your code to show, you need several things:

Firstly, there needs to be a server that handles HTTP requests. At the moment you are just opening a file with Firefox on your local hard drive. A server like Apache or something similar is required.

Secondly, presuming that you now have a server that serves the files, you will also need something that interprets the code as Python code for the server. For Python users the go to solution is nowadays mod_wsgi. But for simpler cases you could stick with CGI (more info here), but if you want to produce web pages easily, you should go with a existing Python web framework like Django.

Setting this up can be quite the hassle, so be prepared.

like image 57
Uku Loskit Avatar answered Nov 03 '22 00:11

Uku Loskit