run python script in apache

How to Run Python Script in Apache Web Server

Apache web server is popularly used by many websites & organizations. Typically, Apache web server is used to run PHP scripts. But sometimes you may need to run python scripts on Apache web server. In this article, we will learn how to run python script in Apache web server.

How to Run Python Script in Apache Web Server

Here are the steps to run python script in Apache web server.

1. Install Python

Download and install python from its website, if you are using Windows. After you download the installer, double click it to run it, you will see a setup wizard. Follow the instructions to install Python. Note the installation location since you will need it later. If you are using Linux, python is already installed by default and you don’t have to do anything.

In Linux, run the following command to get location of python installation

$ locate python

2. Edit Apache Configuration

Open Apache Configuration file in a text editor. Here are the different possible locations of configuration file depending on your operating system.

## Linux

## Windows
C:\Program Files\Apache Group\Apache\conf\httpd. conf

Look for the following line.

Options Indexes FollowSymLinks

Add ExecCGI to this line.

Options Indexes FollowSymLinks ExecCGI

Next, look for the following line.

#AddHandler cgi-script .cgi

Uncomment it by removing # at the beginning of the line.

AddHandler cgi-script .cgi

And add a .py at the end of the line.

AddHandler cgi-script .cgi .py

In order to execute python scripts in Apache, you need to use an Apache module, like CGI module, to run. That is why assign cgi-script module as the handler for .py files (python scripts).

Save and close the file.

3. Restart Apache

Restart Apache server to apply changes.

# Windows
Start -> All Programs -> Apache . . . -> Control Apache Server menu option

# Linux
$ service apache2 restart

4. Run Python Script on Apache

Create a new file and add the following python code in it.

print "Content-type: text/html"
print "<html><head>"
print ""
print "</head><body>"
print "Hello."
print "</body></html>"

Save this file as in htdocs folder under Apache installation directory. Open web browser, and visit apache host (and :port if the port is something other than 80) followed by For example,


You should be able to see ‘Hello.’ message.

In this article, we have learnt how to run python scripts in Apache server. You can use this approach to run other scripts also such as Ruby, Perl in python. The trick is to install & enable the Apache module responsible for executing these scripts.

Also read:

Shell Script to Clear/Delete Log Files
How to Exclude Requests from Apache Log
How to Exclude Requests from NGINX Log
How to Pass Variable via cURL Command
Shell Script to Restart Service If not Running

Leave a Reply

Your email address will not be published.