How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage? How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage? python python

How do I create a webpage with buttons that invoke various Python scripts on the system serving the webpage?


This page on the python site has a good description and example of what you need to do to run a python CGI script. Start out with the simplest case first. Just make a short script that prints html.

#!/usr/bin/python                   #on windows change to your path to the python exeprint "Content-Type: text/html"     # HTML is followingprint                               # blank line, end of headersprint "<TITLE>CGI script output</TITLE>"print "<H1>This is my first CGI script</H1>"print "Hello, world!"

When you try this the first time, the hardest part is usually figuring out where to put the script and how to make the web server recognize and run it. If you are using an apache web sever, take a look at these configuration steps.

Once you have this simple script working, you will just need to add an html form and button tag and use the action property to point it to scripts you want to run.


This simple approach requires nothing except Python standard library. Create this directory structure:

.|-- cgi-bin|   `-- script.py|-- index.html`-- server.py

You put your scripts in "cgi-bin" directory, "index.html" contains links to scripts in "cgi-bin" directory (so you don't have to type them manually, although you could), and "server.py" contains this:

import CGIHTTPServerCGIHTTPServer.test()

To run your server, just run "server.py". That's it, no Apache, no other dependencies.

HTH...


All you need is to have it in a directory that is set to execute CGI scripts, then you need to add

#!/usr/bin/env python

to the top, and it should execute the script as a normal python script if you link to it. (like you would a HTML or PHP file)

This, of course, assumes your webserver is set up to execute CGI at all, and that you have a linux system.

There are other, alternative solutions if you want something a bit more fancy, like mod_python and web frameworks like Pylons, but I think the CGI solution would suit your use case better.

[EDIT]

On Windows if you have Apache, you SHOULD be able to use the same method, but replacing the stuff behind the #! with the path to your python.exe, like so:

#!C:\Python25\python.exe -u

The -u is apparently needed to put Python into unbuffered mode according to this link, which also has more indepth info: http://www.imladris.com/Scripts/PythonForWindows.html