3

I am messing around trying to test a CGI Python script locally on a Windows machine..
I followed a tutorial, so it's pretty simple. Here is my Python script (named test_cgi.py, located in a cgi-bin directory).

print "Content-type: text/html"
print "<html>"
print "<title>Test CGI</title>"
print "<body>"
print "<p>Hello World!</p>"
print "</body>"
print "</html>"

Here is another script that will start the server:

import BaseHTTPServer
import CGIHTTPServer
import cgitb; cgitb.enable()  ## This line enables CGI error reporting

server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", 8000)
handler.cgi_directories = [""]

httpd = server(server_address, handler)
httpd.serve_forever()

After starting the server, when I navigate to http://localhost:8000/test_cgi.py, instead of the browser displaying the HTML contents, it displays the ENTIRE contents of the script. Any ideas?

  1. Yes, all my files have executable permissions.
  2. Yes, I also tried executing python -m CGIHTTPServer from command line.. This starts the server successfully, as does my script. :(
1
  • Aside: Your script has a bug. You need to print a blank line after the "Content-type" line. Commented Dec 5, 2013 at 19:29

3 Answers 3

1

Figured it out -- I was missing the interpreter line at the beginning of my CGI script.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to change handler.cgi_directories to point to the directory containing the cgi script.

Assuming you have stored the file in a folder named cgi-bin, the following should do the trick:

handler.cgi_directories = ['/cgi']

1 Comment

Tried changing to '/cgi' as well as '/cgi-bin' to no avail. :( Still shows entire script.
0

You have started your server with a current working directory of <some-path>\cgi-bin. This doesn't work very will with CGIHTTPServer. Instead, start it from one level higher (i.e. <some-path>).

Also:

  • Don't both setting cgi_directories, the default will work.
  • Point your browser at http://localhost:8000/cgi-bin/test_cgi.py

2 Comments

I did what you said and started this one level higher. I also navigated to the link you suggested, which didn't give me 404 but it's still printing all the contents of the page. This is driving me crazy! Thanks anyway.
IN addition to those two things, you have to not set .cgi_directories.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.