.py file showing code in browser instead of running

user1104854 picture user1104854 · Apr 12, 2012 · Viewed 24.1k times · Source

I'm trying to get started with Python but can't get my server setup up correctly for localhost(using Ampps). Python is running just fine through IDLE and command line, however, when I open up the file in the browser the code is displayed and not run.

I followed this http://www.imladris.com/Scripts/PythonForWindows.html tutorial for getting cgi set up, but it's not working.

Here's the code for my "hello world" program, if that makes any difference.

#!/usr/bin/env python
# -*#!/usr/bin/python

print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! This is my first CGI program</h2>'
print '</body>'
print '</html>'

Any suggestions?

Answer

Ben Burns picture Ben Burns · Apr 12, 2012

Your web server is treating your python code as a static file rather than an executable. The goal here is that you want Apache to execute python and send the stdout back to the user's browser.

I'm not familiar with Ampps, but the basic Apache flow to getting this setup is something like this.

  1. Edit your Options line of httpd.conf to include ExecCGI
  2. Register your python file with httpd.conf as a cgi handler by adding the following line:
    AddHandler .py
  3. Restart Apache
  4. Be sure that your shebang line (the #!/usr/bin/env python bit on top) actually points at the path to your python executable. For python2.6 living on C:, this might read:
    #!\Python26\python
  5. If your scripts must be portable, instead of modifying the shebang line add the line ScriptInterpreterSource registry to your httpd.conf, and make sure that windows opens *.py files with Python.exe by default. This can be tested by double-clicking a script. If it doesn't execute, right-click it, choose open-with, then other, and then browse to your python.exe. Make sure to check the "always use this program to open files of this type" box. There's a Microsoft Knowledge Base article on this here.

Finally, mod_wsgi or FastCGI is the preferred method for getting Apache to execute python, with the prior holding preference to lower traffic sites (10's of thousands of requests per day). I'd also advise looking into web frameworks such as web.py (very lightweight) or django (heavier weight, but saves you tons of time if you're collecting user input or interfacing with a database).