#!/usr/bin/python # for linux import sys def main(): print "Content-type: text/html\n" print "Hello World from Python" print "Standard Hello World from a Python CGI Script

" print "well, mostly standard anyways...

" print "This version is a self printing python program that demonstrates how to use python as a CGI script

" print 'This documents my experiences using DreamHost as my hosting provider. Your milage may vary

' print "It is very important that Python CGI scripts..." print "

    " print "
  1. have '!#usr/bin/python' " print "as the first line of the file
    " print "this tells the system what interpreter to use / what language it is.
    " print "This code, using that command, right now, on this host, is using Python %s
    " % sys.version print "For specific versions of Python here at Dreamhost, you could use one of ...
    " print "v2.1.3 -> #!/usr/bin/python2.1
    " print "v2.2.1 -> #!/usr/bin/python2.2
    " print "v2.3.5 -> #!/usr/bin/python2.3
    " print "v2.4.6 -> #!/usr/bin/python2.4
    " print "v2.5.2 -> #!/usr/bin/python2.5
    " print "v2.7.3 -> #!/usr/bin/python2.7
    " print "(noticing a pattern here?)" print "
  2. " print "
  3. end in '.py'
  4. " print "
  5. print the 'Content-type: text/html\\n' header" print " in the first line if you want to view the output
  6. " print "
  7. mark the file as executable: " print "'chmod 755 [filename.py]'
  8. " print "
" print "
" print "This is a self printing file, full source code follows
" print 'Or you could view the source directly ' print 'helloworld.txt' print "
" f = open('helloworld.py') buff = f.readlines() print "
"
	for line in buff:
		# remove trailing newline
		line = line.rstrip()
		# escape less than/greater thans from < > to &lt; &gt; so they are viewable in html
		# side effect: in a web browser it will look like it's doing nothing ;-)
		line = line.replace("<","<")
		line = line.replace(">",">")
		print line
	print "
" print "" if( __name__ == "__main__"): try: main() except: print "Content-type: text/html\n" print "" print "error?" print "" print "There was an error on the page

" print "Notes:
" print " exception handling is your friend
" print " cgitb only works with current versions (>=2.3 ?) of Python
" print " not even an except block can recover from a print " print "without a closing quote - you'll get an error 500 from the server" print "" print ""