If you’ve Apache & Python installed, you can execute your python scripts as CGI programs, which your visitors can access if you host the scripts in a server. You can write your scripts in python (file-name will end with .py) or in perl (extention .pl) or anything else which is compatible.
Step 1 – Write a “Hello, World! ” script in Python
In a text editor, type following code. Give the file name “first.py”
print "Content-type: text/html\n"
print "Hello, world!"
The first line is important – it tells where in our computer Python is available. If you’re using windows, use appropriate location, for example, change the first line to something like:
Step 2 – Put the script in a suitable directory
Important: If you are in Linux, make your file executable! Type:
chmod +x /path/to/your/first.py
- Let’s rename the file to first.py and make it executable, if we’re in Linux.
- Put it in a directory named “cgi-bin” under our document root. Then, the file may be accessed in the web-browser by simply typing: http://localhost/cgi-bin/first.py
Step 3 – Configure Apache2
Next step is to configure Apache so that it treats our file as a CGI program. Go to the directory where your Apache configuration file exists. In Linux, it resides under /etc/apache2/ and the configuration file is httpd.conf
NOTE: If virtual hosts are enabled (normally the are enabled), changing the httpd.conf will have no effect. You may need to edit particular configuration file for the site which is enabled. Go to the sites-enabled directory and open the file which is currently enabled (If you have only the file “default” in your /etc/apache2/sites-enabled directory, you should open this file with your text editor)
NOTE: If you are in windows, and using Wamp, you can simply open the httpd.conf file and make following changes.
Edit the configuration file:
Search for the line: ScriptAlias /cgi-bin/ /whatever-path/ – when you find it, comment out the line: that is add a # in front of the line:
#ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
Then, paste following lines of code:
AddHandler cgi-script .cgi .py
Options +Indexes FollowSymLinks +ExecCGI
Allow from all
If your first.py is in /var/www/cgi-bin/ folder, then replace the first line by <Directory “/var/www/cgi-bin”>
You’re done! Now restart Apache to activate all changes.
If you’re in Linux, open a terminal and enter sudo /etc/init.d/apache2 reload to restart Apache. If you’re using Wamp in Windows, you can restart Apache clicking appropriate icons!
Fire up your web browser, type http://localhost/cgi-bin/first.py and hit Enter…
If you find only the text:
in the page, then congratulations!
If you find any other text than Hello, world!, something went wrong. Check for your mistakes. Ensure that “cgi_module” Apache module is enabled.
You may find this link helpful.